The fifteenth batch
[git/debian.git] / strbuf.c
blob3d2189a7f648dcba44e85aa1b2047b00b3f871df
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 starts_with_mem(const char *str, size_t len, const char *prefix)
29 const char *end = str + len;
30 for (; ; str++, prefix++) {
31 if (!*prefix)
32 return 1;
33 else if (str == end || *str != *prefix)
34 return 0;
38 int skip_to_optional_arg_default(const char *str, const char *prefix,
39 const char **arg, const char *def)
41 const char *p;
43 if (!skip_prefix(str, prefix, &p))
44 return 0;
46 if (!*p) {
47 if (arg)
48 *arg = def;
49 return 1;
52 if (*p != '=')
53 return 0;
55 if (arg)
56 *arg = p + 1;
57 return 1;
61 * Used as the default ->buf value, so that people can always assume
62 * buf is non NULL and ->buf is NUL terminated even for a freshly
63 * initialized strbuf.
65 char strbuf_slopbuf[1];
67 void strbuf_init(struct strbuf *sb, size_t hint)
69 struct strbuf blank = STRBUF_INIT;
70 memcpy(sb, &blank, sizeof(*sb));
71 if (hint)
72 strbuf_grow(sb, hint);
75 void strbuf_release(struct strbuf *sb)
77 if (sb->alloc) {
78 free(sb->buf);
79 strbuf_init(sb, 0);
83 char *strbuf_detach(struct strbuf *sb, size_t *sz)
85 char *res;
86 strbuf_grow(sb, 0);
87 res = sb->buf;
88 if (sz)
89 *sz = sb->len;
90 strbuf_init(sb, 0);
91 return res;
94 void strbuf_attach(struct strbuf *sb, void *buf, size_t len, size_t alloc)
96 strbuf_release(sb);
97 sb->buf = buf;
98 sb->len = len;
99 sb->alloc = alloc;
100 strbuf_grow(sb, 0);
101 sb->buf[sb->len] = '\0';
104 void strbuf_grow(struct strbuf *sb, size_t extra)
106 int new_buf = !sb->alloc;
107 if (unsigned_add_overflows(extra, 1) ||
108 unsigned_add_overflows(sb->len, extra + 1))
109 die("you want to use way too much memory");
110 if (new_buf)
111 sb->buf = NULL;
112 ALLOC_GROW(sb->buf, sb->len + extra + 1, sb->alloc);
113 if (new_buf)
114 sb->buf[0] = '\0';
117 void strbuf_trim(struct strbuf *sb)
119 strbuf_rtrim(sb);
120 strbuf_ltrim(sb);
123 void strbuf_rtrim(struct strbuf *sb)
125 while (sb->len > 0 && isspace((unsigned char)sb->buf[sb->len - 1]))
126 sb->len--;
127 sb->buf[sb->len] = '\0';
130 void strbuf_trim_trailing_dir_sep(struct strbuf *sb)
132 while (sb->len > 0 && is_dir_sep((unsigned char)sb->buf[sb->len - 1]))
133 sb->len--;
134 sb->buf[sb->len] = '\0';
137 void strbuf_trim_trailing_newline(struct strbuf *sb)
139 if (sb->len > 0 && sb->buf[sb->len - 1] == '\n') {
140 if (--sb->len > 0 && sb->buf[sb->len - 1] == '\r')
141 --sb->len;
142 sb->buf[sb->len] = '\0';
146 void strbuf_ltrim(struct strbuf *sb)
148 char *b = sb->buf;
149 while (sb->len > 0 && isspace(*b)) {
150 b++;
151 sb->len--;
153 memmove(sb->buf, b, sb->len);
154 sb->buf[sb->len] = '\0';
157 int strbuf_reencode(struct strbuf *sb, const char *from, const char *to)
159 char *out;
160 size_t len;
162 if (same_encoding(from, to))
163 return 0;
165 out = reencode_string_len(sb->buf, sb->len, to, from, &len);
166 if (!out)
167 return -1;
169 strbuf_attach(sb, out, len, len);
170 return 0;
173 void strbuf_tolower(struct strbuf *sb)
175 char *p = sb->buf, *end = sb->buf + sb->len;
176 for (; p < end; p++)
177 *p = tolower(*p);
180 struct strbuf **strbuf_split_buf(const char *str, size_t slen,
181 int terminator, int max)
183 struct strbuf **ret = NULL;
184 size_t nr = 0, alloc = 0;
185 struct strbuf *t;
187 while (slen) {
188 int len = slen;
189 if (max <= 0 || nr + 1 < max) {
190 const char *end = memchr(str, terminator, slen);
191 if (end)
192 len = end - str + 1;
194 t = xmalloc(sizeof(struct strbuf));
195 strbuf_init(t, len);
196 strbuf_add(t, str, len);
197 ALLOC_GROW(ret, nr + 2, alloc);
198 ret[nr++] = t;
199 str += len;
200 slen -= len;
202 ALLOC_GROW(ret, nr + 1, alloc); /* In case string was empty */
203 ret[nr] = NULL;
204 return ret;
207 void strbuf_add_separated_string_list(struct strbuf *str,
208 const char *sep,
209 struct string_list *slist)
211 struct string_list_item *item;
212 int sep_needed = 0;
214 for_each_string_list_item(item, slist) {
215 if (sep_needed)
216 strbuf_addstr(str, sep);
217 strbuf_addstr(str, item->string);
218 sep_needed = 1;
222 void strbuf_list_free(struct strbuf **sbs)
224 struct strbuf **s = sbs;
226 if (!s)
227 return;
228 while (*s) {
229 strbuf_release(*s);
230 free(*s++);
232 free(sbs);
235 int strbuf_cmp(const struct strbuf *a, const struct strbuf *b)
237 size_t len = a->len < b->len ? a->len: b->len;
238 int cmp = memcmp(a->buf, b->buf, len);
239 if (cmp)
240 return cmp;
241 return a->len < b->len ? -1: a->len != b->len;
244 void strbuf_splice(struct strbuf *sb, size_t pos, size_t len,
245 const void *data, size_t dlen)
247 if (unsigned_add_overflows(pos, len))
248 die("you want to use way too much memory");
249 if (pos > sb->len)
250 die("`pos' is too far after the end of the buffer");
251 if (pos + len > sb->len)
252 die("`pos + len' is too far after the end of the buffer");
254 if (dlen >= len)
255 strbuf_grow(sb, dlen - len);
256 memmove(sb->buf + pos + dlen,
257 sb->buf + pos + len,
258 sb->len - pos - len);
259 memcpy(sb->buf + pos, data, dlen);
260 strbuf_setlen(sb, sb->len + dlen - len);
263 void strbuf_insert(struct strbuf *sb, size_t pos, const void *data, size_t len)
265 strbuf_splice(sb, pos, 0, data, len);
268 void strbuf_vinsertf(struct strbuf *sb, size_t pos, const char *fmt, va_list ap)
270 int len, len2;
271 char save;
272 va_list cp;
274 if (pos > sb->len)
275 die("`pos' is too far after the end of the buffer");
276 va_copy(cp, ap);
277 len = vsnprintf(sb->buf + sb->len, 0, fmt, cp);
278 va_end(cp);
279 if (len < 0)
280 die(_("unable to format message: %s"), fmt);
281 if (!len)
282 return; /* nothing to do */
283 if (unsigned_add_overflows(sb->len, len))
284 die("you want to use way too much memory");
285 strbuf_grow(sb, len);
286 memmove(sb->buf + pos + len, sb->buf + pos, sb->len - pos);
287 /* vsnprintf() will append a NUL, overwriting one of our characters */
288 save = sb->buf[pos + len];
289 len2 = vsnprintf(sb->buf + pos, len + 1, fmt, ap);
290 sb->buf[pos + len] = save;
291 if (len2 != len)
292 BUG("your vsnprintf is broken (returns inconsistent lengths)");
293 strbuf_setlen(sb, sb->len + len);
296 void strbuf_insertf(struct strbuf *sb, size_t pos, const char *fmt, ...)
298 va_list ap;
299 va_start(ap, fmt);
300 strbuf_vinsertf(sb, pos, fmt, ap);
301 va_end(ap);
304 void strbuf_remove(struct strbuf *sb, size_t pos, size_t len)
306 strbuf_splice(sb, pos, len, "", 0);
309 void strbuf_add(struct strbuf *sb, const void *data, size_t len)
311 strbuf_grow(sb, len);
312 memcpy(sb->buf + sb->len, data, len);
313 strbuf_setlen(sb, sb->len + len);
316 void strbuf_addstrings(struct strbuf *sb, const char *s, size_t n)
318 size_t len = strlen(s);
320 strbuf_grow(sb, st_mult(len, n));
321 for (size_t i = 0; i < n; i++)
322 strbuf_add(sb, s, len);
325 void strbuf_addbuf(struct strbuf *sb, const struct strbuf *sb2)
327 strbuf_grow(sb, sb2->len);
328 memcpy(sb->buf + sb->len, sb2->buf, sb2->len);
329 strbuf_setlen(sb, sb->len + sb2->len);
332 const char *strbuf_join_argv(struct strbuf *buf,
333 int argc, const char **argv, char delim)
335 if (!argc)
336 return buf->buf;
338 strbuf_addstr(buf, *argv);
339 while (--argc) {
340 strbuf_addch(buf, delim);
341 strbuf_addstr(buf, *(++argv));
344 return buf->buf;
347 void strbuf_addchars(struct strbuf *sb, int c, size_t n)
349 strbuf_grow(sb, n);
350 memset(sb->buf + sb->len, c, n);
351 strbuf_setlen(sb, sb->len + n);
354 void strbuf_addf(struct strbuf *sb, const char *fmt, ...)
356 va_list ap;
357 va_start(ap, fmt);
358 strbuf_vaddf(sb, fmt, ap);
359 va_end(ap);
362 static void add_lines(struct strbuf *out,
363 const char *prefix,
364 const char *buf, size_t size,
365 int space_after_prefix)
367 while (size) {
368 const char *next = memchr(buf, '\n', size);
369 next = next ? (next + 1) : (buf + size);
371 strbuf_addstr(out, prefix);
372 if (space_after_prefix && buf[0] != '\n' && buf[0] != '\t')
373 strbuf_addch(out, ' ');
374 strbuf_add(out, buf, next - buf);
375 size -= next - buf;
376 buf = next;
378 strbuf_complete_line(out);
381 void strbuf_add_commented_lines(struct strbuf *out, const char *buf,
382 size_t size, const char *comment_prefix)
384 add_lines(out, comment_prefix, buf, size, 1);
387 void strbuf_commented_addf(struct strbuf *sb, const char *comment_prefix,
388 const char *fmt, ...)
390 va_list params;
391 struct strbuf buf = STRBUF_INIT;
392 int incomplete_line = sb->len && sb->buf[sb->len - 1] != '\n';
394 va_start(params, fmt);
395 strbuf_vaddf(&buf, fmt, params);
396 va_end(params);
398 strbuf_add_commented_lines(sb, buf.buf, buf.len, comment_prefix);
399 if (incomplete_line)
400 sb->buf[--sb->len] = '\0';
402 strbuf_release(&buf);
405 void strbuf_vaddf(struct strbuf *sb, const char *fmt, va_list ap)
407 int len;
408 va_list cp;
410 if (!strbuf_avail(sb))
411 strbuf_grow(sb, 64);
412 va_copy(cp, ap);
413 len = vsnprintf(sb->buf + sb->len, sb->alloc - sb->len, fmt, cp);
414 va_end(cp);
415 if (len < 0)
416 die(_("unable to format message: %s"), fmt);
417 if (len > strbuf_avail(sb)) {
418 strbuf_grow(sb, len);
419 len = vsnprintf(sb->buf + sb->len, sb->alloc - sb->len, fmt, ap);
420 if (len > strbuf_avail(sb))
421 BUG("your vsnprintf is broken (insatiable)");
423 strbuf_setlen(sb, sb->len + len);
426 int strbuf_expand_step(struct strbuf *sb, const char **formatp)
428 const char *format = *formatp;
429 const char *percent = strchrnul(format, '%');
431 strbuf_add(sb, format, percent - format);
432 if (!*percent)
433 return 0;
434 *formatp = percent + 1;
435 return 1;
438 size_t strbuf_expand_literal(struct strbuf *sb, const char *placeholder)
440 int ch;
442 switch (placeholder[0]) {
443 case 'n': /* newline */
444 strbuf_addch(sb, '\n');
445 return 1;
446 case 'x':
447 /* %x00 == NUL, %x0a == LF, etc. */
448 ch = hex2chr(placeholder + 1);
449 if (ch < 0)
450 return 0;
451 strbuf_addch(sb, ch);
452 return 3;
454 return 0;
457 void strbuf_expand_bad_format(const char *format, const char *command)
459 const char *end;
461 if (*format != '(')
462 /* TRANSLATORS: The first %s is a command like "ls-tree". */
463 die(_("bad %s format: element '%s' does not start with '('"),
464 command, format);
466 end = strchr(format + 1, ')');
467 if (!end)
468 /* TRANSLATORS: The first %s is a command like "ls-tree". */
469 die(_("bad %s format: element '%s' does not end in ')'"),
470 command, format);
472 /* TRANSLATORS: %s is a command like "ls-tree". */
473 die(_("bad %s format: %%%.*s"),
474 command, (int)(end - format + 1), format);
477 void strbuf_addbuf_percentquote(struct strbuf *dst, const struct strbuf *src)
479 size_t i, len = src->len;
481 for (i = 0; i < len; i++) {
482 if (src->buf[i] == '%')
483 strbuf_addch(dst, '%');
484 strbuf_addch(dst, src->buf[i]);
488 #define URL_UNSAFE_CHARS " <>\"%{}|\\^`:?#[]@!$&'()*+,;="
490 void strbuf_add_percentencode(struct strbuf *dst, const char *src, int flags)
492 size_t i, len = strlen(src);
494 for (i = 0; i < len; i++) {
495 unsigned char ch = src[i];
496 if (ch <= 0x1F || ch >= 0x7F ||
497 (ch == '/' && (flags & STRBUF_ENCODE_SLASH)) ||
498 strchr(URL_UNSAFE_CHARS, ch))
499 strbuf_addf(dst, "%%%02X", (unsigned char)ch);
500 else
501 strbuf_addch(dst, ch);
505 size_t strbuf_fread(struct strbuf *sb, size_t size, FILE *f)
507 size_t res;
508 size_t oldalloc = sb->alloc;
510 strbuf_grow(sb, size);
511 res = fread(sb->buf + sb->len, 1, size, f);
512 if (res > 0)
513 strbuf_setlen(sb, sb->len + res);
514 else if (oldalloc == 0)
515 strbuf_release(sb);
516 return res;
519 ssize_t strbuf_read(struct strbuf *sb, int fd, size_t hint)
521 size_t oldlen = sb->len;
522 size_t oldalloc = sb->alloc;
524 strbuf_grow(sb, hint ? hint : 8192);
525 for (;;) {
526 ssize_t want = sb->alloc - sb->len - 1;
527 ssize_t got = read_in_full(fd, sb->buf + sb->len, want);
529 if (got < 0) {
530 if (oldalloc == 0)
531 strbuf_release(sb);
532 else
533 strbuf_setlen(sb, oldlen);
534 return -1;
536 sb->len += got;
537 if (got < want)
538 break;
539 strbuf_grow(sb, 8192);
542 sb->buf[sb->len] = '\0';
543 return sb->len - oldlen;
546 ssize_t strbuf_read_once(struct strbuf *sb, int fd, size_t hint)
548 size_t oldalloc = sb->alloc;
549 ssize_t cnt;
551 strbuf_grow(sb, hint ? hint : 8192);
552 cnt = xread(fd, sb->buf + sb->len, sb->alloc - sb->len - 1);
553 if (cnt > 0)
554 strbuf_setlen(sb, sb->len + cnt);
555 else if (oldalloc == 0)
556 strbuf_release(sb);
557 return cnt;
560 ssize_t strbuf_write(struct strbuf *sb, FILE *f)
562 return sb->len ? fwrite(sb->buf, 1, sb->len, f) : 0;
565 #define STRBUF_MAXLINK (2*PATH_MAX)
567 int strbuf_readlink(struct strbuf *sb, const char *path, size_t hint)
569 size_t oldalloc = sb->alloc;
571 if (hint < 32)
572 hint = 32;
574 while (hint < STRBUF_MAXLINK) {
575 ssize_t len;
577 strbuf_grow(sb, hint);
578 len = readlink(path, sb->buf, hint);
579 if (len < 0) {
580 if (errno != ERANGE)
581 break;
582 } else if (len < hint) {
583 strbuf_setlen(sb, len);
584 return 0;
587 /* .. the buffer was too small - try again */
588 hint *= 2;
590 if (oldalloc == 0)
591 strbuf_release(sb);
592 return -1;
595 int strbuf_getcwd(struct strbuf *sb)
597 size_t oldalloc = sb->alloc;
598 size_t guessed_len = 128;
600 for (;; guessed_len *= 2) {
601 strbuf_grow(sb, guessed_len);
602 if (getcwd(sb->buf, sb->alloc)) {
603 strbuf_setlen(sb, strlen(sb->buf));
604 return 0;
608 * If getcwd(3) is implemented as a syscall that falls
609 * back to a regular lookup using readdir(3) etc. then
610 * we may be able to avoid EACCES by providing enough
611 * space to the syscall as it's not necessarily bound
612 * to the same restrictions as the fallback.
614 if (errno == EACCES && guessed_len < PATH_MAX)
615 continue;
617 if (errno != ERANGE)
618 break;
620 if (oldalloc == 0)
621 strbuf_release(sb);
622 else
623 strbuf_reset(sb);
624 return -1;
627 #ifdef HAVE_GETDELIM
628 int strbuf_getwholeline(struct strbuf *sb, FILE *fp, int term)
630 ssize_t r;
632 if (feof(fp))
633 return EOF;
635 strbuf_reset(sb);
637 /* Translate slopbuf to NULL, as we cannot call realloc on it */
638 if (!sb->alloc)
639 sb->buf = NULL;
640 errno = 0;
641 r = getdelim(&sb->buf, &sb->alloc, term, fp);
643 if (r > 0) {
644 sb->len = r;
645 return 0;
647 assert(r == -1);
650 * Normally we would have called xrealloc, which will try to free
651 * memory and recover. But we have no way to tell getdelim() to do so.
652 * Worse, we cannot try to recover ENOMEM ourselves, because we have
653 * no idea how many bytes were read by getdelim.
655 * Dying here is reasonable. It mirrors what xrealloc would do on
656 * catastrophic memory failure. We skip the opportunity to free pack
657 * memory and retry, but that's unlikely to help for a malloc small
658 * enough to hold a single line of input, anyway.
660 if (errno == ENOMEM)
661 die("Out of memory, getdelim failed");
664 * Restore strbuf invariants; if getdelim left us with a NULL pointer,
665 * we can just re-init, but otherwise we should make sure that our
666 * length is empty, and that the result is NUL-terminated.
668 if (!sb->buf)
669 strbuf_init(sb, 0);
670 else
671 strbuf_reset(sb);
672 return EOF;
674 #else
675 int strbuf_getwholeline(struct strbuf *sb, FILE *fp, int term)
677 int ch;
679 if (feof(fp))
680 return EOF;
682 strbuf_reset(sb);
683 flockfile(fp);
684 while ((ch = getc_unlocked(fp)) != EOF) {
685 if (!strbuf_avail(sb))
686 strbuf_grow(sb, 1);
687 sb->buf[sb->len++] = ch;
688 if (ch == term)
689 break;
691 funlockfile(fp);
692 if (ch == EOF && sb->len == 0)
693 return EOF;
695 sb->buf[sb->len] = '\0';
696 return 0;
698 #endif
700 int strbuf_appendwholeline(struct strbuf *sb, FILE *fp, int term)
702 struct strbuf line = STRBUF_INIT;
703 if (strbuf_getwholeline(&line, fp, term)) {
704 strbuf_release(&line);
705 return EOF;
707 strbuf_addbuf(sb, &line);
708 strbuf_release(&line);
709 return 0;
712 static int strbuf_getdelim(struct strbuf *sb, FILE *fp, int term)
714 if (strbuf_getwholeline(sb, fp, term))
715 return EOF;
716 if (sb->buf[sb->len - 1] == term)
717 strbuf_setlen(sb, sb->len - 1);
718 return 0;
721 int strbuf_getdelim_strip_crlf(struct strbuf *sb, FILE *fp, int term)
723 if (strbuf_getwholeline(sb, fp, term))
724 return EOF;
725 if (term == '\n' && sb->buf[sb->len - 1] == '\n') {
726 strbuf_setlen(sb, sb->len - 1);
727 if (sb->len && sb->buf[sb->len - 1] == '\r')
728 strbuf_setlen(sb, sb->len - 1);
730 return 0;
733 int strbuf_getline(struct strbuf *sb, FILE *fp)
735 return strbuf_getdelim_strip_crlf(sb, fp, '\n');
738 int strbuf_getline_lf(struct strbuf *sb, FILE *fp)
740 return strbuf_getdelim(sb, fp, '\n');
743 int strbuf_getline_nul(struct strbuf *sb, FILE *fp)
745 return strbuf_getdelim(sb, fp, '\0');
748 int strbuf_getwholeline_fd(struct strbuf *sb, int fd, int term)
750 strbuf_reset(sb);
752 while (1) {
753 char ch;
754 ssize_t len = xread(fd, &ch, 1);
755 if (len <= 0)
756 return EOF;
757 strbuf_addch(sb, ch);
758 if (ch == term)
759 break;
761 return 0;
764 ssize_t strbuf_read_file(struct strbuf *sb, const char *path, size_t hint)
766 int fd;
767 ssize_t len;
768 int saved_errno;
770 fd = open(path, O_RDONLY);
771 if (fd < 0)
772 return -1;
773 len = strbuf_read(sb, fd, hint);
774 saved_errno = errno;
775 close(fd);
776 if (len < 0) {
777 errno = saved_errno;
778 return -1;
781 return len;
784 void strbuf_add_lines(struct strbuf *out, const char *prefix,
785 const char *buf, size_t size)
787 add_lines(out, prefix, buf, size, 0);
790 void strbuf_addstr_xml_quoted(struct strbuf *buf, const char *s)
792 while (*s) {
793 size_t len = strcspn(s, "\"<>&");
794 strbuf_add(buf, s, len);
795 s += len;
796 switch (*s) {
797 case '"':
798 strbuf_addstr(buf, "&quot;");
799 break;
800 case '<':
801 strbuf_addstr(buf, "&lt;");
802 break;
803 case '>':
804 strbuf_addstr(buf, "&gt;");
805 break;
806 case '&':
807 strbuf_addstr(buf, "&amp;");
808 break;
809 case 0:
810 return;
812 s++;
816 static void strbuf_add_urlencode(struct strbuf *sb, const char *s, size_t len,
817 char_predicate allow_unencoded_fn)
819 strbuf_grow(sb, len);
820 while (len--) {
821 char ch = *s++;
822 if (allow_unencoded_fn(ch))
823 strbuf_addch(sb, ch);
824 else
825 strbuf_addf(sb, "%%%02x", (unsigned char)ch);
829 void strbuf_addstr_urlencode(struct strbuf *sb, const char *s,
830 char_predicate allow_unencoded_fn)
832 strbuf_add_urlencode(sb, s, strlen(s), allow_unencoded_fn);
835 static void strbuf_humanise(struct strbuf *buf, off_t bytes,
836 int humanise_rate)
838 if (bytes > 1 << 30) {
839 strbuf_addf(buf,
840 humanise_rate == 0 ?
841 /* TRANSLATORS: IEC 80000-13:2008 gibibyte */
842 _("%u.%2.2u GiB") :
843 /* TRANSLATORS: IEC 80000-13:2008 gibibyte/second */
844 _("%u.%2.2u GiB/s"),
845 (unsigned)(bytes >> 30),
846 (unsigned)(bytes & ((1 << 30) - 1)) / 10737419);
847 } else if (bytes > 1 << 20) {
848 unsigned x = bytes + 5243; /* for rounding */
849 strbuf_addf(buf,
850 humanise_rate == 0 ?
851 /* TRANSLATORS: IEC 80000-13:2008 mebibyte */
852 _("%u.%2.2u MiB") :
853 /* TRANSLATORS: IEC 80000-13:2008 mebibyte/second */
854 _("%u.%2.2u MiB/s"),
855 x >> 20, ((x & ((1 << 20) - 1)) * 100) >> 20);
856 } else if (bytes > 1 << 10) {
857 unsigned x = bytes + 5; /* for rounding */
858 strbuf_addf(buf,
859 humanise_rate == 0 ?
860 /* TRANSLATORS: IEC 80000-13:2008 kibibyte */
861 _("%u.%2.2u KiB") :
862 /* TRANSLATORS: IEC 80000-13:2008 kibibyte/second */
863 _("%u.%2.2u KiB/s"),
864 x >> 10, ((x & ((1 << 10) - 1)) * 100) >> 10);
865 } else {
866 strbuf_addf(buf,
867 humanise_rate == 0 ?
868 /* TRANSLATORS: IEC 80000-13:2008 byte */
869 Q_("%u byte", "%u bytes", bytes) :
870 /* TRANSLATORS: IEC 80000-13:2008 byte/second */
871 Q_("%u byte/s", "%u bytes/s", bytes),
872 (unsigned)bytes);
876 void strbuf_humanise_bytes(struct strbuf *buf, off_t bytes)
878 strbuf_humanise(buf, bytes, 0);
881 void strbuf_humanise_rate(struct strbuf *buf, off_t bytes)
883 strbuf_humanise(buf, bytes, 1);
886 int printf_ln(const char *fmt, ...)
888 int ret;
889 va_list ap;
890 va_start(ap, fmt);
891 ret = vprintf(fmt, ap);
892 va_end(ap);
893 if (ret < 0 || putchar('\n') == EOF)
894 return -1;
895 return ret + 1;
898 int fprintf_ln(FILE *fp, const char *fmt, ...)
900 int ret;
901 va_list ap;
902 va_start(ap, fmt);
903 ret = vfprintf(fp, fmt, ap);
904 va_end(ap);
905 if (ret < 0 || putc('\n', fp) == EOF)
906 return -1;
907 return ret + 1;
910 char *xstrdup_tolower(const char *string)
912 char *result;
913 size_t len, i;
915 len = strlen(string);
916 result = xmallocz(len);
917 for (i = 0; i < len; i++)
918 result[i] = tolower(string[i]);
919 return result;
922 char *xstrdup_toupper(const char *string)
924 char *result;
925 size_t len, i;
927 len = strlen(string);
928 result = xmallocz(len);
929 for (i = 0; i < len; i++)
930 result[i] = toupper(string[i]);
931 return result;
934 char *xstrvfmt(const char *fmt, va_list ap)
936 struct strbuf buf = STRBUF_INIT;
937 strbuf_vaddf(&buf, fmt, ap);
938 return strbuf_detach(&buf, NULL);
941 char *xstrfmt(const char *fmt, ...)
943 va_list ap;
944 char *ret;
946 va_start(ap, fmt);
947 ret = xstrvfmt(fmt, ap);
948 va_end(ap);
950 return ret;
953 void strbuf_addftime(struct strbuf *sb, const char *fmt, const struct tm *tm,
954 int tz_offset, int suppress_tz_name)
956 struct strbuf munged_fmt = STRBUF_INIT;
957 size_t hint = 128;
958 size_t len;
960 if (!*fmt)
961 return;
964 * There is no portable way to pass timezone information to
965 * strftime, so we handle %z and %Z here. Likewise '%s', because
966 * going back to an epoch time requires knowing the zone.
968 * Note that tz_offset is in the "[-+]HHMM" decimal form; this is what
969 * we want for %z, but the computation for %s has to convert to number
970 * of seconds.
972 while (strbuf_expand_step(&munged_fmt, &fmt)) {
973 if (skip_prefix(fmt, "%", &fmt))
974 strbuf_addstr(&munged_fmt, "%%");
975 else if (skip_prefix(fmt, "s", &fmt))
976 strbuf_addf(&munged_fmt, "%"PRItime,
977 (timestamp_t)tm_to_time_t(tm) -
978 3600 * (tz_offset / 100) -
979 60 * (tz_offset % 100));
980 else if (skip_prefix(fmt, "z", &fmt))
981 strbuf_addf(&munged_fmt, "%+05d", tz_offset);
982 else if (suppress_tz_name && skip_prefix(fmt, "Z", &fmt))
983 ; /* nothing */
984 else
985 strbuf_addch(&munged_fmt, '%');
987 fmt = munged_fmt.buf;
989 strbuf_grow(sb, hint);
990 len = strftime(sb->buf + sb->len, sb->alloc - sb->len, fmt, tm);
992 if (!len) {
994 * strftime reports "0" if it could not fit the result in the buffer.
995 * Unfortunately, it also reports "0" if the requested time string
996 * takes 0 bytes. So our strategy is to munge the format so that the
997 * output contains at least one character, and then drop the extra
998 * character before returning.
1000 strbuf_addch(&munged_fmt, ' ');
1001 while (!len) {
1002 hint *= 2;
1003 strbuf_grow(sb, hint);
1004 len = strftime(sb->buf + sb->len, sb->alloc - sb->len,
1005 munged_fmt.buf, tm);
1007 len--; /* drop munged space */
1009 strbuf_release(&munged_fmt);
1010 strbuf_setlen(sb, sb->len + len);
1014 * Returns the length of a line, without trailing spaces.
1016 * If the line ends with newline, it will be removed too.
1018 static size_t cleanup(char *line, size_t len)
1020 while (len) {
1021 unsigned char c = line[len - 1];
1022 if (!isspace(c))
1023 break;
1024 len--;
1027 return len;
1031 * Remove empty lines from the beginning and end
1032 * and also trailing spaces from every line.
1034 * Turn multiple consecutive empty lines between paragraphs
1035 * into just one empty line.
1037 * If the input has only empty lines and spaces,
1038 * no output will be produced.
1040 * If last line does not have a newline at the end, one is added.
1042 * Pass a non-NULL comment_prefix to skip every line starting
1043 * with it.
1045 void strbuf_stripspace(struct strbuf *sb, const char *comment_prefix)
1047 size_t empties = 0;
1048 size_t i, j, len, newlen;
1049 char *eol;
1051 /* We may have to add a newline. */
1052 strbuf_grow(sb, 1);
1054 for (i = j = 0; i < sb->len; i += len, j += newlen) {
1055 eol = memchr(sb->buf + i, '\n', sb->len - i);
1056 len = eol ? eol - (sb->buf + i) + 1 : sb->len - i;
1058 if (comment_prefix && len &&
1059 starts_with(sb->buf + i, comment_prefix)) {
1060 newlen = 0;
1061 continue;
1063 newlen = cleanup(sb->buf + i, len);
1065 /* Not just an empty line? */
1066 if (newlen) {
1067 if (empties > 0 && j > 0)
1068 sb->buf[j++] = '\n';
1069 empties = 0;
1070 memmove(sb->buf + j, sb->buf + i, newlen);
1071 sb->buf[newlen + j++] = '\n';
1072 } else {
1073 empties++;
1077 strbuf_setlen(sb, j);
1080 void strbuf_strip_file_from_path(struct strbuf *sb)
1082 char *path_sep = find_last_dir_sep(sb->buf);
1083 strbuf_setlen(sb, path_sep ? path_sep - sb->buf + 1 : 0);