summaryrefslogtreecommitdiffstats
path: root/dstring.c
diff options
context:
space:
mode:
authorTavian Barnes <tavianator@tavianator.com>2019-03-27 22:45:01 -0400
committerTavian Barnes <tavianator@tavianator.com>2019-03-27 23:14:13 -0400
commit1d2bdf995af658209f5fb63fc42c825411d8da9e (patch)
treec38d9d0774ccf16a0b63b9eab5fa6ddd93808c19 /dstring.c
parentce5be644a16b3e4e7fdba0e0e4537daf3da70676 (diff)
downloadbfs-1d2bdf995af658209f5fb63fc42c825411d8da9e.tar.xz
dstring: Add a dstrdup() function
Diffstat (limited to 'dstring.c')
-rw-r--r--dstring.c19
1 files changed, 14 insertions, 5 deletions
diff --git a/dstring.c b/dstring.c
index 10e1557..35ea5b2 100644
--- a/dstring.c
+++ b/dstring.c
@@ -1,6 +1,6 @@
/****************************************************************************
* bfs *
- * Copyright (C) 2016-2017 Tavian Barnes <tavianator@tavianator.com> *
+ * Copyright (C) 2016-2019 Tavian Barnes <tavianator@tavianator.com> *
* *
* Permission to use, copy, modify, and/or distribute this software for any *
* purpose with or without fee is hereby granted. *
@@ -37,16 +37,25 @@ static size_t dstrsize(size_t capacity) {
return sizeof(struct dstring) + capacity + 1;
}
-char *dstralloc(size_t capacity) {
+/** Allocate a dstring with the given contents. */
+static char *dstralloc_impl(size_t capacity, size_t length, const char *data) {
struct dstring *header = malloc(dstrsize(capacity));
if (!header) {
return NULL;
}
header->capacity = capacity;
- header->length = 0;
- header->data[0] = '\0';
- return header->data;
+ header->length = length;
+ return memcpy(header->data, data, length + 1);
+}
+
+char *dstralloc(size_t capacity) {
+ return dstralloc_impl(capacity, 0, "");
+}
+
+char *dstrdup(const char *str) {
+ size_t len = strlen(str);
+ return dstralloc_impl(len, len, str);
}
size_t dstrlen(const char *dstr) {