Commit ae6fbf1d authored by Daniel Verkamp's avatar Daniel Verkamp Committed by Ben Walker
Browse files

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: default avatarDaniel Verkamp <daniel.verkamp@intel.com>
parent 5c146a19
Loading
Loading
Loading
Loading
+11 −0
Original line number Diff line number Diff line
@@ -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
+29 −0
Original line number Diff line number Diff line
@@ -34,6 +34,7 @@

#include <stdarg.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
@@ -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--;
	}
}