diff --git a/include/ucore/string.h b/include/ucore/string.h index 4225a2a..7914f01 100644 --- a/include/ucore/string.h +++ b/include/ucore/string.h @@ -101,6 +101,18 @@ char * uc_human_bytesz_dec(uint64_t bytes, char *result, size_t result_len); //(base 2 ,1 KiB == 1024 bytes) char * uc_human_bytesz_bin(uint64_t bytes, char *result, size_t result_len); +/** Copy a C string ensuring dst is nul terminated. + * If @max is 0, no action is done + * src must be a nul terminated string + * + * @param dst destination buffer + * @param src source string + * @maram max max chars (including nul terminator to copy). This should + * is normally the size of the dst buffer) + * return strlen(src) which may be larger than the no. of bytes copied. + */ +size_t uc_strlcpy(char *dst, const char *src, size_t max); + #ifdef __cplusplus } #endif diff --git a/src/strlcpy.c b/src/strlcpy.c new file mode 100644 index 0000000..dc67290 --- /dev/null +++ b/src/strlcpy.c @@ -0,0 +1,17 @@ +#include + +size_t uc_strlcpy(char *dst, const char *src, size_t max) +{ + size_t len = strlen(src); + + if (max != 0) { + if (len >= max) { + memcpy(dst, src, max - 1); + dst[max - 1] = 0; + } else { + memcpy(dst, src, len + 1); + } + } + + return len; +}