From ae6fbf1d2d5f60edbedd13e2a59795529fd39a81 Mon Sep 17 00:00:00 2001 From: Daniel Verkamp Date: Mon, 21 Nov 2016 13:06:24 -0700 Subject: [PATCH] util: add spdk_strlen_pad() function This is a counterpart to spdk_strcpy_pad() which determines the length of a string in a fixed-size buffer that may be right-padded with a specific character. Change-Id: I2dab8d218ee9d55f7c264daa3956c2752d9fc7f7 Signed-off-by: Daniel Verkamp --- include/spdk/string.h | 11 +++++++++++ lib/util/string.c | 29 +++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/include/spdk/string.h b/include/spdk/string.h index 27c226923..2d4959e17 100644 --- a/include/spdk/string.h +++ b/include/spdk/string.h @@ -92,6 +92,17 @@ char *spdk_str_trim(char *s); */ void spdk_strcpy_pad(void *dst, const char *src, size_t size, int pad); +/** + * Find the length of a string that has been padded with a specific byte. + * + * \param str Right-padded string to find the length of. + * \param size Size of the full string pointed to by str, including padding. + * \param pad Character that was used to pad str up to size. + * + * \return Length of the non-padded portion of str. + */ +size_t spdk_strlen_pad(const void *str, size_t size, int pad); + #ifdef __cplusplus } #endif diff --git a/lib/util/string.c b/lib/util/string.c index fa4e9e366..b5af46a8b 100644 --- a/lib/util/string.c +++ b/lib/util/string.c @@ -34,6 +34,7 @@ #include #include +#include #include #include #include @@ -214,3 +215,31 @@ spdk_strcpy_pad(void *dst, const char *src, size_t size, int pad) memcpy(dst, src, size); } } + +size_t +spdk_strlen_pad(const void *str, size_t size, int pad) +{ + const uint8_t *start; + const uint8_t *iter; + uint8_t pad_byte; + + pad_byte = (uint8_t)pad; + start = (const uint8_t *)str; + + if (size == 0) { + return 0; + } + + iter = start + size - 1; + while (1) { + if (*iter != pad_byte) { + return iter - start + 1; + } + + if (iter == start) { + /* Hit the start of the string finding only pad_byte. */ + return 0; + } + iter--; + } +}