reftable/writer: fix index corruption when writing multiple indices
[alt-git.git] / strbuf.c
blob7827178d8e5e374582357f48a14a77bb15d98320
1 #include "git-compat-util.h"
2 #include "gettext.h"
3 #include "hex-ll.h"
4 #include "strbuf.h"
5 #include "string-list.h"
6 #include "utf8.h"
7 #include "date.h"
9 int starts_with(const char *str, const char *prefix)
11 for (; ; str++, prefix++)
12 if (!*prefix)
13 return 1;
14 else if (*str != *prefix)
15 return 0;
18 int istarts_with(const char *str, const char *prefix)
20 for (; ; str++, prefix++)
21 if (!*prefix)
22 return 1;
23 else if (tolower(*str) != tolower(*prefix))
24 return 0;
27 int skip_to_optional_arg_default(const char *str, const char *prefix,
28 const char **arg, const char *def)
30 const char *p;
32 if (!skip_prefix(str, prefix, &p))
33 return 0;
35 if (!*p) {
36 if (arg)
37 *arg = def;
38 return 1;
41 if (*p != '=')
42 return 0;
44 if (arg)
45 *arg = p + 1;
46 return 1;
50 * Used as the default ->buf value, so that people can always assume
51 * buf is non NULL and ->buf is NUL terminated even for a freshly
52 * initialized strbuf.
54 char strbuf_slopbuf[1];
56 void strbuf_init(struct strbuf *sb, size_t hint)
58 struct strbuf blank = STRBUF_INIT;
59 memcpy(sb, &blank, sizeof(*sb));
60 if (hint)
61 strbuf_grow(sb, hint);
64 void strbuf_release(struct strbuf *sb)
66 if (sb->alloc) {
67 free(sb->buf);
68 strbuf_init(sb, 0);
72 char *strbuf_detach(struct strbuf *sb, size_t *sz)
74 char *res;
75 strbuf_grow(sb, 0);
76 res = sb->buf;
77 if (sz)
78 *sz = sb->len;
79 strbuf_init(sb, 0);
80 return res;
83 void strbuf_attach(struct strbuf *sb, void *buf, size_t len, size_t alloc)
85 strbuf_release(sb);
86 sb->buf = buf;
87 sb->len = len;
88 sb->alloc = alloc;
89 strbuf_grow(sb, 0);
90 sb->buf[sb->len] = '\0';
93 void strbuf_grow(struct strbuf *sb, size_t extra)
95 int new_buf = !sb->alloc;
96 if (unsigned_add_overflows(extra, 1) ||
97 unsigned_add_overflows(sb->len, extra + 1))
98 die("you want to use way too much memory");
99 if (new_buf)
100 sb->buf = NULL;
101 ALLOC_GROW(sb->buf, sb->len + extra + 1, sb->alloc);
102 if (new_buf)
103 sb->buf[0] = '\0';
106 void strbuf_trim(struct strbuf *sb)
108 strbuf_rtrim(sb);
109 strbuf_ltrim(sb);
112 void strbuf_rtrim(struct strbuf *sb)
114 while (sb->len > 0 && isspace((unsigned char)sb->buf[sb->len - 1]))
115 sb->len--;
116 sb->buf[sb->len] = '\0';
119 void strbuf_trim_trailing_dir_sep(struct strbuf *sb)
121 while (sb->len > 0 && is_dir_sep((unsigned char)sb->buf[sb->len - 1]))
122 sb->len--;
123 sb->buf[sb->len] = '\0';
126 void strbuf_trim_trailing_newline(struct strbuf *sb)
128 if (sb->len > 0 && sb->buf[sb->len - 1] == '\n') {
129 if (--sb->len > 0 && sb->buf[sb->len - 1] == '\r')
130 --sb->len;
131 sb->buf[sb->len] = '\0';
135 void strbuf_ltrim(struct strbuf *sb)
137 char *b = sb->buf;
138 while (sb->len > 0 && isspace(*b)) {
139 b++;
140 sb->len--;
142 memmove(sb->buf, b, sb->len);
143 sb->buf[sb->len] = '\0';
146 int strbuf_reencode(struct strbuf *sb, const char *from, const char *to)
148 char *out;
149 size_t len;
151 if (same_encoding(from, to))
152 return 0;
154 out = reencode_string_len(sb->buf, sb->len, to, from, &len);
155 if (!out)
156 return -1;
158 strbuf_attach(sb, out, len, len);
159 return 0;
162 void strbuf_tolower(struct strbuf *sb)
164 char *p = sb->buf, *end = sb->buf + sb->len;
165 for (; p < end; p++)
166 *p = tolower(*p);
169 struct strbuf **strbuf_split_buf(const char *str, size_t slen,
170 int terminator, int max)
172 struct strbuf **ret = NULL;
173 size_t nr = 0, alloc = 0;
174 struct strbuf *t;
176 while (slen) {
177 int len = slen;
178 if (max <= 0 || nr + 1 < max) {
179 const char *end = memchr(str, terminator, slen);
180 if (end)
181 len = end - str + 1;
183 t = xmalloc(sizeof(struct strbuf));
184 strbuf_init(t, len);
185 strbuf_add(t, str, len);
186 ALLOC_GROW(ret, nr + 2, alloc);
187 ret[nr++] = t;
188 str += len;
189 slen -= len;
191 ALLOC_GROW(ret, nr + 1, alloc); /* In case string was empty */
192 ret[nr] = NULL;
193 return ret;
196 void strbuf_add_separated_string_list(struct strbuf *str,
197 const char *sep,
198 struct string_list *slist)
200 struct string_list_item *item;
201 int sep_needed = 0;
203 for_each_string_list_item(item, slist) {
204 if (sep_needed)
205 strbuf_addstr(str, sep);
206 strbuf_addstr(str, item->string);
207 sep_needed = 1;
211 void strbuf_list_free(struct strbuf **sbs)
213 struct strbuf **s = sbs;
215 if (!s)
216 return;
217 while (*s) {
218 strbuf_release(*s);
219 free(*s++);
221 free(sbs);
224 int strbuf_cmp(const struct strbuf *a, const struct strbuf *b)
226 size_t len = a->len < b->len ? a->len: b->len;
227 int cmp = memcmp(a->buf, b->buf, len);
228 if (cmp)
229 return cmp;
230 return a->len < b->len ? -1: a->len != b->len;
233 void strbuf_splice(struct strbuf *sb, size_t pos, size_t len,
234 const void *data, size_t dlen)
236 if (unsigned_add_overflows(pos, len))
237 die("you want to use way too much memory");
238 if (pos > sb->len)
239 die("`pos' is too far after the end of the buffer");
240 if (pos + len > sb->len)
241 die("`pos + len' is too far after the end of the buffer");
243 if (dlen >= len)
244 strbuf_grow(sb, dlen - len);
245 memmove(sb->buf + pos + dlen,
246 sb->buf + pos + len,
247 sb->len - pos - len);
248 memcpy(sb->buf + pos, data, dlen);
249 strbuf_setlen(sb, sb->len + dlen - len);
252 void strbuf_insert(struct strbuf *sb, size_t pos, const void *data, size_t len)
254 strbuf_splice(sb, pos, 0, data, len);
257 void strbuf_vinsertf(struct strbuf *sb, size_t pos, const char *fmt, va_list ap)
259 int len, len2;
260 char save;
261 va_list cp;
263 if (pos > sb->len)
264 die("`pos' is too far after the end of the buffer");
265 va_copy(cp, ap);
266 len = vsnprintf(sb->buf + sb->len, 0, fmt, cp);
267 va_end(cp);
268 if (len < 0)
269 BUG("your vsnprintf is broken (returned %d)", len);
270 if (!len)
271 return; /* nothing to do */
272 if (unsigned_add_overflows(sb->len, len))
273 die("you want to use way too much memory");
274 strbuf_grow(sb, len);
275 memmove(sb->buf + pos + len, sb->buf + pos, sb->len - pos);
276 /* vsnprintf() will append a NUL, overwriting one of our characters */
277 save = sb->buf[pos + len];
278 len2 = vsnprintf(sb->buf + pos, len + 1, fmt, ap);
279 sb->buf[pos + len] = save;
280 if (len2 != len)
281 BUG("your vsnprintf is broken (returns inconsistent lengths)");
282 strbuf_setlen(sb, sb->len + len);
285 void strbuf_insertf(struct strbuf *sb, size_t pos, const char *fmt, ...)
287 va_list ap;
288 va_start(ap, fmt);
289 strbuf_vinsertf(sb, pos, fmt, ap);
290 va_end(ap);
293 void strbuf_remove(struct strbuf *sb, size_t pos, size_t len)
295 strbuf_splice(sb, pos, len, "", 0);
298 void strbuf_add(struct strbuf *sb, const void *data, size_t len)
300 strbuf_grow(sb, len);
301 memcpy(sb->buf + sb->len, data, len);
302 strbuf_setlen(sb, sb->len + len);
305 void strbuf_addbuf(struct strbuf *sb, const struct strbuf *sb2)
307 strbuf_grow(sb, sb2->len);
308 memcpy(sb->buf + sb->len, sb2->buf, sb2->len);
309 strbuf_setlen(sb, sb->len + sb2->len);
312 const char *strbuf_join_argv(struct strbuf *buf,
313 int argc, const char **argv, char delim)
315 if (!argc)
316 return buf->buf;
318 strbuf_addstr(buf, *argv);
319 while (--argc) {
320 strbuf_addch(buf, delim);
321 strbuf_addstr(buf, *(++argv));
324 return buf->buf;
327 void strbuf_addchars(struct strbuf *sb, int c, size_t n)
329 strbuf_grow(sb, n);
330 memset(sb->buf + sb->len, c, n);
331 strbuf_setlen(sb, sb->len + n);
334 void strbuf_addf(struct strbuf *sb, const char *fmt, ...)
336 va_list ap;
337 va_start(ap, fmt);
338 strbuf_vaddf(sb, fmt, ap);
339 va_end(ap);
342 static void add_lines(struct strbuf *out,
343 const char *prefix1,
344 const char *prefix2,
345 const char *buf, size_t size)
347 while (size) {
348 const char *prefix;
349 const char *next = memchr(buf, '\n', size);
350 next = next ? (next + 1) : (buf + size);
352 prefix = ((prefix2 && (buf[0] == '\n' || buf[0] == '\t'))
353 ? prefix2 : prefix1);
354 strbuf_addstr(out, prefix);
355 strbuf_add(out, buf, next - buf);
356 size -= next - buf;
357 buf = next;
359 strbuf_complete_line(out);
362 void strbuf_add_commented_lines(struct strbuf *out, const char *buf,
363 size_t size, char comment_line_char)
365 static char prefix1[3];
366 static char prefix2[2];
368 if (prefix1[0] != comment_line_char) {
369 xsnprintf(prefix1, sizeof(prefix1), "%c ", comment_line_char);
370 xsnprintf(prefix2, sizeof(prefix2), "%c", comment_line_char);
372 add_lines(out, prefix1, prefix2, buf, size);
375 void strbuf_commented_addf(struct strbuf *sb, char comment_line_char,
376 const char *fmt, ...)
378 va_list params;
379 struct strbuf buf = STRBUF_INIT;
380 int incomplete_line = sb->len && sb->buf[sb->len - 1] != '\n';
382 va_start(params, fmt);
383 strbuf_vaddf(&buf, fmt, params);
384 va_end(params);
386 strbuf_add_commented_lines(sb, buf.buf, buf.len, comment_line_char);
387 if (incomplete_line)
388 sb->buf[--sb->len] = '\0';
390 strbuf_release(&buf);
393 void strbuf_vaddf(struct strbuf *sb, const char *fmt, va_list ap)
395 int len;
396 va_list cp;
398 if (!strbuf_avail(sb))
399 strbuf_grow(sb, 64);
400 va_copy(cp, ap);
401 len = vsnprintf(sb->buf + sb->len, sb->alloc - sb->len, fmt, cp);
402 va_end(cp);
403 if (len < 0)
404 BUG("your vsnprintf is broken (returned %d)", len);
405 if (len > strbuf_avail(sb)) {
406 strbuf_grow(sb, len);
407 len = vsnprintf(sb->buf + sb->len, sb->alloc - sb->len, fmt, ap);
408 if (len > strbuf_avail(sb))
409 BUG("your vsnprintf is broken (insatiable)");
411 strbuf_setlen(sb, sb->len + len);
414 int strbuf_expand_step(struct strbuf *sb, const char **formatp)
416 const char *format = *formatp;
417 const char *percent = strchrnul(format, '%');
419 strbuf_add(sb, format, percent - format);
420 if (!*percent)
421 return 0;
422 *formatp = percent + 1;
423 return 1;
426 size_t strbuf_expand_literal(struct strbuf *sb, const char *placeholder)
428 int ch;
430 switch (placeholder[0]) {
431 case 'n': /* newline */
432 strbuf_addch(sb, '\n');
433 return 1;
434 case 'x':
435 /* %x00 == NUL, %x0a == LF, etc. */
436 ch = hex2chr(placeholder + 1);
437 if (ch < 0)
438 return 0;
439 strbuf_addch(sb, ch);
440 return 3;
442 return 0;
445 void strbuf_addbuf_percentquote(struct strbuf *dst, const struct strbuf *src)
447 size_t i, len = src->len;
449 for (i = 0; i < len; i++) {
450 if (src->buf[i] == '%')
451 strbuf_addch(dst, '%');
452 strbuf_addch(dst, src->buf[i]);
456 #define URL_UNSAFE_CHARS " <>\"%{}|\\^`:?#[]@!$&'()*+,;="
458 void strbuf_add_percentencode(struct strbuf *dst, const char *src, int flags)
460 size_t i, len = strlen(src);
462 for (i = 0; i < len; i++) {
463 unsigned char ch = src[i];
464 if (ch <= 0x1F || ch >= 0x7F ||
465 (ch == '/' && (flags & STRBUF_ENCODE_SLASH)) ||
466 strchr(URL_UNSAFE_CHARS, ch))
467 strbuf_addf(dst, "%%%02X", (unsigned char)ch);
468 else
469 strbuf_addch(dst, ch);
473 size_t strbuf_fread(struct strbuf *sb, size_t size, FILE *f)
475 size_t res;
476 size_t oldalloc = sb->alloc;
478 strbuf_grow(sb, size);
479 res = fread(sb->buf + sb->len, 1, size, f);
480 if (res > 0)
481 strbuf_setlen(sb, sb->len + res);
482 else if (oldalloc == 0)
483 strbuf_release(sb);
484 return res;
487 ssize_t strbuf_read(struct strbuf *sb, int fd, size_t hint)
489 size_t oldlen = sb->len;
490 size_t oldalloc = sb->alloc;
492 strbuf_grow(sb, hint ? hint : 8192);
493 for (;;) {
494 ssize_t want = sb->alloc - sb->len - 1;
495 ssize_t got = read_in_full(fd, sb->buf + sb->len, want);
497 if (got < 0) {
498 if (oldalloc == 0)
499 strbuf_release(sb);
500 else
501 strbuf_setlen(sb, oldlen);
502 return -1;
504 sb->len += got;
505 if (got < want)
506 break;
507 strbuf_grow(sb, 8192);
510 sb->buf[sb->len] = '\0';
511 return sb->len - oldlen;
514 ssize_t strbuf_read_once(struct strbuf *sb, int fd, size_t hint)
516 size_t oldalloc = sb->alloc;
517 ssize_t cnt;
519 strbuf_grow(sb, hint ? hint : 8192);
520 cnt = xread(fd, sb->buf + sb->len, sb->alloc - sb->len - 1);
521 if (cnt > 0)
522 strbuf_setlen(sb, sb->len + cnt);
523 else if (oldalloc == 0)
524 strbuf_release(sb);
525 return cnt;
528 ssize_t strbuf_write(struct strbuf *sb, FILE *f)
530 return sb->len ? fwrite(sb->buf, 1, sb->len, f) : 0;
533 #define STRBUF_MAXLINK (2*PATH_MAX)
535 int strbuf_readlink(struct strbuf *sb, const char *path, size_t hint)
537 size_t oldalloc = sb->alloc;
539 if (hint < 32)
540 hint = 32;
542 while (hint < STRBUF_MAXLINK) {
543 ssize_t len;
545 strbuf_grow(sb, hint);
546 len = readlink(path, sb->buf, hint);
547 if (len < 0) {
548 if (errno != ERANGE)
549 break;
550 } else if (len < hint) {
551 strbuf_setlen(sb, len);
552 return 0;
555 /* .. the buffer was too small - try again */
556 hint *= 2;
558 if (oldalloc == 0)
559 strbuf_release(sb);
560 return -1;
563 int strbuf_getcwd(struct strbuf *sb)
565 size_t oldalloc = sb->alloc;
566 size_t guessed_len = 128;
568 for (;; guessed_len *= 2) {
569 strbuf_grow(sb, guessed_len);
570 if (getcwd(sb->buf, sb->alloc)) {
571 strbuf_setlen(sb, strlen(sb->buf));
572 return 0;
576 * If getcwd(3) is implemented as a syscall that falls
577 * back to a regular lookup using readdir(3) etc. then
578 * we may be able to avoid EACCES by providing enough
579 * space to the syscall as it's not necessarily bound
580 * to the same restrictions as the fallback.
582 if (errno == EACCES && guessed_len < PATH_MAX)
583 continue;
585 if (errno != ERANGE)
586 break;
588 if (oldalloc == 0)
589 strbuf_release(sb);
590 else
591 strbuf_reset(sb);
592 return -1;
595 #ifdef HAVE_GETDELIM
596 int strbuf_getwholeline(struct strbuf *sb, FILE *fp, int term)
598 ssize_t r;
600 if (feof(fp))
601 return EOF;
603 strbuf_reset(sb);
605 /* Translate slopbuf to NULL, as we cannot call realloc on it */
606 if (!sb->alloc)
607 sb->buf = NULL;
608 errno = 0;
609 r = getdelim(&sb->buf, &sb->alloc, term, fp);
611 if (r > 0) {
612 sb->len = r;
613 return 0;
615 assert(r == -1);
618 * Normally we would have called xrealloc, which will try to free
619 * memory and recover. But we have no way to tell getdelim() to do so.
620 * Worse, we cannot try to recover ENOMEM ourselves, because we have
621 * no idea how many bytes were read by getdelim.
623 * Dying here is reasonable. It mirrors what xrealloc would do on
624 * catastrophic memory failure. We skip the opportunity to free pack
625 * memory and retry, but that's unlikely to help for a malloc small
626 * enough to hold a single line of input, anyway.
628 if (errno == ENOMEM)
629 die("Out of memory, getdelim failed");
632 * Restore strbuf invariants; if getdelim left us with a NULL pointer,
633 * we can just re-init, but otherwise we should make sure that our
634 * length is empty, and that the result is NUL-terminated.
636 if (!sb->buf)
637 strbuf_init(sb, 0);
638 else
639 strbuf_reset(sb);
640 return EOF;
642 #else
643 int strbuf_getwholeline(struct strbuf *sb, FILE *fp, int term)
645 int ch;
647 if (feof(fp))
648 return EOF;
650 strbuf_reset(sb);
651 flockfile(fp);
652 while ((ch = getc_unlocked(fp)) != EOF) {
653 if (!strbuf_avail(sb))
654 strbuf_grow(sb, 1);
655 sb->buf[sb->len++] = ch;
656 if (ch == term)
657 break;
659 funlockfile(fp);
660 if (ch == EOF && sb->len == 0)
661 return EOF;
663 sb->buf[sb->len] = '\0';
664 return 0;
666 #endif
668 int strbuf_appendwholeline(struct strbuf *sb, FILE *fp, int term)
670 struct strbuf line = STRBUF_INIT;
671 if (strbuf_getwholeline(&line, fp, term))
672 return EOF;
673 strbuf_addbuf(sb, &line);
674 strbuf_release(&line);
675 return 0;
678 static int strbuf_getdelim(struct strbuf *sb, FILE *fp, int term)
680 if (strbuf_getwholeline(sb, fp, term))
681 return EOF;
682 if (sb->buf[sb->len - 1] == term)
683 strbuf_setlen(sb, sb->len - 1);
684 return 0;
687 int strbuf_getdelim_strip_crlf(struct strbuf *sb, FILE *fp, int term)
689 if (strbuf_getwholeline(sb, fp, term))
690 return EOF;
691 if (term == '\n' && sb->buf[sb->len - 1] == '\n') {
692 strbuf_setlen(sb, sb->len - 1);
693 if (sb->len && sb->buf[sb->len - 1] == '\r')
694 strbuf_setlen(sb, sb->len - 1);
696 return 0;
699 int strbuf_getline(struct strbuf *sb, FILE *fp)
701 return strbuf_getdelim_strip_crlf(sb, fp, '\n');
704 int strbuf_getline_lf(struct strbuf *sb, FILE *fp)
706 return strbuf_getdelim(sb, fp, '\n');
709 int strbuf_getline_nul(struct strbuf *sb, FILE *fp)
711 return strbuf_getdelim(sb, fp, '\0');
714 int strbuf_getwholeline_fd(struct strbuf *sb, int fd, int term)
716 strbuf_reset(sb);
718 while (1) {
719 char ch;
720 ssize_t len = xread(fd, &ch, 1);
721 if (len <= 0)
722 return EOF;
723 strbuf_addch(sb, ch);
724 if (ch == term)
725 break;
727 return 0;
730 ssize_t strbuf_read_file(struct strbuf *sb, const char *path, size_t hint)
732 int fd;
733 ssize_t len;
734 int saved_errno;
736 fd = open(path, O_RDONLY);
737 if (fd < 0)
738 return -1;
739 len = strbuf_read(sb, fd, hint);
740 saved_errno = errno;
741 close(fd);
742 if (len < 0) {
743 errno = saved_errno;
744 return -1;
747 return len;
750 void strbuf_add_lines(struct strbuf *out, const char *prefix,
751 const char *buf, size_t size)
753 add_lines(out, prefix, NULL, buf, size);
756 void strbuf_addstr_xml_quoted(struct strbuf *buf, const char *s)
758 while (*s) {
759 size_t len = strcspn(s, "\"<>&");
760 strbuf_add(buf, s, len);
761 s += len;
762 switch (*s) {
763 case '"':
764 strbuf_addstr(buf, "&quot;");
765 break;
766 case '<':
767 strbuf_addstr(buf, "&lt;");
768 break;
769 case '>':
770 strbuf_addstr(buf, "&gt;");
771 break;
772 case '&':
773 strbuf_addstr(buf, "&amp;");
774 break;
775 case 0:
776 return;
778 s++;
782 static void strbuf_add_urlencode(struct strbuf *sb, const char *s, size_t len,
783 char_predicate allow_unencoded_fn)
785 strbuf_grow(sb, len);
786 while (len--) {
787 char ch = *s++;
788 if (allow_unencoded_fn(ch))
789 strbuf_addch(sb, ch);
790 else
791 strbuf_addf(sb, "%%%02x", (unsigned char)ch);
795 void strbuf_addstr_urlencode(struct strbuf *sb, const char *s,
796 char_predicate allow_unencoded_fn)
798 strbuf_add_urlencode(sb, s, strlen(s), allow_unencoded_fn);
801 static void strbuf_humanise(struct strbuf *buf, off_t bytes,
802 int humanise_rate)
804 if (bytes > 1 << 30) {
805 strbuf_addf(buf,
806 humanise_rate == 0 ?
807 /* TRANSLATORS: IEC 80000-13:2008 gibibyte */
808 _("%u.%2.2u GiB") :
809 /* TRANSLATORS: IEC 80000-13:2008 gibibyte/second */
810 _("%u.%2.2u GiB/s"),
811 (unsigned)(bytes >> 30),
812 (unsigned)(bytes & ((1 << 30) - 1)) / 10737419);
813 } else if (bytes > 1 << 20) {
814 unsigned x = bytes + 5243; /* for rounding */
815 strbuf_addf(buf,
816 humanise_rate == 0 ?
817 /* TRANSLATORS: IEC 80000-13:2008 mebibyte */
818 _("%u.%2.2u MiB") :
819 /* TRANSLATORS: IEC 80000-13:2008 mebibyte/second */
820 _("%u.%2.2u MiB/s"),
821 x >> 20, ((x & ((1 << 20) - 1)) * 100) >> 20);
822 } else if (bytes > 1 << 10) {
823 unsigned x = bytes + 5; /* for rounding */
824 strbuf_addf(buf,
825 humanise_rate == 0 ?
826 /* TRANSLATORS: IEC 80000-13:2008 kibibyte */
827 _("%u.%2.2u KiB") :
828 /* TRANSLATORS: IEC 80000-13:2008 kibibyte/second */
829 _("%u.%2.2u KiB/s"),
830 x >> 10, ((x & ((1 << 10) - 1)) * 100) >> 10);
831 } else {
832 strbuf_addf(buf,
833 humanise_rate == 0 ?
834 /* TRANSLATORS: IEC 80000-13:2008 byte */
835 Q_("%u byte", "%u bytes", bytes) :
836 /* TRANSLATORS: IEC 80000-13:2008 byte/second */
837 Q_("%u byte/s", "%u bytes/s", bytes),
838 (unsigned)bytes);
842 void strbuf_humanise_bytes(struct strbuf *buf, off_t bytes)
844 strbuf_humanise(buf, bytes, 0);
847 void strbuf_humanise_rate(struct strbuf *buf, off_t bytes)
849 strbuf_humanise(buf, bytes, 1);
852 int printf_ln(const char *fmt, ...)
854 int ret;
855 va_list ap;
856 va_start(ap, fmt);
857 ret = vprintf(fmt, ap);
858 va_end(ap);
859 if (ret < 0 || putchar('\n') == EOF)
860 return -1;
861 return ret + 1;
864 int fprintf_ln(FILE *fp, const char *fmt, ...)
866 int ret;
867 va_list ap;
868 va_start(ap, fmt);
869 ret = vfprintf(fp, fmt, ap);
870 va_end(ap);
871 if (ret < 0 || putc('\n', fp) == EOF)
872 return -1;
873 return ret + 1;
876 char *xstrdup_tolower(const char *string)
878 char *result;
879 size_t len, i;
881 len = strlen(string);
882 result = xmallocz(len);
883 for (i = 0; i < len; i++)
884 result[i] = tolower(string[i]);
885 return result;
888 char *xstrdup_toupper(const char *string)
890 char *result;
891 size_t len, i;
893 len = strlen(string);
894 result = xmallocz(len);
895 for (i = 0; i < len; i++)
896 result[i] = toupper(string[i]);
897 return result;
900 char *xstrvfmt(const char *fmt, va_list ap)
902 struct strbuf buf = STRBUF_INIT;
903 strbuf_vaddf(&buf, fmt, ap);
904 return strbuf_detach(&buf, NULL);
907 char *xstrfmt(const char *fmt, ...)
909 va_list ap;
910 char *ret;
912 va_start(ap, fmt);
913 ret = xstrvfmt(fmt, ap);
914 va_end(ap);
916 return ret;
919 void strbuf_addftime(struct strbuf *sb, const char *fmt, const struct tm *tm,
920 int tz_offset, int suppress_tz_name)
922 struct strbuf munged_fmt = STRBUF_INIT;
923 size_t hint = 128;
924 size_t len;
926 if (!*fmt)
927 return;
930 * There is no portable way to pass timezone information to
931 * strftime, so we handle %z and %Z here. Likewise '%s', because
932 * going back to an epoch time requires knowing the zone.
934 * Note that tz_offset is in the "[-+]HHMM" decimal form; this is what
935 * we want for %z, but the computation for %s has to convert to number
936 * of seconds.
938 while (strbuf_expand_step(&munged_fmt, &fmt)) {
939 if (skip_prefix(fmt, "%", &fmt))
940 strbuf_addstr(&munged_fmt, "%%");
941 else if (skip_prefix(fmt, "s", &fmt))
942 strbuf_addf(&munged_fmt, "%"PRItime,
943 (timestamp_t)tm_to_time_t(tm) -
944 3600 * (tz_offset / 100) -
945 60 * (tz_offset % 100));
946 else if (skip_prefix(fmt, "z", &fmt))
947 strbuf_addf(&munged_fmt, "%+05d", tz_offset);
948 else if (suppress_tz_name && skip_prefix(fmt, "Z", &fmt))
949 ; /* nothing */
950 else
951 strbuf_addch(&munged_fmt, '%');
953 fmt = munged_fmt.buf;
955 strbuf_grow(sb, hint);
956 len = strftime(sb->buf + sb->len, sb->alloc - sb->len, fmt, tm);
958 if (!len) {
960 * strftime reports "0" if it could not fit the result in the buffer.
961 * Unfortunately, it also reports "0" if the requested time string
962 * takes 0 bytes. So our strategy is to munge the format so that the
963 * output contains at least one character, and then drop the extra
964 * character before returning.
966 strbuf_addch(&munged_fmt, ' ');
967 while (!len) {
968 hint *= 2;
969 strbuf_grow(sb, hint);
970 len = strftime(sb->buf + sb->len, sb->alloc - sb->len,
971 munged_fmt.buf, tm);
973 len--; /* drop munged space */
975 strbuf_release(&munged_fmt);
976 strbuf_setlen(sb, sb->len + len);
980 * Returns the length of a line, without trailing spaces.
982 * If the line ends with newline, it will be removed too.
984 static size_t cleanup(char *line, size_t len)
986 while (len) {
987 unsigned char c = line[len - 1];
988 if (!isspace(c))
989 break;
990 len--;
993 return len;
997 * Remove empty lines from the beginning and end
998 * and also trailing spaces from every line.
1000 * Turn multiple consecutive empty lines between paragraphs
1001 * into just one empty line.
1003 * If the input has only empty lines and spaces,
1004 * no output will be produced.
1006 * If last line does not have a newline at the end, one is added.
1008 * Pass a non-NUL comment_line_char to skip every line starting
1009 * with it.
1011 void strbuf_stripspace(struct strbuf *sb, char comment_line_char)
1013 size_t empties = 0;
1014 size_t i, j, len, newlen;
1015 char *eol;
1017 /* We may have to add a newline. */
1018 strbuf_grow(sb, 1);
1020 for (i = j = 0; i < sb->len; i += len, j += newlen) {
1021 eol = memchr(sb->buf + i, '\n', sb->len - i);
1022 len = eol ? eol - (sb->buf + i) + 1 : sb->len - i;
1024 if (comment_line_char && len &&
1025 sb->buf[i] == comment_line_char) {
1026 newlen = 0;
1027 continue;
1029 newlen = cleanup(sb->buf + i, len);
1031 /* Not just an empty line? */
1032 if (newlen) {
1033 if (empties > 0 && j > 0)
1034 sb->buf[j++] = '\n';
1035 empties = 0;
1036 memmove(sb->buf + j, sb->buf + i, newlen);
1037 sb->buf[newlen + j++] = '\n';
1038 } else {
1039 empties++;
1043 strbuf_setlen(sb, j);
1046 void strbuf_strip_file_from_path(struct strbuf *sb)
1048 char *path_sep = find_last_dir_sep(sb->buf);
1049 strbuf_setlen(sb, path_sep ? path_sep - sb->buf + 1 : 0);