From c57b13f1e8202ce704953e8585236b444954c664 Mon Sep 17 00:00:00 2001 From: Benjamin Valentin Date: Tue, 30 May 2023 20:39:10 +0200 Subject: [PATCH] sys/string_utils: add memchk() Check if all bytes in a buffer are set to s certain value - inverse of memset(). --- sys/include/string_utils.h | 12 ++++++++++++ sys/libc/string.c | 13 +++++++++++++ 2 files changed, 25 insertions(+) diff --git a/sys/include/string_utils.h b/sys/include/string_utils.h index b04a148ec9..004e284aaf 100644 --- a/sys/include/string_utils.h +++ b/sys/include/string_utils.h @@ -91,6 +91,18 @@ static inline void explicit_bzero(void *dest, size_t n_bytes) */ ssize_t strscpy(char *dest, const char *src, size_t count); +/** + * @brief Check if the entire buffer is filled with the same byte. + * + * @param[in] data The buffer to probe + * @param[in] c The byte to check of + * @param[in] len Size of the buffer + * + * @return NULL if the entire buffer is filled with @p c + * @return pointer to the first non-matching byte + */ +const void *memchk(const void *data, uint8_t c, size_t len); + #ifdef __cplusplus } #endif diff --git a/sys/libc/string.c b/sys/libc/string.c index c3c1cc661a..7a8b4ba047 100644 --- a/sys/libc/string.c +++ b/sys/libc/string.c @@ -37,4 +37,17 @@ ssize_t strscpy(char *dest, const char *src, size_t count) return -E2BIG; } } + +const void *memchk(const void *data, uint8_t c, size_t len) +{ + const uint8_t *end = (uint8_t *)data + len; + for (const uint8_t *d = data; d != end; ++d) { + if (c != *d) { + return d; + } + } + + return NULL; +} + /** @} */