diff options
| author | Carlos Maiolino <[email protected]> | 2026-03-08 13:34:34 +0100 |
|---|---|---|
| committer | Carlos Maiolino <[email protected]> | 2026-03-08 13:47:28 +0100 |
| commit | 5ba10e3ee774602e20553091568551e210731fbb (patch) | |
| tree | 09250320a20ce832b7e6b831270503fb3c099f13 | |
| parent | 525d3163a541c3553d88acc5cc2db4cc58b5b42d (diff) | |
add strncpy helper
Also fix a off by one bug in strnlen
Signed-off-by: Carlos Maiolino <[email protected]>
| -rw-r--r-- | src/include/toxic/string.h | 1 | ||||
| -rw-r--r-- | src/lib/string.c | 17 |
2 files changed, 17 insertions, 1 deletions
diff --git a/src/include/toxic/string.h b/src/include/toxic/string.h index b43942b..0aedb0b 100644 --- a/src/include/toxic/string.h +++ b/src/include/toxic/string.h @@ -10,6 +10,7 @@ bool isdigit(char c); size_t strlen(const char *s); size_t strnlen(const char *s, size_t maxlen); char *strcpy(char *restrict dst, const char *restrict src); +char *strncpy(char *restrict dst, const char *restrict src, size_t dsize); int strncmp(const char *s1, const char *s2, size_t n); void *memset(void *s, int c, size_t n); diff --git a/src/lib/string.c b/src/lib/string.c index d50435f..8ebf64c 100644 --- a/src/lib/string.c +++ b/src/lib/string.c @@ -20,7 +20,7 @@ size_t strnlen(const char *s, size_t maxlen) { size_t c = 0; - while (c <= maxlen && s[c]) + while (c < maxlen && s[c]) c++; return c; @@ -37,6 +37,21 @@ char *strcpy(char *restrict dst, const char *restrict src) return dst; } +char *strncpy(char *restrict dst, const char *restrict src, size_t dsize) +{ + size_t pos = 0; + + for(pos = 0; pos < dsize && src[pos] != '\0'; pos++) + dst[pos] = src[pos]; + + while (pos < dsize) { + dst[pos] = '\0'; + pos++; + } + + return dst; +} + int strncmp(const char *s1, const char *s2, size_t n) { int i = 0; |
