Skip to content

Commit 2f1d9e2

Browse files
peffgitster
authored andcommitted
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 <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent c5d6350 commit 2f1d9e2

File tree

2 files changed

+17
-7
lines changed

2 files changed

+17
-7
lines changed

strbuf.c

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -101,27 +101,27 @@ void strbuf_ltrim(struct strbuf *sb)
101101
sb->buf[sb->len] = '\0';
102102
}
103103

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)
105105
{
106106
int alloc = 2, pos = 0;
107-
char *n, *p;
107+
const char *n, *p;
108108
struct strbuf **ret;
109109
struct strbuf *t;
110110

111111
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) {
114114
int len;
115115
if (max <= 0 || pos + 1 < max)
116-
n = memchr(n, delim, sb->len - (n - sb->buf));
116+
n = memchr(n, delim, slen - (n - str));
117117
else
118118
n = NULL;
119119
if (pos + 1 >= alloc) {
120120
alloc = alloc * 2;
121121
ret = xrealloc(ret, sizeof(struct strbuf *) * alloc);
122122
}
123123
if (!n)
124-
n = sb->buf + sb->len - 1;
124+
n = str + slen - 1;
125125
len = n - p + 1;
126126
t = xmalloc(sizeof(struct strbuf));
127127
strbuf_init(t, len);

strbuf.h

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,18 @@ extern void strbuf_rtrim(struct strbuf *);
4747
extern void strbuf_ltrim(struct strbuf *);
4848
extern int strbuf_cmp(const struct strbuf *, const struct strbuf *);
4949

50-
extern struct strbuf **strbuf_split_max(const struct strbuf *,
50+
extern struct strbuf **strbuf_split_buf(const char *, size_t,
5151
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+
}
5262
static inline struct strbuf **strbuf_split(const struct strbuf *sb, int delim)
5363
{
5464
return strbuf_split_max(sb, delim, 0);

0 commit comments

Comments
 (0)