line-range: plug leaking find functions
[git/gitster.git] / strbuf.c
blobe1076c989172480ed26b849f47b9736160b245de
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_addbuf(struct strbuf *sb, const struct strbuf *sb2)
318 strbuf_grow(sb, sb2->len);
319 memcpy(sb->buf + sb->len, sb2->buf, sb2->len);
320 strbuf_setlen(sb, sb->len + sb2->len);
323 const char *strbuf_join_argv(struct strbuf *buf,
324 int argc, const char **argv, char delim)
326 if (!argc)
327 return buf->buf;
329 strbuf_addstr(buf, *argv);
330 while (--argc) {
331 strbuf_addch(buf, delim);
332 strbuf_addstr(buf, *(++argv));
335 return buf->buf;
338 void strbuf_addchars(struct strbuf *sb, int c, size_t n)
340 strbuf_grow(sb, n);
341 memset(sb->buf + sb->len, c, n);
342 strbuf_setlen(sb, sb->len + n);
345 void strbuf_addf(struct strbuf *sb, const char *fmt, ...)
347 va_list ap;
348 va_start(ap, fmt);
349 strbuf_vaddf(sb, fmt, ap);
350 va_end(ap);
353 static void add_lines(struct strbuf *out,
354 const char *prefix,
355 const char *buf, size_t size,
356 int space_after_prefix)
358 while (size) {
359 const char *next = memchr(buf, '\n', size);
360 next = next ? (next + 1) : (buf + size);
362 strbuf_addstr(out, prefix);
363 if (space_after_prefix && buf[0] != '\n' && buf[0] != '\t')
364 strbuf_addch(out, ' ');
365 strbuf_add(out, buf, next - buf);
366 size -= next - buf;
367 buf = next;
369 strbuf_complete_line(out);
372 void strbuf_add_commented_lines(struct strbuf *out, const char *buf,
373 size_t size, const char *comment_prefix)
375 add_lines(out, comment_prefix, buf, size, 1);
378 void strbuf_commented_addf(struct strbuf *sb, const char *comment_prefix,
379 const char *fmt, ...)
381 va_list params;
382 struct strbuf buf = STRBUF_INIT;
383 int incomplete_line = sb->len && sb->buf[sb->len - 1] != '\n';
385 va_start(params, fmt);
386 strbuf_vaddf(&buf, fmt, params);
387 va_end(params);
389 strbuf_add_commented_lines(sb, buf.buf, buf.len, comment_prefix);
390 if (incomplete_line)
391 sb->buf[--sb->len] = '\0';
393 strbuf_release(&buf);
396 void strbuf_vaddf(struct strbuf *sb, const char *fmt, va_list ap)
398 int len;
399 va_list cp;
401 if (!strbuf_avail(sb))
402 strbuf_grow(sb, 64);
403 va_copy(cp, ap);
404 len = vsnprintf(sb->buf + sb->len, sb->alloc - sb->len, fmt, cp);
405 va_end(cp);
406 if (len < 0)
407 die(_("unable to format message: %s"), fmt);
408 if (len > strbuf_avail(sb)) {
409 strbuf_grow(sb, len);
410 len = vsnprintf(sb->buf + sb->len, sb->alloc - sb->len, fmt, ap);
411 if (len > strbuf_avail(sb))
412 BUG("your vsnprintf is broken (insatiable)");
414 strbuf_setlen(sb, sb->len + len);
417 int strbuf_expand_step(struct strbuf *sb, const char **formatp)
419 const char *format = *formatp;
420 const char *percent = strchrnul(format, '%');
422 strbuf_add(sb, format, percent - format);
423 if (!*percent)
424 return 0;
425 *formatp = percent + 1;
426 return 1;
429 size_t strbuf_expand_literal(struct strbuf *sb, const char *placeholder)
431 int ch;
433 switch (placeholder[0]) {
434 case 'n': /* newline */
435 strbuf_addch(sb, '\n');
436 return 1;
437 case 'x':
438 /* %x00 == NUL, %x0a == LF, etc. */
439 ch = hex2chr(placeholder + 1);
440 if (ch < 0)
441 return 0;
442 strbuf_addch(sb, ch);
443 return 3;
445 return 0;
448 void strbuf_expand_bad_format(const char *format, const char *command)
450 const char *end;
452 if (*format != '(')
453 /* TRANSLATORS: The first %s is a command like "ls-tree". */
454 die(_("bad %s format: element '%s' does not start with '('"),
455 command, format);
457 end = strchr(format + 1, ')');
458 if (!end)
459 /* TRANSLATORS: The first %s is a command like "ls-tree". */
460 die(_("bad %s format: element '%s' does not end in ')'"),
461 command, format);
463 /* TRANSLATORS: %s is a command like "ls-tree". */
464 die(_("bad %s format: %%%.*s"),
465 command, (int)(end - format + 1), format);
468 void strbuf_addbuf_percentquote(struct strbuf *dst, const struct strbuf *src)
470 size_t i, len = src->len;
472 for (i = 0; i < len; i++) {
473 if (src->buf[i] == '%')
474 strbuf_addch(dst, '%');
475 strbuf_addch(dst, src->buf[i]);
479 #define URL_UNSAFE_CHARS " <>\"%{}|\\^`:?#[]@!$&'()*+,;="
481 void strbuf_add_percentencode(struct strbuf *dst, const char *src, int flags)
483 size_t i, len = strlen(src);
485 for (i = 0; i < len; i++) {
486 unsigned char ch = src[i];
487 if (ch <= 0x1F || ch >= 0x7F ||
488 (ch == '/' && (flags & STRBUF_ENCODE_SLASH)) ||
489 strchr(URL_UNSAFE_CHARS, ch))
490 strbuf_addf(dst, "%%%02X", (unsigned char)ch);
491 else
492 strbuf_addch(dst, ch);
496 size_t strbuf_fread(struct strbuf *sb, size_t size, FILE *f)
498 size_t res;
499 size_t oldalloc = sb->alloc;
501 strbuf_grow(sb, size);
502 res = fread(sb->buf + sb->len, 1, size, f);
503 if (res > 0)
504 strbuf_setlen(sb, sb->len + res);
505 else if (oldalloc == 0)
506 strbuf_release(sb);
507 return res;
510 ssize_t strbuf_read(struct strbuf *sb, int fd, size_t hint)
512 size_t oldlen = sb->len;
513 size_t oldalloc = sb->alloc;
515 strbuf_grow(sb, hint ? hint : 8192);
516 for (;;) {
517 ssize_t want = sb->alloc - sb->len - 1;
518 ssize_t got = read_in_full(fd, sb->buf + sb->len, want);
520 if (got < 0) {
521 if (oldalloc == 0)
522 strbuf_release(sb);
523 else
524 strbuf_setlen(sb, oldlen);
525 return -1;
527 sb->len += got;
528 if (got < want)
529 break;
530 strbuf_grow(sb, 8192);
533 sb->buf[sb->len] = '\0';
534 return sb->len - oldlen;
537 ssize_t strbuf_read_once(struct strbuf *sb, int fd, size_t hint)
539 size_t oldalloc = sb->alloc;
540 ssize_t cnt;
542 strbuf_grow(sb, hint ? hint : 8192);
543 cnt = xread(fd, sb->buf + sb->len, sb->alloc - sb->len - 1);
544 if (cnt > 0)
545 strbuf_setlen(sb, sb->len + cnt);
546 else if (oldalloc == 0)
547 strbuf_release(sb);
548 return cnt;
551 ssize_t strbuf_write(struct strbuf *sb, FILE *f)
553 return sb->len ? fwrite(sb->buf, 1, sb->len, f) : 0;
556 #define STRBUF_MAXLINK (2*PATH_MAX)
558 int strbuf_readlink(struct strbuf *sb, const char *path, size_t hint)
560 size_t oldalloc = sb->alloc;
562 if (hint < 32)
563 hint = 32;
565 while (hint < STRBUF_MAXLINK) {
566 ssize_t len;
568 strbuf_grow(sb, hint);
569 len = readlink(path, sb->buf, hint);
570 if (len < 0) {
571 if (errno != ERANGE)
572 break;
573 } else if (len < hint) {
574 strbuf_setlen(sb, len);
575 return 0;
578 /* .. the buffer was too small - try again */
579 hint *= 2;
581 if (oldalloc == 0)
582 strbuf_release(sb);
583 return -1;
586 int strbuf_getcwd(struct strbuf *sb)
588 size_t oldalloc = sb->alloc;
589 size_t guessed_len = 128;
591 for (;; guessed_len *= 2) {
592 strbuf_grow(sb, guessed_len);
593 if (getcwd(sb->buf, sb->alloc)) {
594 strbuf_setlen(sb, strlen(sb->buf));
595 return 0;
599 * If getcwd(3) is implemented as a syscall that falls
600 * back to a regular lookup using readdir(3) etc. then
601 * we may be able to avoid EACCES by providing enough
602 * space to the syscall as it's not necessarily bound
603 * to the same restrictions as the fallback.
605 if (errno == EACCES && guessed_len < PATH_MAX)
606 continue;
608 if (errno != ERANGE)
609 break;
611 if (oldalloc == 0)
612 strbuf_release(sb);
613 else
614 strbuf_reset(sb);
615 return -1;
618 #ifdef HAVE_GETDELIM
619 int strbuf_getwholeline(struct strbuf *sb, FILE *fp, int term)
621 ssize_t r;
623 if (feof(fp))
624 return EOF;
626 strbuf_reset(sb);
628 /* Translate slopbuf to NULL, as we cannot call realloc on it */
629 if (!sb->alloc)
630 sb->buf = NULL;
631 errno = 0;
632 r = getdelim(&sb->buf, &sb->alloc, term, fp);
634 if (r > 0) {
635 sb->len = r;
636 return 0;
638 assert(r == -1);
641 * Normally we would have called xrealloc, which will try to free
642 * memory and recover. But we have no way to tell getdelim() to do so.
643 * Worse, we cannot try to recover ENOMEM ourselves, because we have
644 * no idea how many bytes were read by getdelim.
646 * Dying here is reasonable. It mirrors what xrealloc would do on
647 * catastrophic memory failure. We skip the opportunity to free pack
648 * memory and retry, but that's unlikely to help for a malloc small
649 * enough to hold a single line of input, anyway.
651 if (errno == ENOMEM)
652 die("Out of memory, getdelim failed");
655 * Restore strbuf invariants; if getdelim left us with a NULL pointer,
656 * we can just re-init, but otherwise we should make sure that our
657 * length is empty, and that the result is NUL-terminated.
659 if (!sb->buf)
660 strbuf_init(sb, 0);
661 else
662 strbuf_reset(sb);
663 return EOF;
665 #else
666 int strbuf_getwholeline(struct strbuf *sb, FILE *fp, int term)
668 int ch;
670 if (feof(fp))
671 return EOF;
673 strbuf_reset(sb);
674 flockfile(fp);
675 while ((ch = getc_unlocked(fp)) != EOF) {
676 if (!strbuf_avail(sb))
677 strbuf_grow(sb, 1);
678 sb->buf[sb->len++] = ch;
679 if (ch == term)
680 break;
682 funlockfile(fp);
683 if (ch == EOF && sb->len == 0)
684 return EOF;
686 sb->buf[sb->len] = '\0';
687 return 0;
689 #endif
691 int strbuf_appendwholeline(struct strbuf *sb, FILE *fp, int term)
693 struct strbuf line = STRBUF_INIT;
694 if (strbuf_getwholeline(&line, fp, term)) {
695 strbuf_release(&line);
696 return EOF;
698 strbuf_addbuf(sb, &line);
699 strbuf_release(&line);
700 return 0;
703 static int strbuf_getdelim(struct strbuf *sb, FILE *fp, int term)
705 if (strbuf_getwholeline(sb, fp, term))
706 return EOF;
707 if (sb->buf[sb->len - 1] == term)
708 strbuf_setlen(sb, sb->len - 1);
709 return 0;
712 int strbuf_getdelim_strip_crlf(struct strbuf *sb, FILE *fp, int term)
714 if (strbuf_getwholeline(sb, fp, term))
715 return EOF;
716 if (term == '\n' && sb->buf[sb->len - 1] == '\n') {
717 strbuf_setlen(sb, sb->len - 1);
718 if (sb->len && sb->buf[sb->len - 1] == '\r')
719 strbuf_setlen(sb, sb->len - 1);
721 return 0;
724 int strbuf_getline(struct strbuf *sb, FILE *fp)
726 return strbuf_getdelim_strip_crlf(sb, fp, '\n');
729 int strbuf_getline_lf(struct strbuf *sb, FILE *fp)
731 return strbuf_getdelim(sb, fp, '\n');
734 int strbuf_getline_nul(struct strbuf *sb, FILE *fp)
736 return strbuf_getdelim(sb, fp, '\0');
739 int strbuf_getwholeline_fd(struct strbuf *sb, int fd, int term)
741 strbuf_reset(sb);
743 while (1) {
744 char ch;
745 ssize_t len = xread(fd, &ch, 1);
746 if (len <= 0)
747 return EOF;
748 strbuf_addch(sb, ch);
749 if (ch == term)
750 break;
752 return 0;
755 ssize_t strbuf_read_file(struct strbuf *sb, const char *path, size_t hint)
757 int fd;
758 ssize_t len;
759 int saved_errno;
761 fd = open(path, O_RDONLY);
762 if (fd < 0)
763 return -1;
764 len = strbuf_read(sb, fd, hint);
765 saved_errno = errno;
766 close(fd);
767 if (len < 0) {
768 errno = saved_errno;
769 return -1;
772 return len;
775 void strbuf_add_lines(struct strbuf *out, const char *prefix,
776 const char *buf, size_t size)
778 add_lines(out, prefix, buf, size, 0);
781 void strbuf_addstr_xml_quoted(struct strbuf *buf, const char *s)
783 while (*s) {
784 size_t len = strcspn(s, "\"<>&");
785 strbuf_add(buf, s, len);
786 s += len;
787 switch (*s) {
788 case '"':
789 strbuf_addstr(buf, "&quot;");
790 break;
791 case '<':
792 strbuf_addstr(buf, "&lt;");
793 break;
794 case '>':
795 strbuf_addstr(buf, "&gt;");
796 break;
797 case '&':
798 strbuf_addstr(buf, "&amp;");
799 break;
800 case 0:
801 return;
803 s++;
807 static void strbuf_add_urlencode(struct strbuf *sb, const char *s, size_t len,
808 char_predicate allow_unencoded_fn)
810 strbuf_grow(sb, len);
811 while (len--) {
812 char ch = *s++;
813 if (allow_unencoded_fn(ch))
814 strbuf_addch(sb, ch);
815 else
816 strbuf_addf(sb, "%%%02x", (unsigned char)ch);
820 void strbuf_addstr_urlencode(struct strbuf *sb, const char *s,
821 char_predicate allow_unencoded_fn)
823 strbuf_add_urlencode(sb, s, strlen(s), allow_unencoded_fn);
826 static void strbuf_humanise(struct strbuf *buf, off_t bytes,
827 int humanise_rate)
829 if (bytes > 1 << 30) {
830 strbuf_addf(buf,
831 humanise_rate == 0 ?
832 /* TRANSLATORS: IEC 80000-13:2008 gibibyte */
833 _("%u.%2.2u GiB") :
834 /* TRANSLATORS: IEC 80000-13:2008 gibibyte/second */
835 _("%u.%2.2u GiB/s"),
836 (unsigned)(bytes >> 30),
837 (unsigned)(bytes & ((1 << 30) - 1)) / 10737419);
838 } else if (bytes > 1 << 20) {
839 unsigned x = bytes + 5243; /* for rounding */
840 strbuf_addf(buf,
841 humanise_rate == 0 ?
842 /* TRANSLATORS: IEC 80000-13:2008 mebibyte */
843 _("%u.%2.2u MiB") :
844 /* TRANSLATORS: IEC 80000-13:2008 mebibyte/second */
845 _("%u.%2.2u MiB/s"),
846 x >> 20, ((x & ((1 << 20) - 1)) * 100) >> 20);
847 } else if (bytes > 1 << 10) {
848 unsigned x = bytes + 5; /* for rounding */
849 strbuf_addf(buf,
850 humanise_rate == 0 ?
851 /* TRANSLATORS: IEC 80000-13:2008 kibibyte */
852 _("%u.%2.2u KiB") :
853 /* TRANSLATORS: IEC 80000-13:2008 kibibyte/second */
854 _("%u.%2.2u KiB/s"),
855 x >> 10, ((x & ((1 << 10) - 1)) * 100) >> 10);
856 } else {
857 strbuf_addf(buf,
858 humanise_rate == 0 ?
859 /* TRANSLATORS: IEC 80000-13:2008 byte */
860 Q_("%u byte", "%u bytes", bytes) :
861 /* TRANSLATORS: IEC 80000-13:2008 byte/second */
862 Q_("%u byte/s", "%u bytes/s", bytes),
863 (unsigned)bytes);
867 void strbuf_humanise_bytes(struct strbuf *buf, off_t bytes)
869 strbuf_humanise(buf, bytes, 0);
872 void strbuf_humanise_rate(struct strbuf *buf, off_t bytes)
874 strbuf_humanise(buf, bytes, 1);
877 int printf_ln(const char *fmt, ...)
879 int ret;
880 va_list ap;
881 va_start(ap, fmt);
882 ret = vprintf(fmt, ap);
883 va_end(ap);
884 if (ret < 0 || putchar('\n') == EOF)
885 return -1;
886 return ret + 1;
889 int fprintf_ln(FILE *fp, const char *fmt, ...)
891 int ret;
892 va_list ap;
893 va_start(ap, fmt);
894 ret = vfprintf(fp, fmt, ap);
895 va_end(ap);
896 if (ret < 0 || putc('\n', fp) == EOF)
897 return -1;
898 return ret + 1;
901 char *xstrdup_tolower(const char *string)
903 char *result;
904 size_t len, i;
906 len = strlen(string);
907 result = xmallocz(len);
908 for (i = 0; i < len; i++)
909 result[i] = tolower(string[i]);
910 return result;
913 char *xstrdup_toupper(const char *string)
915 char *result;
916 size_t len, i;
918 len = strlen(string);
919 result = xmallocz(len);
920 for (i = 0; i < len; i++)
921 result[i] = toupper(string[i]);
922 return result;
925 char *xstrvfmt(const char *fmt, va_list ap)
927 struct strbuf buf = STRBUF_INIT;
928 strbuf_vaddf(&buf, fmt, ap);
929 return strbuf_detach(&buf, NULL);
932 char *xstrfmt(const char *fmt, ...)
934 va_list ap;
935 char *ret;
937 va_start(ap, fmt);
938 ret = xstrvfmt(fmt, ap);
939 va_end(ap);
941 return ret;
944 void strbuf_addftime(struct strbuf *sb, const char *fmt, const struct tm *tm,
945 int tz_offset, int suppress_tz_name)
947 struct strbuf munged_fmt = STRBUF_INIT;
948 size_t hint = 128;
949 size_t len;
951 if (!*fmt)
952 return;
955 * There is no portable way to pass timezone information to
956 * strftime, so we handle %z and %Z here. Likewise '%s', because
957 * going back to an epoch time requires knowing the zone.
959 * Note that tz_offset is in the "[-+]HHMM" decimal form; this is what
960 * we want for %z, but the computation for %s has to convert to number
961 * of seconds.
963 while (strbuf_expand_step(&munged_fmt, &fmt)) {
964 if (skip_prefix(fmt, "%", &fmt))
965 strbuf_addstr(&munged_fmt, "%%");
966 else if (skip_prefix(fmt, "s", &fmt))
967 strbuf_addf(&munged_fmt, "%"PRItime,
968 (timestamp_t)tm_to_time_t(tm) -
969 3600 * (tz_offset / 100) -
970 60 * (tz_offset % 100));
971 else if (skip_prefix(fmt, "z", &fmt))
972 strbuf_addf(&munged_fmt, "%+05d", tz_offset);
973 else if (suppress_tz_name && skip_prefix(fmt, "Z", &fmt))
974 ; /* nothing */
975 else
976 strbuf_addch(&munged_fmt, '%');
978 fmt = munged_fmt.buf;
980 strbuf_grow(sb, hint);
981 len = strftime(sb->buf + sb->len, sb->alloc - sb->len, fmt, tm);
983 if (!len) {
985 * strftime reports "0" if it could not fit the result in the buffer.
986 * Unfortunately, it also reports "0" if the requested time string
987 * takes 0 bytes. So our strategy is to munge the format so that the
988 * output contains at least one character, and then drop the extra
989 * character before returning.
991 strbuf_addch(&munged_fmt, ' ');
992 while (!len) {
993 hint *= 2;
994 strbuf_grow(sb, hint);
995 len = strftime(sb->buf + sb->len, sb->alloc - sb->len,
996 munged_fmt.buf, tm);
998 len--; /* drop munged space */
1000 strbuf_release(&munged_fmt);
1001 strbuf_setlen(sb, sb->len + len);
1005 * Returns the length of a line, without trailing spaces.
1007 * If the line ends with newline, it will be removed too.
1009 static size_t cleanup(char *line, size_t len)
1011 while (len) {
1012 unsigned char c = line[len - 1];
1013 if (!isspace(c))
1014 break;
1015 len--;
1018 return len;
1022 * Remove empty lines from the beginning and end
1023 * and also trailing spaces from every line.
1025 * Turn multiple consecutive empty lines between paragraphs
1026 * into just one empty line.
1028 * If the input has only empty lines and spaces,
1029 * no output will be produced.
1031 * If last line does not have a newline at the end, one is added.
1033 * Pass a non-NULL comment_prefix to skip every line starting
1034 * with it.
1036 void strbuf_stripspace(struct strbuf *sb, const char *comment_prefix)
1038 size_t empties = 0;
1039 size_t i, j, len, newlen;
1040 char *eol;
1042 /* We may have to add a newline. */
1043 strbuf_grow(sb, 1);
1045 for (i = j = 0; i < sb->len; i += len, j += newlen) {
1046 eol = memchr(sb->buf + i, '\n', sb->len - i);
1047 len = eol ? eol - (sb->buf + i) + 1 : sb->len - i;
1049 if (comment_prefix && len &&
1050 starts_with(sb->buf + i, comment_prefix)) {
1051 newlen = 0;
1052 continue;
1054 newlen = cleanup(sb->buf + i, len);
1056 /* Not just an empty line? */
1057 if (newlen) {
1058 if (empties > 0 && j > 0)
1059 sb->buf[j++] = '\n';
1060 empties = 0;
1061 memmove(sb->buf + j, sb->buf + i, newlen);
1062 sb->buf[newlen + j++] = '\n';
1063 } else {
1064 empties++;
1068 strbuf_setlen(sb, j);
1071 void strbuf_strip_file_from_path(struct strbuf *sb)
1073 char *path_sep = find_last_dir_sep(sb->buf);
1074 strbuf_setlen(sb, path_sep ? path_sep - sb->buf + 1 : 0);