]> git.ipfire.org Git - thirdparty/shadow.git/commitdiff
lib/string/strtok/: strsep2ls(), STRSEP2LS(): Add APIs
authorAlejandro Colomar <alx@kernel.org>
Fri, 6 Dec 2024 21:00:43 +0000 (22:00 +0100)
committerAlejandro Colomar <foss+github@alejandro-colomar.es>
Sat, 7 Jun 2025 14:52:03 +0000 (16:52 +0200)
This API set implements another usual loop around strsep(3).

This one implements a loop where we are interested in an arbitrary
number of fields.  For that, a NULL terminator is added at the end.
That is commonly referred to as "list".

Signed-off-by: Alejandro Colomar <alx@kernel.org>
lib/Makefile.am
lib/string/strtok/strsep2ls.c [new file with mode: 0644]
lib/string/strtok/strsep2ls.h [new file with mode: 0644]

index 93e84f20954a075c630f0bbbab6ffa01da6cee6d..918e77d206bb9b0adaff0950bf33249d192dad40 100644 (file)
@@ -245,6 +245,8 @@ libshadow_la_SOURCES = \
        string/strtok/stpsep.h \
        string/strtok/strsep2arr.c \
        string/strtok/strsep2arr.h \
+       string/strtok/strsep2ls.c \
+       string/strtok/strsep2ls.h \
        strtoday.c \
        sub.c \
        subordinateio.h \
diff --git a/lib/string/strtok/strsep2ls.c b/lib/string/strtok/strsep2ls.c
new file mode 100644 (file)
index 0000000..b7eed18
--- /dev/null
@@ -0,0 +1,14 @@
+// SPDX-FileCopyrightText: 2024, Alejandro Colomar <alx@kernel.org>
+// SPDX-License-Identifier: BSD-3-Clause
+
+
+#include <config.h>
+
+#include "string/strtok/strsep2ls.h"
+
+#include <stddef.h>
+#include <sys/types.h>
+
+
+extern inline ssize_t strsep2ls(char *s, const char *restrict delim,
+    size_t n, char *ls[restrict n]);
diff --git a/lib/string/strtok/strsep2ls.h b/lib/string/strtok/strsep2ls.h
new file mode 100644 (file)
index 0000000..473fe58
--- /dev/null
@@ -0,0 +1,48 @@
+// SPDX-FileCopyrightText: 2024, Alejandro Colomar <alx@kernel.org>
+// SPDX-License-Identifier: BSD-3-Clause
+
+
+#ifndef SHADOW_INCLUDE_LIB_STRING_STRTOK_STRSEP2LS_H_
+#define SHADOW_INCLUDE_LIB_STRING_STRTOK_STRSEP2LS_H_
+
+
+#include <config.h>
+
+#include <errno.h>
+#include <stddef.h>
+#include <sys/types.h>
+
+#include "attr.h"
+#include "sizeof.h"
+#include "string/strtok/strsep2arr.h"
+
+
+#define STRSEP2LS(s, delim, ls)  strsep2ls(s, delim, countof(ls), ls)
+
+
+ATTR_ACCESS(read_write, 1) ATTR_ACCESS(write_only, 4, 3)
+ATTR_STRING(1) ATTR_STRING(2)
+inline ssize_t strsep2ls(char *s, const char *restrict delim,
+    size_t n, char *ls[restrict n]);
+
+
+// string separate to list-of-strings
+// Like strsep2arr(), but add a NULL terminator.
+inline ssize_t
+strsep2ls(char *s, const char *restrict delim, size_t n, char *ls[restrict n])
+{
+       size_t  i;
+
+       i = strsep2arr(s, delim, n, ls);
+       if (i >= n) {
+               errno = E2BIG;
+               return -1;
+       }
+
+       ls[i] = NULL;
+
+       return i;
+}
+
+
+#endif  // include guard