summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorAlejandro Colomar <alx@kernel.org>2023-01-24 19:23:39 +0100
committerAlejandro Colomar <alx@kernel.org>2023-01-24 19:23:50 +0100
commitbbe3d0e08e7652d26f2d171814b9ba898c16b84d (patch)
tree9d5671bce3f80fa9a2976b31bbc3832a7dd3a7fc
parenta92665fc0e71f356a4cb0781163093f1debb53eb (diff)
Add c_ustr2stpe()
This allows copying with truncation from a measured character sequence to a string. Signed-off-by: Alejandro Colomar <alx@kernel.org>
-rw-r--r--include/c/str/cpy/stp/stpe/ustr2stpe.h49
-rw-r--r--src/c/str/cpy/stp/stpe/ustr2stpe.c13
2 files changed, 62 insertions, 0 deletions
diff --git a/include/c/str/cpy/stp/stpe/ustr2stpe.h b/include/c/str/cpy/stp/stpe/ustr2stpe.h
new file mode 100644
index 0000000..a4424b8
--- /dev/null
+++ b/include/c/str/cpy/stp/stpe/ustr2stpe.h
@@ -0,0 +1,49 @@
+// Copyright 2023 Alejandro Colomar <alx@kernel.org>
+// SPDX-License-Identifier: LGPL-3.0-or-later WITH LGPL-3.0-linking-exception
+
+
+#ifndef INCLUDE_C_STR_CPY_STP_STPE_USTR2STPE_H_
+#define INCLUDE_C_STR_CPY_STP_STPE_USTR2STPE_H_
+
+
+#include <stdbool.h>
+#include <stddef.h>
+#include <sys/param.h>
+
+#include <c/branch/likely.h>
+#include <c/branch/unreachable.h>
+#include <c/mem/cpy/mempcpy.h>
+#include <c/qual/nullable/nullable.h>
+#include <c/str/len/strlen.h>
+
+
+#pragma clang assume_nonnull begin
+inline char *c_nullable c_ustr2stpe(char *c_nullable dst, char *end,
+ const char *restrict src, size_t slen);
+
+
+inline char *c_nullable
+c_ustr2stpe(char *c_nullable dst, char *end, const char *restrict src,
+ size_t slen)
+{
+ bool trunc;
+ size_t dsize, dlen;
+
+ if (dst == end)
+ return end;
+ if (c_unlikely(dst == NULL)) // Allow chaining with stpeprintf().
+ return NULL;
+ c_impossible(dst > end);
+
+ dsize = end - dst;
+ slen = MIN(slen, dsize);
+ trunc = (slen == dsize);
+ dlen = slen - trunc;
+ dst[dlen] = '\0';
+
+ return c_mempcpy(dst, src, dlen) + trunc;
+}
+#pragma clang assume_nonnull end
+
+
+#endif // Header guard
diff --git a/src/c/str/cpy/stp/stpe/ustr2stpe.c b/src/c/str/cpy/stp/stpe/ustr2stpe.c
new file mode 100644
index 0000000..a7df817
--- /dev/null
+++ b/src/c/str/cpy/stp/stpe/ustr2stpe.c
@@ -0,0 +1,13 @@
+// Copyright 2023 Alejandro Colomar <alx@kernel.org>
+// SPDX-License-Identifier: LGPL-3.0-or-later WITH LGPL-3.0-linking-exception
+
+
+#include <c/str/cpy/stp/stpe/ustr2stpe.h>
+
+#include <c/qual/nullable/nullable.h>
+
+
+#pragma clang assume_nonnull begin
+extern inline char *c_nullable c_ustr2stpe(char *c_nullable dst, char end[0],
+ const char *restrict src, size_t slen);
+#pragma clang assume_nonnull end