strbuf_split: add a max parameter

Sometimes when splitting, you only want a limited number of fields, and for the final field to contain "everything else", even if it includes the delimiter. This patch introduces strbuf_split_max, which provides a "max number of fields" parameter; it behaves similarly to perl's "split" with a 3rd field. The existing 2-argument form of strbuf_split is retained for compatibility and ease-of-use. Signed-off-by: Jeff King <peff@peff.net> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Jeff King committed Jun 9, 2011 at 11:51 UTC 28fc3a6857a5d7a6b4f63b2672fb0ce966b0df78
2 files changed +11 -3
strbuf.c
+5 -2
@@ -101,7 +101,7 @@ void strbuf_ltrim(struct strbuf *sb)
101 sb->buf[sb->len] = '\0';
102 }
103
104 -struct strbuf **strbuf_split(const struct strbuf *sb, int delim)
104 +struct strbuf **strbuf_split_max(const struct strbuf *sb, int delim, int max)
105 {
106 int alloc = 2, pos = 0;
107 char *n, *p;
@@ -112,7 +112,10 @@ struct strbuf **strbuf_split(const struct strbuf *sb, int delim)
112 p = n = sb->buf;
113 while (n < sb->buf + sb->len) {
114 int len;
115 - n = memchr(n, delim, sb->len - (n - sb->buf));
115 + if (max <= 0 || pos + 1 < max)
116 + n = memchr(n, delim, sb->len - (n - sb->buf));
117 + else
118 + n = NULL;
119 if (pos + 1 >= alloc) {
120 alloc = alloc * 2;
121 ret = xrealloc(ret, sizeof(struct strbuf *) * alloc);
strbuf.h
+6 -1
@@ -47,7 +47,12 @@ extern void strbuf_rtrim(struct strbuf *);
47 extern void strbuf_ltrim(struct strbuf *);
48 extern int strbuf_cmp(const struct strbuf *, const struct strbuf *);
49
50 -extern struct strbuf **strbuf_split(const struct strbuf *, int delim);
50 +extern struct strbuf **strbuf_split_max(const struct strbuf *,
51 + int delim, int max);
52 +static inline struct strbuf **strbuf_split(const struct strbuf *sb, int delim)
53 +{
54 + return strbuf_split_max(sb, delim, 0);
55 +}
56 extern void strbuf_list_free(struct strbuf **);
57
58 /*----- add data in your buffer -----*/