1 // SPDX-License-Identifier: GPL-2.0
4 #include <linux/kernel.h>
9 * Used as the default ->buf value, so that people can always assume
10 * buf is non NULL and ->buf is NUL terminated even for a freshly
13 char strbuf_slopbuf[1];
15 int strbuf_init(struct strbuf *sb, ssize_t hint)
17 sb->alloc = sb->len = 0;
18 sb->buf = strbuf_slopbuf;
20 return strbuf_grow(sb, hint);
24 void strbuf_release(struct strbuf *sb)
32 char *strbuf_detach(struct strbuf *sb, size_t *sz)
34 char *res = sb->alloc ? sb->buf : NULL;
41 int strbuf_grow(struct strbuf *sb, size_t extra)
44 size_t nr = sb->len + extra + 1;
52 if (alloc_nr(sb->alloc) > nr)
53 nr = alloc_nr(sb->alloc);
56 * Note that sb->buf == strbuf_slopbuf if sb->alloc == 0, and it is
57 * a static variable. Thus we have to avoid passing it to realloc.
59 buf = realloc(sb->alloc ? sb->buf : NULL, nr * sizeof(*buf));
68 int strbuf_addch(struct strbuf *sb, int c)
70 int ret = strbuf_grow(sb, 1);
74 sb->buf[sb->len++] = c;
75 sb->buf[sb->len] = '\0';
79 int strbuf_add(struct strbuf *sb, const void *data, size_t len)
81 int ret = strbuf_grow(sb, len);
85 memcpy(sb->buf + sb->len, data, len);
86 return strbuf_setlen(sb, sb->len + len);
89 static int strbuf_addv(struct strbuf *sb, const char *fmt, va_list ap)
94 if (!strbuf_avail(sb)) {
95 ret = strbuf_grow(sb, 64);
100 va_copy(ap_saved, ap);
101 len = vsnprintf(sb->buf + sb->len, sb->alloc - sb->len, fmt, ap);
106 if (len > strbuf_avail(sb)) {
107 ret = strbuf_grow(sb, len);
112 len = vsnprintf(sb->buf + sb->len, sb->alloc - sb->len, fmt, ap_saved);
113 if (len > strbuf_avail(sb)) {
114 pr_debug("this should not happen, your vsnprintf is broken");
120 return strbuf_setlen(sb, sb->len + len);
123 int strbuf_addf(struct strbuf *sb, const char *fmt, ...)
129 ret = strbuf_addv(sb, fmt, ap);
134 ssize_t strbuf_read(struct strbuf *sb, int fd, ssize_t hint)
136 size_t oldlen = sb->len;
137 size_t oldalloc = sb->alloc;
140 ret = strbuf_grow(sb, hint ? hint : 8192);
147 cnt = read(fd, sb->buf + sb->len, sb->alloc - sb->len - 1);
152 strbuf_setlen(sb, oldlen);
158 ret = strbuf_grow(sb, 8192);
163 sb->buf[sb->len] = '\0';
164 return sb->len - oldlen;