Skip to content

Commit 28fc3a6

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

File tree

2 files changed

+11
-3
lines changed

2 files changed

+11
-3
lines changed

strbuf.c

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

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)
105105
{
106106
int alloc = 2, pos = 0;
107107
char *n, *p;
@@ -112,7 +112,10 @@ struct strbuf **strbuf_split(const struct strbuf *sb, int delim)
112112
p = n = sb->buf;
113113
while (n < sb->buf + sb->len) {
114114
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;
116119
if (pos + 1 >= alloc) {
117120
alloc = alloc * 2;
118121
ret = xrealloc(ret, sizeof(struct strbuf *) * alloc);

strbuf.h

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,12 @@ 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(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+
}
5156
extern void strbuf_list_free(struct strbuf **);
5257

5358
/*----- add data in your buffer -----*/

0 commit comments

Comments
 (0)