strbuf: export strbuf_addchars()
[git] / strbuf.c
1 #include "cache.h"
2 #include "refs.h"
3
4 int prefixcmp(const char *str, const char *prefix)
5 {
6         for (; ; str++, prefix++)
7                 if (!*prefix)
8                         return 0;
9                 else if (*str != *prefix)
10                         return (unsigned char)*prefix - (unsigned char)*str;
11 }
12
13 int suffixcmp(const char *str, const char *suffix)
14 {
15         int len = strlen(str), suflen = strlen(suffix);
16         if (len < suflen)
17                 return -1;
18         else
19                 return strcmp(str + len - suflen, suffix);
20 }
21
22 /*
23  * Used as the default ->buf value, so that people can always assume
24  * buf is non NULL and ->buf is NUL terminated even for a freshly
25  * initialized strbuf.
26  */
27 char strbuf_slopbuf[1];
28
29 void strbuf_init(struct strbuf *sb, size_t hint)
30 {
31         sb->alloc = sb->len = 0;
32         sb->buf = strbuf_slopbuf;
33         if (hint)
34                 strbuf_grow(sb, hint);
35 }
36
37 void strbuf_release(struct strbuf *sb)
38 {
39         if (sb->alloc) {
40                 free(sb->buf);
41                 strbuf_init(sb, 0);
42         }
43 }
44
45 char *strbuf_detach(struct strbuf *sb, size_t *sz)
46 {
47         char *res;
48         strbuf_grow(sb, 0);
49         res = sb->buf;
50         if (sz)
51                 *sz = sb->len;
52         strbuf_init(sb, 0);
53         return res;
54 }
55
56 void strbuf_attach(struct strbuf *sb, void *buf, size_t len, size_t alloc)
57 {
58         strbuf_release(sb);
59         sb->buf   = buf;
60         sb->len   = len;
61         sb->alloc = alloc;
62         strbuf_grow(sb, 0);
63         sb->buf[sb->len] = '\0';
64 }
65
66 void strbuf_grow(struct strbuf *sb, size_t extra)
67 {
68         int new_buf = !sb->alloc;
69         if (unsigned_add_overflows(extra, 1) ||
70             unsigned_add_overflows(sb->len, extra + 1))
71                 die("you want to use way too much memory");
72         if (new_buf)
73                 sb->buf = NULL;
74         ALLOC_GROW(sb->buf, sb->len + extra + 1, sb->alloc);
75         if (new_buf)
76                 sb->buf[0] = '\0';
77 }
78
79 void strbuf_trim(struct strbuf *sb)
80 {
81         char *b = sb->buf;
82         while (sb->len > 0 && isspace((unsigned char)sb->buf[sb->len - 1]))
83                 sb->len--;
84         while (sb->len > 0 && isspace(*b)) {
85                 b++;
86                 sb->len--;
87         }
88         memmove(sb->buf, b, sb->len);
89         sb->buf[sb->len] = '\0';
90 }
91 void strbuf_rtrim(struct strbuf *sb)
92 {
93         while (sb->len > 0 && isspace((unsigned char)sb->buf[sb->len - 1]))
94                 sb->len--;
95         sb->buf[sb->len] = '\0';
96 }
97
98 void strbuf_ltrim(struct strbuf *sb)
99 {
100         char *b = sb->buf;
101         while (sb->len > 0 && isspace(*b)) {
102                 b++;
103                 sb->len--;
104         }
105         memmove(sb->buf, b, sb->len);
106         sb->buf[sb->len] = '\0';
107 }
108
109 struct strbuf **strbuf_split_buf(const char *str, size_t slen,
110                                  int terminator, int max)
111 {
112         struct strbuf **ret = NULL;
113         size_t nr = 0, alloc = 0;
114         struct strbuf *t;
115
116         while (slen) {
117                 int len = slen;
118                 if (max <= 0 || nr + 1 < max) {
119                         const char *end = memchr(str, terminator, slen);
120                         if (end)
121                                 len = end - str + 1;
122                 }
123                 t = xmalloc(sizeof(struct strbuf));
124                 strbuf_init(t, len);
125                 strbuf_add(t, str, len);
126                 ALLOC_GROW(ret, nr + 2, alloc);
127                 ret[nr++] = t;
128                 str += len;
129                 slen -= len;
130         }
131         ALLOC_GROW(ret, nr + 1, alloc); /* In case string was empty */
132         ret[nr] = NULL;
133         return ret;
134 }
135
136 void strbuf_list_free(struct strbuf **sbs)
137 {
138         struct strbuf **s = sbs;
139
140         while (*s) {
141                 strbuf_release(*s);
142                 free(*s++);
143         }
144         free(sbs);
145 }
146
147 int strbuf_cmp(const struct strbuf *a, const struct strbuf *b)
148 {
149         int len = a->len < b->len ? a->len: b->len;
150         int cmp = memcmp(a->buf, b->buf, len);
151         if (cmp)
152                 return cmp;
153         return a->len < b->len ? -1: a->len != b->len;
154 }
155
156 void strbuf_splice(struct strbuf *sb, size_t pos, size_t len,
157                                    const void *data, size_t dlen)
158 {
159         if (unsigned_add_overflows(pos, len))
160                 die("you want to use way too much memory");
161         if (pos > sb->len)
162                 die("`pos' is too far after the end of the buffer");
163         if (pos + len > sb->len)
164                 die("`pos + len' is too far after the end of the buffer");
165
166         if (dlen >= len)
167                 strbuf_grow(sb, dlen - len);
168         memmove(sb->buf + pos + dlen,
169                         sb->buf + pos + len,
170                         sb->len - pos - len);
171         memcpy(sb->buf + pos, data, dlen);
172         strbuf_setlen(sb, sb->len + dlen - len);
173 }
174
175 void strbuf_insert(struct strbuf *sb, size_t pos, const void *data, size_t len)
176 {
177         strbuf_splice(sb, pos, 0, data, len);
178 }
179
180 void strbuf_remove(struct strbuf *sb, size_t pos, size_t len)
181 {
182         strbuf_splice(sb, pos, len, NULL, 0);
183 }
184
185 void strbuf_add(struct strbuf *sb, const void *data, size_t len)
186 {
187         strbuf_grow(sb, len);
188         memcpy(sb->buf + sb->len, data, len);
189         strbuf_setlen(sb, sb->len + len);
190 }
191
192 void strbuf_adddup(struct strbuf *sb, size_t pos, size_t len)
193 {
194         strbuf_grow(sb, len);
195         memcpy(sb->buf + sb->len, sb->buf + pos, len);
196         strbuf_setlen(sb, sb->len + len);
197 }
198
199 void strbuf_addchars(struct strbuf *sb, int c, size_t n)
200 {
201         strbuf_grow(sb, n);
202         memset(sb->buf + sb->len, c, n);
203         strbuf_setlen(sb, sb->len + n);
204 }
205
206 void strbuf_addf(struct strbuf *sb, const char *fmt, ...)
207 {
208         va_list ap;
209         va_start(ap, fmt);
210         strbuf_vaddf(sb, fmt, ap);
211         va_end(ap);
212 }
213
214 static void add_lines(struct strbuf *out,
215                         const char *prefix1,
216                         const char *prefix2,
217                         const char *buf, size_t size)
218 {
219         while (size) {
220                 const char *prefix;
221                 const char *next = memchr(buf, '\n', size);
222                 next = next ? (next + 1) : (buf + size);
223
224                 prefix = (prefix2 && buf[0] == '\n') ? prefix2 : prefix1;
225                 strbuf_addstr(out, prefix);
226                 strbuf_add(out, buf, next - buf);
227                 size -= next - buf;
228                 buf = next;
229         }
230         strbuf_complete_line(out);
231 }
232
233 void strbuf_add_commented_lines(struct strbuf *out, const char *buf, size_t size)
234 {
235         static char prefix1[3];
236         static char prefix2[2];
237
238         if (prefix1[0] != comment_line_char) {
239                 sprintf(prefix1, "%c ", comment_line_char);
240                 sprintf(prefix2, "%c", comment_line_char);
241         }
242         add_lines(out, prefix1, prefix2, buf, size);
243 }
244
245 void strbuf_commented_addf(struct strbuf *sb, const char *fmt, ...)
246 {
247         va_list params;
248         struct strbuf buf = STRBUF_INIT;
249         int incomplete_line = sb->len && sb->buf[sb->len - 1] != '\n';
250
251         va_start(params, fmt);
252         strbuf_vaddf(&buf, fmt, params);
253         va_end(params);
254
255         strbuf_add_commented_lines(sb, buf.buf, buf.len);
256         if (incomplete_line)
257                 sb->buf[--sb->len] = '\0';
258
259         strbuf_release(&buf);
260 }
261
262 void strbuf_vaddf(struct strbuf *sb, const char *fmt, va_list ap)
263 {
264         int len;
265         va_list cp;
266
267         if (!strbuf_avail(sb))
268                 strbuf_grow(sb, 64);
269         va_copy(cp, ap);
270         len = vsnprintf(sb->buf + sb->len, sb->alloc - sb->len, fmt, cp);
271         va_end(cp);
272         if (len < 0)
273                 die("BUG: your vsnprintf is broken (returned %d)", len);
274         if (len > strbuf_avail(sb)) {
275                 strbuf_grow(sb, len);
276                 len = vsnprintf(sb->buf + sb->len, sb->alloc - sb->len, fmt, ap);
277                 if (len > strbuf_avail(sb))
278                         die("BUG: your vsnprintf is broken (insatiable)");
279         }
280         strbuf_setlen(sb, sb->len + len);
281 }
282
283 void strbuf_expand(struct strbuf *sb, const char *format, expand_fn_t fn,
284                    void *context)
285 {
286         for (;;) {
287                 const char *percent;
288                 size_t consumed;
289
290                 percent = strchrnul(format, '%');
291                 strbuf_add(sb, format, percent - format);
292                 if (!*percent)
293                         break;
294                 format = percent + 1;
295
296                 if (*format == '%') {
297                         strbuf_addch(sb, '%');
298                         format++;
299                         continue;
300                 }
301
302                 consumed = fn(sb, format, context);
303                 if (consumed)
304                         format += consumed;
305                 else
306                         strbuf_addch(sb, '%');
307         }
308 }
309
310 size_t strbuf_expand_dict_cb(struct strbuf *sb, const char *placeholder,
311                 void *context)
312 {
313         struct strbuf_expand_dict_entry *e = context;
314         size_t len;
315
316         for (; e->placeholder && (len = strlen(e->placeholder)); e++) {
317                 if (!strncmp(placeholder, e->placeholder, len)) {
318                         if (e->value)
319                                 strbuf_addstr(sb, e->value);
320                         return len;
321                 }
322         }
323         return 0;
324 }
325
326 void strbuf_addbuf_percentquote(struct strbuf *dst, const struct strbuf *src)
327 {
328         int i, len = src->len;
329
330         for (i = 0; i < len; i++) {
331                 if (src->buf[i] == '%')
332                         strbuf_addch(dst, '%');
333                 strbuf_addch(dst, src->buf[i]);
334         }
335 }
336
337 size_t strbuf_fread(struct strbuf *sb, size_t size, FILE *f)
338 {
339         size_t res;
340         size_t oldalloc = sb->alloc;
341
342         strbuf_grow(sb, size);
343         res = fread(sb->buf + sb->len, 1, size, f);
344         if (res > 0)
345                 strbuf_setlen(sb, sb->len + res);
346         else if (oldalloc == 0)
347                 strbuf_release(sb);
348         return res;
349 }
350
351 ssize_t strbuf_read(struct strbuf *sb, int fd, size_t hint)
352 {
353         size_t oldlen = sb->len;
354         size_t oldalloc = sb->alloc;
355
356         strbuf_grow(sb, hint ? hint : 8192);
357         for (;;) {
358                 ssize_t cnt;
359
360                 cnt = xread(fd, sb->buf + sb->len, sb->alloc - sb->len - 1);
361                 if (cnt < 0) {
362                         if (oldalloc == 0)
363                                 strbuf_release(sb);
364                         else
365                                 strbuf_setlen(sb, oldlen);
366                         return -1;
367                 }
368                 if (!cnt)
369                         break;
370                 sb->len += cnt;
371                 strbuf_grow(sb, 8192);
372         }
373
374         sb->buf[sb->len] = '\0';
375         return sb->len - oldlen;
376 }
377
378 #define STRBUF_MAXLINK (2*PATH_MAX)
379
380 int strbuf_readlink(struct strbuf *sb, const char *path, size_t hint)
381 {
382         size_t oldalloc = sb->alloc;
383
384         if (hint < 32)
385                 hint = 32;
386
387         while (hint < STRBUF_MAXLINK) {
388                 int len;
389
390                 strbuf_grow(sb, hint);
391                 len = readlink(path, sb->buf, hint);
392                 if (len < 0) {
393                         if (errno != ERANGE)
394                                 break;
395                 } else if (len < hint) {
396                         strbuf_setlen(sb, len);
397                         return 0;
398                 }
399
400                 /* .. the buffer was too small - try again */
401                 hint *= 2;
402         }
403         if (oldalloc == 0)
404                 strbuf_release(sb);
405         return -1;
406 }
407
408 int strbuf_getwholeline(struct strbuf *sb, FILE *fp, int term)
409 {
410         int ch;
411
412         if (feof(fp))
413                 return EOF;
414
415         strbuf_reset(sb);
416         while ((ch = fgetc(fp)) != EOF) {
417                 strbuf_grow(sb, 1);
418                 sb->buf[sb->len++] = ch;
419                 if (ch == term)
420                         break;
421         }
422         if (ch == EOF && sb->len == 0)
423                 return EOF;
424
425         sb->buf[sb->len] = '\0';
426         return 0;
427 }
428
429 int strbuf_getline(struct strbuf *sb, FILE *fp, int term)
430 {
431         if (strbuf_getwholeline(sb, fp, term))
432                 return EOF;
433         if (sb->buf[sb->len-1] == term)
434                 strbuf_setlen(sb, sb->len-1);
435         return 0;
436 }
437
438 int strbuf_getwholeline_fd(struct strbuf *sb, int fd, int term)
439 {
440         strbuf_reset(sb);
441
442         while (1) {
443                 char ch;
444                 ssize_t len = xread(fd, &ch, 1);
445                 if (len <= 0)
446                         return EOF;
447                 strbuf_addch(sb, ch);
448                 if (ch == term)
449                         break;
450         }
451         return 0;
452 }
453
454 int strbuf_read_file(struct strbuf *sb, const char *path, size_t hint)
455 {
456         int fd, len;
457
458         fd = open(path, O_RDONLY);
459         if (fd < 0)
460                 return -1;
461         len = strbuf_read(sb, fd, hint);
462         close(fd);
463         if (len < 0)
464                 return -1;
465
466         return len;
467 }
468
469 void strbuf_add_lines(struct strbuf *out, const char *prefix,
470                       const char *buf, size_t size)
471 {
472         add_lines(out, prefix, NULL, buf, size);
473 }
474
475 void strbuf_addstr_xml_quoted(struct strbuf *buf, const char *s)
476 {
477         while (*s) {
478                 size_t len = strcspn(s, "\"<>&");
479                 strbuf_add(buf, s, len);
480                 s += len;
481                 switch (*s) {
482                 case '"':
483                         strbuf_addstr(buf, "&quot;");
484                         break;
485                 case '<':
486                         strbuf_addstr(buf, "&lt;");
487                         break;
488                 case '>':
489                         strbuf_addstr(buf, "&gt;");
490                         break;
491                 case '&':
492                         strbuf_addstr(buf, "&amp;");
493                         break;
494                 case 0:
495                         return;
496                 }
497                 s++;
498         }
499 }
500
501 static int is_rfc3986_reserved(char ch)
502 {
503         switch (ch) {
504                 case '!': case '*': case '\'': case '(': case ')': case ';':
505                 case ':': case '@': case '&': case '=': case '+': case '$':
506                 case ',': case '/': case '?': case '#': case '[': case ']':
507                         return 1;
508         }
509         return 0;
510 }
511
512 static int is_rfc3986_unreserved(char ch)
513 {
514         return isalnum(ch) ||
515                 ch == '-' || ch == '_' || ch == '.' || ch == '~';
516 }
517
518 static void strbuf_add_urlencode(struct strbuf *sb, const char *s, size_t len,
519                                  int reserved)
520 {
521         strbuf_grow(sb, len);
522         while (len--) {
523                 char ch = *s++;
524                 if (is_rfc3986_unreserved(ch) ||
525                     (!reserved && is_rfc3986_reserved(ch)))
526                         strbuf_addch(sb, ch);
527                 else
528                         strbuf_addf(sb, "%%%02x", ch);
529         }
530 }
531
532 void strbuf_addstr_urlencode(struct strbuf *sb, const char *s,
533                              int reserved)
534 {
535         strbuf_add_urlencode(sb, s, strlen(s), reserved);
536 }
537
538 void strbuf_humanise_bytes(struct strbuf *buf, off_t bytes)
539 {
540         if (bytes > 1 << 30) {
541                 strbuf_addf(buf, "%u.%2.2u GiB",
542                             (int)(bytes >> 30),
543                             (int)(bytes & ((1 << 30) - 1)) / 10737419);
544         } else if (bytes > 1 << 20) {
545                 int x = bytes + 5243;  /* for rounding */
546                 strbuf_addf(buf, "%u.%2.2u MiB",
547                             x >> 20, ((x & ((1 << 20) - 1)) * 100) >> 20);
548         } else if (bytes > 1 << 10) {
549                 int x = bytes + 5;  /* for rounding */
550                 strbuf_addf(buf, "%u.%2.2u KiB",
551                             x >> 10, ((x & ((1 << 10) - 1)) * 100) >> 10);
552         } else {
553                 strbuf_addf(buf, "%u bytes", (int)bytes);
554         }
555 }
556
557 int printf_ln(const char *fmt, ...)
558 {
559         int ret;
560         va_list ap;
561         va_start(ap, fmt);
562         ret = vprintf(fmt, ap);
563         va_end(ap);
564         if (ret < 0 || putchar('\n') == EOF)
565                 return -1;
566         return ret + 1;
567 }
568
569 int fprintf_ln(FILE *fp, const char *fmt, ...)
570 {
571         int ret;
572         va_list ap;
573         va_start(ap, fmt);
574         ret = vfprintf(fp, fmt, ap);
575         va_end(ap);
576         if (ret < 0 || putc('\n', fp) == EOF)
577                 return -1;
578         return ret + 1;
579 }