strbuf: allow strbuf_split to work on non-strbufs

The strbuf_split function takes a strbuf as input, and outputs a list of strbufs. However, there is no reason that the input has to be a strbuf, and not an arbitrary buffer. This patch adds strbuf_split_buf for a length-delimited buffer, and strbuf_split_str for NUL-terminated strings. 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:54 UTC 2f1d9e2b93e1b7fbfcfa59331db89dd6c76a3505
2 files changed +17 -7
strbuf.c
+6 -6
@@ -101,19 +101,19 @@ void strbuf_ltrim(struct strbuf *sb)
101 sb->buf[sb->len] = '\0';
102 }
103
104 -struct strbuf **strbuf_split_max(const struct strbuf *sb, int delim, int max)
104 +struct strbuf **strbuf_split_buf(const char *str, size_t slen, int delim, int max)
105 {
106 int alloc = 2, pos = 0;
107 - char *n, *p;
107 + const char *n, *p;
108 struct strbuf **ret;
109 struct strbuf *t;
110
111 ret = xcalloc(alloc, sizeof(struct strbuf *));
112 - p = n = sb->buf;
113 - while (n < sb->buf + sb->len) {
112 + p = n = str;
113 + while (n < str + slen) {
114 int len;
115 if (max <= 0 || pos + 1 < max)
116 - n = memchr(n, delim, sb->len - (n - sb->buf));
116 + n = memchr(n, delim, slen - (n - str));
117 else
118 n = NULL;
119 if (pos + 1 >= alloc) {
@@ -121,7 +121,7 @@ struct strbuf **strbuf_split_max(const struct strbuf *sb, int delim, int max)
121 ret = xrealloc(ret, sizeof(struct strbuf *) * alloc);
122 }
123 if (!n)
124 - n = sb->buf + sb->len - 1;
124 + n = str + slen - 1;
125 len = n - p + 1;
126 t = xmalloc(sizeof(struct strbuf));
127 strbuf_init(t, len);
strbuf.h
+11 -1
@@ -47,8 +47,18 @@ 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_max(const struct strbuf *,
50 +extern struct strbuf **strbuf_split_buf(const char *, size_t,
51 int delim, int max);
52 +static inline struct strbuf **strbuf_split_str(const char *str,
53 + int delim, int max)
54 +{
55 + return strbuf_split_buf(str, strlen(str), delim, max);
56 +}
57 +static inline struct strbuf **strbuf_split_max(const struct strbuf *sb,
58 + int delim, int max)
59 +{
60 + return strbuf_split_buf(sb->buf, sb->len, delim, max);
61 +}
62 static inline struct strbuf **strbuf_split(const struct strbuf *sb, int delim)
63 {
64 return strbuf_split_max(sb, delim, 0);