commit 75182685b04a5dc38c56a843ca8533ec7b45a5dd
parent 9428eda2a8af49da2fe210a7f5f7283afb1c10e8
Author: Louis Burda <quent.burda@gmail.com>
Date: Wed, 31 May 2023 23:47:28 +0200
Add str_ndup
Diffstat:
4 files changed, 11 insertions(+), 4 deletions(-)
diff --git a/include/str.h b/include/str.h
@@ -18,4 +18,5 @@
char *str_fmt(const struct allocator *allocator, int *rc, const char *fmstr, ...);
char *str_dup(const struct allocator *allocator, int *rc, const char *str);
+char *str_ndup(const struct allocator *allocator, int *rc, const char *str, size_t n);
char *str_app(const struct allocator *allocator, int *rc, char *str, const char *app);
diff --git a/libstr.api b/libstr.api
@@ -1,3 +1,4 @@
str_fmt
str_dup
+str_ndup
str_app
diff --git a/libstr.lds b/libstr.lds
@@ -2,6 +2,7 @@ LIBSTR_1.0 {
global:
str_fmt;
str_dup;
+ str_ndup;
str_app;
local: *;
};
diff --git a/src/str.c b/src/str.c
@@ -41,18 +41,22 @@ str_fmt(const struct allocator *allocator, int *rc, const char *fmtstr, ...)
char *
str_dup(const struct allocator *allocator, int *rc, const char *str)
{
- size_t len;
+ return str_ndup(allocator, rc, str, strlen(str));
+}
+
+char *
+str_ndup(const struct allocator *allocator, int *rc, const char *str, size_t n)
+{
char *nstr;
LIBSTR_ABORT_ON_ARGS(!allocator || !str);
- len = strlen(str);
- nstr = allocator->alloc(allocator, len + 1, rc);
+ nstr = allocator->alloc(allocator, n + 1, rc);
LIBSTR_ABORT_ON_ALLOC(!nstr);
if (!nstr && rc) *rc = -*rc;
if (!nstr) return NULL;
- strncpy(nstr, str, len + 1);
+ strncpy(nstr, str, n + 1);
return nstr;
}