From: Arran Cudbard-Bell Date: Fri, 17 Jun 2022 21:39:58 +0000 (-0500) Subject: Add functions to concat talloced arrays of strings X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=f82f362003e6ecffc2ddc4b87ff95dd04a436fa7;p=thirdparty%2Ffreeradius-server.git Add functions to concat talloced arrays of strings --- diff --git a/src/lib/util/talloc.c b/src/lib/util/talloc.c index c8a32423731..4b6070cb720 100644 --- a/src/lib/util/talloc.c +++ b/src/lib/util/talloc.c @@ -23,10 +23,11 @@ */ RCSID("$Id$") +#include #include #include +#include #include -#include static TALLOC_CTX *global_ctx; static _Thread_local TALLOC_CTX *thread_local_ctx; @@ -765,6 +766,41 @@ void **talloc_array_null_strip(void **array) return new; } +/** Concat an array of strings (not NULL terminated), with a string separator + * + * @param[out] out Where to write the resulting string. + * @param[in] array of strings to concat. + * @param[in] sep to insert between elements. May be NULL. + * @return + * - >= 0 on success - length of the string created. + * - <0 on failure. How many bytes we would need. + */ +fr_slen_t talloc_array_concat(fr_sbuff_t *out, char const * const *array, char const *sep) +{ + fr_sbuff_t our_out = FR_SBUFF(out); + size_t len = talloc_array_length(array); + char const * const * p; + char const * const * end; + fr_sbuff_escape_rules_t e_rules = { + .name = __FUNCTION__, + .chr = '\\' + }; + + if (sep) e_rules.subs[(uint8_t)*sep] = *sep; + + for (p = array, end = array + len; + (p < end); + p++) { + if (*p) FR_SBUFF_RETURN(fr_sbuff_in_escape, &our_out, *p, strlen(*p), &e_rules); + + if (sep && ((p + 1) < end)) { + FR_SBUFF_RETURN(fr_sbuff_in_strcpy, &our_out, sep); + } + } + + return fr_sbuff_set(out, &our_out); +} + /** Callback to free the autofree ctx on global exit * */ diff --git a/src/lib/util/talloc.h b/src/lib/util/talloc.h index 48c4855b305..0d1a85254b6 100644 --- a/src/lib/util/talloc.h +++ b/src/lib/util/talloc.h @@ -28,9 +28,6 @@ RCSIDH(talloc_h, "$Id$") extern "C" { #endif -#include /* Very easy to miss including in special builds */ -#include -#include #include #include #include @@ -43,6 +40,11 @@ DIAG_OFF(documentation) DIAG_ON(documentation) #endif +#include /* Very easy to miss including in special builds */ +#include +#include +#include + #undef talloc_autofree_context /** The original function is deprecated, so replace it with our version */ @@ -198,6 +200,8 @@ void **talloc_array_null_terminate(void **array); void **talloc_array_null_strip(void **array); +fr_slen_t talloc_array_concat(fr_sbuff_t *out, char const * const *array, char const *sep); + /** Free const'd memory * * @param[in] ptr to free.