3 int prefixcmp(const char *str
, const char *prefix
)
5 for (; ; str
++, prefix
++)
8 else if (*str
!= *prefix
)
9 return (unsigned char)*prefix
- (unsigned char)*str
;
13 * Used as the default ->buf value, so that people can always assume
14 * buf is non NULL and ->buf is NUL terminated even for a freshly
17 char strbuf_slopbuf
[1];
19 void strbuf_init(struct strbuf
*sb
, ssize_t hint
)
21 sb
->alloc
= sb
->len
= 0;
22 sb
->buf
= strbuf_slopbuf
;
24 strbuf_grow(sb
, hint
);
27 void strbuf_release(struct strbuf
*sb
)
35 char *strbuf_detach(struct strbuf
*sb
, size_t *sz
)
37 char *res
= sb
->alloc
? sb
->buf
: NULL
;
44 void strbuf_grow(struct strbuf
*sb
, size_t extra
)
46 if (sb
->len
+ extra
+ 1 <= sb
->len
)
47 die("you want to use way too much memory");
50 ALLOC_GROW(sb
->buf
, sb
->len
+ extra
+ 1, sb
->alloc
);
53 static void strbuf_splice(struct strbuf
*sb
, size_t pos
, size_t len
,
54 const void *data
, size_t dlen
)
57 die("you want to use way too much memory");
59 die("`pos' is too far after the end of the buffer");
60 if (pos
+ len
> sb
->len
)
61 die("`pos + len' is too far after the end of the buffer");
64 strbuf_grow(sb
, dlen
- len
);
65 memmove(sb
->buf
+ pos
+ dlen
,
68 memcpy(sb
->buf
+ pos
, data
, dlen
);
69 strbuf_setlen(sb
, sb
->len
+ dlen
- len
);
72 void strbuf_remove(struct strbuf
*sb
, size_t pos
, size_t len
)
74 strbuf_splice(sb
, pos
, len
, NULL
, 0);
77 void strbuf_add(struct strbuf
*sb
, const void *data
, size_t len
)
80 memcpy(sb
->buf
+ sb
->len
, data
, len
);
81 strbuf_setlen(sb
, sb
->len
+ len
);
84 void strbuf_addf(struct strbuf
*sb
, const char *fmt
, ...)
89 if (!strbuf_avail(sb
))
92 len
= vsnprintf(sb
->buf
+ sb
->len
, sb
->alloc
- sb
->len
, fmt
, ap
);
95 die("your vsnprintf is broken");
96 if (len
> strbuf_avail(sb
)) {
99 len
= vsnprintf(sb
->buf
+ sb
->len
, sb
->alloc
- sb
->len
, fmt
, ap
);
101 if (len
> strbuf_avail(sb
)) {
102 die("this should not happen, your snprintf is broken");
105 strbuf_setlen(sb
, sb
->len
+ len
);
108 ssize_t
strbuf_read(struct strbuf
*sb
, int fd
, ssize_t hint
)
110 size_t oldlen
= sb
->len
;
111 size_t oldalloc
= sb
->alloc
;
113 strbuf_grow(sb
, hint
? hint
: 8192);
117 cnt
= read(fd
, sb
->buf
+ sb
->len
, sb
->alloc
- sb
->len
- 1);
122 strbuf_setlen(sb
, oldlen
);
128 strbuf_grow(sb
, 8192);
131 sb
->buf
[sb
->len
] = '\0';
132 return sb
->len
- oldlen
;