3 void strbuf_init(struct strbuf
*sb
, size_t hint
)
5 memset(sb
, 0, sizeof(*sb
));
10 void strbuf_release(struct strbuf
*sb
)
13 memset(sb
, 0, sizeof(*sb
));
16 void strbuf_reset(struct strbuf
*sb
)
23 char *strbuf_detach(struct strbuf
*sb
)
30 void strbuf_attach(struct strbuf
*sb
, void *buf
, size_t len
, size_t alloc
)
37 sb
->buf
[sb
->len
] = '\0';
40 void strbuf_grow(struct strbuf
*sb
, size_t extra
)
42 if (sb
->len
+ extra
+ 1 <= sb
->len
)
43 die("you want to use way too much memory");
44 ALLOC_GROW(sb
->buf
, sb
->len
+ extra
+ 1, sb
->alloc
);
47 void strbuf_rtrim(struct strbuf
*sb
)
49 while (sb
->len
> 0 && isspace((unsigned char)sb
->buf
[sb
->len
- 1]))
51 sb
->buf
[sb
->len
] = '\0';
54 void strbuf_insert(struct strbuf
*sb
, size_t pos
, const void *data
, size_t len
)
58 die("`pos' is too far after the end of the buffer");
59 memmove(sb
->buf
+ pos
+ len
, sb
->buf
+ pos
, sb
->len
- pos
);
60 memcpy(sb
->buf
+ pos
, data
, len
);
61 strbuf_setlen(sb
, sb
->len
+ len
);
64 void strbuf_splice(struct strbuf
*sb
, size_t pos
, size_t len
,
65 const void *data
, size_t dlen
)
68 die("you want to use way too much memory");
70 die("`pos' is too far after the end of the buffer");
71 if (pos
+ len
> sb
->len
)
72 die("`pos + len' is too far after the end of the buffer");
75 strbuf_grow(sb
, dlen
- len
);
76 memmove(sb
->buf
+ pos
+ dlen
,
79 memcpy(sb
->buf
+ pos
, data
, dlen
);
80 strbuf_setlen(sb
, sb
->len
+ dlen
- len
);
83 void strbuf_add(struct strbuf
*sb
, const void *data
, size_t len
)
86 memcpy(sb
->buf
+ sb
->len
, data
, len
);
87 strbuf_setlen(sb
, sb
->len
+ len
);
90 void strbuf_addf(struct strbuf
*sb
, const char *fmt
, ...)
96 len
= vsnprintf(sb
->buf
+ sb
->len
, sb
->alloc
- sb
->len
, fmt
, ap
);
101 if (len
> strbuf_avail(sb
)) {
102 strbuf_grow(sb
, len
);
104 len
= vsnprintf(sb
->buf
+ sb
->len
, sb
->alloc
- sb
->len
, fmt
, ap
);
106 if (len
> strbuf_avail(sb
)) {
107 die("this should not happen, your snprintf is broken");
110 strbuf_setlen(sb
, sb
->len
+ len
);
113 size_t strbuf_fread(struct strbuf
*sb
, size_t size
, FILE *f
)
117 strbuf_grow(sb
, size
);
118 res
= fread(sb
->buf
+ sb
->len
, 1, size
, f
);
120 strbuf_setlen(sb
, sb
->len
+ res
);
125 ssize_t
strbuf_read(struct strbuf
*sb
, int fd
, size_t hint
)
127 size_t oldlen
= sb
->len
;
129 strbuf_grow(sb
, hint
? hint
: 8192);
133 cnt
= xread(fd
, sb
->buf
+ sb
->len
, sb
->alloc
- sb
->len
- 1);
135 strbuf_setlen(sb
, oldlen
);
141 strbuf_grow(sb
, 8192);
144 sb
->buf
[sb
->len
] = '\0';
145 return sb
->len
- oldlen
;
148 void read_line(struct strbuf
*sb
, FILE *fp
, int term
)
158 while ((ch
= fgetc(fp
)) != EOF
) {
162 sb
->buf
[sb
->len
++] = ch
;
164 if (ch
== EOF
&& sb
->len
== 0) {
170 sb
->buf
[sb
->len
] = '\0';