Thread (16 messages) 16 messages, 5 authors, 2018-05-20
STALE2941d
Revisions (4)
  1. v2 [diff vs current]
  2. v3 [diff vs current]
  3. v4 current
  4. v5 [diff vs current]

[PATCH v4 3/4] string-list: provide `string_list_appendf()`

From: Martin Ågren <hidden>
Date: 2018-05-20 10:18:39
Subsystem: the rest · Maintainer: Linus Torvalds

Add a function `string_list_appendf(list, fmt, ...)` to the string-list
API. The next commit will add a user.

This function naturally ignores the `strdup_strings`-setting and always
appends a freshly allocated string. Thus, using this function with
`strdup_strings = 0` risks making ownership unclear and leaking memory.
With `strdup_strings = 1` on the other hand, we can easily add formatted
strings without going through `string_list_append_nodup()` or playing
with `strdup_strings`.

Suggested-by: Jeff King <redacted>
Signed-off-by: Martin Ågren <redacted>
---
 string-list.h |  9 +++++++++
 string-list.c | 13 +++++++++++++
 2 files changed, 22 insertions(+)
diff --git a/string-list.h b/string-list.h
index ff8f6094a3..3a73b86ffa 100644
--- a/string-list.h
+++ b/string-list.h
@@ -208,6 +208,15 @@ void string_list_remove_duplicates(struct string_list *sorted_list, int free_uti
  */
 struct string_list_item *string_list_append(struct string_list *list, const char *string);
 
+/**
+ * Add formatted string to the end of `list`. This function ignores
+ * the value of `list->strdup_strings` and always appends a freshly
+ * allocated string, so you will probably not want to use it with
+ * `strdup_strings = 0`.
+ */
+struct string_list_item *string_list_appendf(struct string_list *list,
+					     const char *fmt, ...);
+
 /**
  * Like string_list_append(), except string is never copied.  When
  * list->strdup_strings is set, this function can be used to hand
diff --git a/string-list.c b/string-list.c
index a0cf0cfe88..b54d31c1cf 100644
--- a/string-list.c
+++ b/string-list.c
@@ -224,6 +224,19 @@ struct string_list_item *string_list_append(struct string_list *list,
 			list->strdup_strings ? xstrdup(string) : (char *)string);
 }
 
+struct string_list_item *string_list_appendf(struct string_list *list,
+					     const char *fmt, ...)
+{
+	struct string_list_item *retval;
+	va_list ap;
+
+	va_start(ap, fmt);
+	retval = string_list_append_nodup(list, xstrvfmt(fmt, ap));
+	va_end(ap);
+
+	return retval;
+}
+
 static int cmp_items(const void *a, const void *b, void *ctx)
 {
 	compare_strings_fn cmp = ctx;
-- 
2.17.0.840.g5d83f92caf
Keyboard shortcuts
hback out one level
jnext message in thread
kprevious message in thread
ldrill in
Escclose help / fold thread tree
?toggle this help