aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/core/support
diff options
context:
space:
mode:
authorGravatar David Garcia Quintas <dgq@google.com>2015-07-07 15:41:52 -0700
committerGravatar David Garcia Quintas <dgq@google.com>2015-07-07 16:06:57 -0700
commitb7541e8eea1c5a6f4676e79fa3cd2f40a78a49d0 (patch)
treea4a56198989e08ffea34e0d1eff2c60ddaa4812c /src/core/support
parent772187cdf0ff9dfafd2e693474c51eeddfe4c800 (diff)
Added convenience method gpr_strjoin_sep
Diffstat (limited to 'src/core/support')
-rw-r--r--src/core/support/string.c15
-rw-r--r--src/core/support/string.h6
2 files changed, 20 insertions, 1 deletions
diff --git a/src/core/support/string.c b/src/core/support/string.c
index 6a80ccc841..f85f656da4 100644
--- a/src/core/support/string.c
+++ b/src/core/support/string.c
@@ -153,6 +153,12 @@ int gpr_ltoa(long value, char *string) {
}
char *gpr_strjoin(const char **strs, size_t nstrs, size_t *final_length) {
+ return gpr_strjoin_sep(strs, nstrs, "", final_length);
+}
+
+char *gpr_strjoin_sep(const char **strs, size_t nstrs, const char *sep,
+ size_t *final_length) {
+ const size_t sep_len = strlen(sep);
size_t out_length = 0;
size_t i;
char *out;
@@ -160,12 +166,19 @@ char *gpr_strjoin(const char **strs, size_t nstrs, size_t *final_length) {
out_length += strlen(strs[i]);
}
out_length += 1; /* null terminator */
+ if (nstrs > 0) {
+ out_length += sep_len * (nstrs - 1); /* separators */
+ }
out = gpr_malloc(out_length);
out_length = 0;
for (i = 0; i < nstrs; i++) {
- size_t slen = strlen(strs[i]);
+ const size_t slen = strlen(strs[i]);
memcpy(out + out_length, strs[i], slen);
out_length += slen;
+ if (sep_len > 0 && nstrs > 0 && i < nstrs - 1) {
+ memcpy(out + out_length, sep, sep_len);
+ out_length += sep_len;
+ }
}
out[out_length] = 0;
if (final_length != NULL) {
diff --git a/src/core/support/string.h b/src/core/support/string.h
index 31e9fcb5e9..a4da485dce 100644
--- a/src/core/support/string.h
+++ b/src/core/support/string.h
@@ -72,6 +72,12 @@ void gpr_reverse_bytes(char *str, int len);
if it is non-null. */
char *gpr_strjoin(const char **strs, size_t nstrs, size_t *total_length);
+/* Join a set of strings using a separator, returning the resulting string.
+ Total combined length (excluding null terminator) is returned in total_length
+ if it is non-null. */
+char *gpr_strjoin_sep(const char **strs, size_t nstrs, const char *sep,
+ size_t *total_length);
+
/* A vector of strings... for building up a final string one piece at a time */
typedef struct {
char **strs;