summaryrefslogtreecommitdiffstats
path: root/src/dstring.c
diff options
context:
space:
mode:
authorTavian Barnes <tavianator@tavianator.com>2024-10-17 12:23:03 -0400
committerTavian Barnes <tavianator@tavianator.com>2024-10-17 12:23:03 -0400
commitefb24a431007012a31641b25ea2c1857d5d8d803 (patch)
treeff8b87c6424c009c995cc587cb4b357c61041843 /src/dstring.c
parent1520d4d3fe297f34bbbf128ab7c3d1b735fab517 (diff)
downloadbfs-efb24a431007012a31641b25ea2c1857d5d8d803.tar.xz
dstring: Add an infallible dstrshrink() function
And mark the fallible ones with _nodiscard.
Diffstat (limited to 'src/dstring.c')
-rw-r--r--src/dstring.c21
1 files changed, 16 insertions, 5 deletions
diff --git a/src/dstring.c b/src/dstring.c
index af499fd..0f08679 100644
--- a/src/dstring.c
+++ b/src/dstring.c
@@ -46,6 +46,13 @@ static dchar *dstrdata(struct dstring *header) {
return (char *)header + DSTR_OFFSET;
}
+/** Set the length of a dynamic string. */
+static void dstrsetlen(struct dstring *header, size_t len) {
+ bfs_assert(len < header->cap);
+ header->len = len;
+ header->str[len] = '\0';
+}
+
/** Allocate a dstring with the given contents. */
static dchar *dstralloc_impl(size_t cap, size_t len, const char *str) {
// Avoid reallocations for small strings
@@ -59,11 +66,10 @@ static dchar *dstralloc_impl(size_t cap, size_t len, const char *str) {
}
header->cap = cap;
- header->len = len;
+ dstrsetlen(header, len);
- char *ret = dstrdata(header);
+ dchar *ret = dstrdata(header);
memcpy(ret, str, len);
- ret[len] = '\0';
return ret;
}
@@ -121,11 +127,16 @@ int dstresize(dchar **dstr, size_t len) {
}
struct dstring *header = dstrheader(*dstr);
- header->len = len;
- header->str[len] = '\0';
+ dstrsetlen(header, len);
return 0;
}
+void dstrshrink(dchar *dstr, size_t len) {
+ struct dstring *header = dstrheader(dstr);
+ bfs_assert(len <= header->len);
+ dstrsetlen(header, len);
+}
+
int dstrcat(dchar **dest, const char *src) {
return dstrxcat(dest, src, strlen(src));
}