diff mbox series

[1/2] strvec.c: add a strvec_split_delim()

Message ID ea7408c36e515440771851c3581d7a9e3c6e4c8f.1642615122.git.gitgitgadget@gmail.com (mailing list archive)
State New, archived
Headers show
Series cat-file: add a --stdin-cmd mode | expand

Commit Message

John Cai Jan. 19, 2022, 5:58 p.m. UTC
From: John Cai <johncai86@gmail.com>

This is just string_list_split() copy/pasted with the "push" part
adjusted. The next commit will call this function to parse a line of
command arguments.

Helped-by: Ævar Arnfjörð Bjarmason <avarab@gmail.com>
Signed-off-by: John Cai <johncai86@gmail.com>
---
 strvec.c | 23 +++++++++++++++++++++++
 strvec.h |  8 ++++++++
 2 files changed, 31 insertions(+)
diff mbox series

Patch

diff --git a/strvec.c b/strvec.c
index 61a76ce6cb9..7dca04bf7a5 100644
--- a/strvec.c
+++ b/strvec.c
@@ -85,6 +85,29 @@  void strvec_split(struct strvec *array, const char *to_split)
 	}
 }
 
+size_t strvec_split_delim(struct strvec *array, const char *string,
+			  int delim, int maxsplit)
+{
+	size_t count = 0;
+	const char *p = string, *end;
+
+	for (;;) {
+		count++;
+		if (maxsplit >= 0 && count > maxsplit) {
+			strvec_push(array, p);
+			return count;
+		}
+		end = strchr(p, delim);
+		if (end) {
+			strvec_push_nodup(array, xmemdupz(p, end - p));
+			p = end + 1;
+		} else {
+			strvec_push(array, p);
+			return count;
+		}
+	}
+}
+
 void strvec_clear(struct strvec *array)
 {
 	if (array->v != empty_strvec) {
diff --git a/strvec.h b/strvec.h
index 9f55c8766ba..c474918b91a 100644
--- a/strvec.h
+++ b/strvec.h
@@ -73,6 +73,14 @@  void strvec_pop(struct strvec *);
 /* Splits by whitespace; does not handle quoted arguments! */
 void strvec_split(struct strvec *, const char *);
 
+/**
+ * strvec_split_delim() is a split function that behaves more like its
+ * string_list_split() cousin than the whitespace-splitting
+ * strvec_split().
+ */
+size_t strvec_split_delim(struct strvec *array, const char *string,
+			  int delim, int maxsplit);
+
 /**
  * Free all memory associated with the array and return it to the
  * initial, empty state.