From: Alejandro Colomar Date: Fri, 6 Dec 2024 20:15:10 +0000 (+0100) Subject: lib/string/strtok/: strsep2arr(), STRSEP2ARR(): Add APIs X-Git-Tag: 4.18.0-rc1~13 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=4e64ef699373c32e0336a53f2d6f0718279ddb5b;p=thirdparty%2Fshadow.git lib/string/strtok/: strsep2arr(), STRSEP2ARR(): Add APIs This API set implements the usual loop around strsep(3). This one implements a loop where we are interested in an exact number of fields. I'll add another API set, strsep2ls() and STRSEP2LS(), which will add a NULL terminator, for arbitrary numbers of fields. Signed-off-by: Alejandro Colomar --- diff --git a/lib/Makefile.am b/lib/Makefile.am index 788862d63..93e84f209 100644 --- a/lib/Makefile.am +++ b/lib/Makefile.am @@ -243,6 +243,8 @@ libshadow_la_SOURCES = \ string/strspn/strrspn.h \ string/strtok/stpsep.c \ string/strtok/stpsep.h \ + string/strtok/strsep2arr.c \ + string/strtok/strsep2arr.h \ strtoday.c \ sub.c \ subordinateio.h \ diff --git a/lib/string/strtok/strsep2arr.c b/lib/string/strtok/strsep2arr.c new file mode 100644 index 000000000..775eee203 --- /dev/null +++ b/lib/string/strtok/strsep2arr.c @@ -0,0 +1,14 @@ +// SPDX-FileCopyrightText: 2024, Alejandro Colomar +// SPDX-License-Identifier: BSD-3-Clause + + +#include + +#include "string/strtok/strsep2arr.h" + +#include +#include + + +extern inline ssize_t strsep2arr(char *s, const char *restrict delim, + size_t n, char *a[restrict n]); diff --git a/lib/string/strtok/strsep2arr.h b/lib/string/strtok/strsep2arr.h new file mode 100644 index 000000000..71704727d --- /dev/null +++ b/lib/string/strtok/strsep2arr.h @@ -0,0 +1,52 @@ +// SPDX-FileCopyrightText: 2024, Alejandro Colomar +// SPDX-License-Identifier: BSD-3-Clause + + +#ifndef SHADOW_INCLUDE_LIB_STRING_STRTOK_STRSEP2ARR_H_ +#define SHADOW_INCLUDE_LIB_STRING_STRTOK_STRSEP2ARR_H_ + + +#include + +#include +#include +#include +#include + +#include "attr.h" +#include "sizeof.h" + + +#define STRSEP2ARR(s, delim, a) \ +( \ + strsep2arr(s, delim, countof(a), a) == countof(a) ? 0 : -1 \ +) + + +ATTR_ACCESS(read_write, 1) ATTR_ACCESS(write_only, 4, 3) +ATTR_STRING(1) ATTR_STRING(2) +inline ssize_t strsep2arr(char *s, const char *restrict delim, + size_t n, char *a[restrict n]); + + +// string separate to array-of-strings +// strsep(3) a string into an array of strings. +// Return the number of fields in the string, or -1 on error. +inline ssize_t +strsep2arr(char *s, const char *restrict delim, size_t n, char *a[restrict n]) +{ + size_t i; + + for (i = 0; i < n && s != NULL; i++) + a[i] = strsep(&s, delim); + + if (s != NULL) { + errno = E2BIG; + return -1; + } + + return i; +} + + +#endif // include guard