summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorTavian Barnes <tavianator@tavianator.com>2019-09-03 17:07:58 -0400
committerTavian Barnes <tavianator@tavianator.com>2019-09-03 17:11:12 -0400
commitf7f1e3cfa25cf95e15bac30e6934d5a534ceca08 (patch)
treec5a15638ad3f26909114495bb43dcb62cf999ebd
parent325b37b290dda53392a22c7f2ef802f581e4232d (diff)
downloadbfs-f7f1e3cfa25cf95e15bac30e6934d5a534ceca08.tar.xz
dstring: New dstrndup() function
-rw-r--r--dstring.c10
-rw-r--r--dstring.h10
2 files changed, 19 insertions, 1 deletions
diff --git a/dstring.c b/dstring.c
index d7ce456..8b226bc 100644
--- a/dstring.c
+++ b/dstring.c
@@ -49,7 +49,10 @@ static char *dstralloc_impl(size_t capacity, size_t length, const char *data) {
header->capacity = capacity;
header->length = length;
- return memcpy(header->data, data, length + 1);
+
+ memcpy(header->data, data, length);
+ header->data[length] = '\0';
+ return header->data;
}
char *dstralloc(size_t capacity) {
@@ -61,6 +64,11 @@ char *dstrdup(const char *str) {
return dstralloc_impl(len, len, str);
}
+char *dstrndup(const char *str, size_t n) {
+ size_t len = strnlen(str, n);
+ return dstralloc_impl(len, len, str);
+}
+
size_t dstrlen(const char *dstr) {
return dstrheader(dstr)->length;
}
diff --git a/dstring.h b/dstring.h
index 22476b9..19fd6d7 100644
--- a/dstring.h
+++ b/dstring.h
@@ -41,6 +41,16 @@ char *dstralloc(size_t capacity);
char *dstrdup(const char *str);
/**
+ * Create a length-limited dynamic copy of a string.
+ *
+ * @param str
+ * The string to copy.
+ * @param n
+ * The maximum number of characters to copy from str.
+ */
+char *dstrndup(const char *str, size_t n);
+
+/**
* Get a dynamic string's length.
*
* @param dstr