diff --git a/src/string.c b/src/string.c index 0931764..754ca78 100644 --- a/src/string.c +++ b/src/string.c @@ -58,6 +58,28 @@ cfw_strdup(const char *s) return copy; } +char* +cfw_strndup(const char *s, size_t max) +{ + char *copy; + size_t len; + + len = strlen(s); + + if (len > max) + len = max; + + if ((copy = malloc(len + 1)) == NULL) { + errno = ENOMEM; + return NULL; + } + + memcpy(copy, s, len); + copy[len] = 0; + + return copy; +} + static bool ctor(void *ptr, va_list args) { diff --git a/src/string.h b/src/string.h index f00bfb8..87737c8 100644 --- a/src/string.h +++ b/src/string.h @@ -33,6 +33,7 @@ typedef struct CFWString CFWString; extern CFWClass *cfw_string; extern char* cfw_strdup(const char*); +extern char* cfw_strndup(const char*, size_t); extern const char* cfw_string_c(CFWString*); extern size_t cfw_string_length(CFWString*); extern bool cfw_string_set(CFWString*, const char*);