* strbuf_rtrim removes trailing spaces. * strbuf_insert insert data at a given position. off-by-one fix: * strbuf_avail() does not counts the final \0 so the overflow test for snprintf is the strict comparison. This is not critical as the growth mechanism chosen will always allocate _more_ memory than asked, so the second test will not fail. It's some kind of miracle though. Signed-off-by: Pierre Habouzit <madcoder@xxxxxxxxxx> --- strbuf.c | 22 ++++++++++++++++++++-- strbuf.h | 6 ++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/strbuf.c b/strbuf.c index 7136de1..cf48699 100644 --- a/strbuf.c +++ b/strbuf.c @@ -28,6 +28,24 @@ void strbuf_grow(struct strbuf *sb, size_t extra) { ALLOC_GROW(sb->buf, sb->len + extra + 1, sb->alloc); } +void strbuf_rtrim(struct strbuf *sb) +{ + while (sb->len > 0 && isspace((unsigned char)sb->buf[sb->len - 1])) + sb->len--; + sb->buf[sb->len] = '\0'; +} + +void strbuf_insert(struct strbuf *sb, size_t pos, const void *data, size_t len) { + strbuf_grow(sb, len); + if (pos >= sb->len) { + pos = sb->len; + } else { + memmove(sb->buf + pos + len, sb->buf + pos, sb->len - pos); + } + memcpy(sb->buf + pos, data, len); + strbuf_setlen(sb, sb->len + len); +} + void strbuf_add(struct strbuf *sb, const void *data, size_t len) { strbuf_grow(sb, len); memcpy(sb->buf + sb->len, data, len); @@ -44,12 +62,12 @@ void strbuf_addf(struct strbuf *sb, const char *fmt, ...) { if (len < 0) { len = 0; } - if (len >= strbuf_avail(sb)) { + if (len > strbuf_avail(sb)) { strbuf_grow(sb, len); va_start(ap, fmt); len = vsnprintf(sb->buf + sb->len, sb->alloc - sb->len, fmt, ap); va_end(ap); - if (len >= strbuf_avail(sb)) { + if (len > strbuf_avail(sb)) { die("this should not happen, your snprintf is broken"); } } diff --git a/strbuf.h b/strbuf.h index b40dc99..b90cbdf 100644 --- a/strbuf.h +++ b/strbuf.h @@ -68,6 +68,9 @@ static inline void strbuf_setlen(struct strbuf *sb, size_t len) { extern void strbuf_grow(struct strbuf *, size_t); +/*----- content related -----*/ +extern void strbuf_rtrim(struct strbuf *); + /*----- add data in your buffer -----*/ static inline void strbuf_addch(struct strbuf *sb, int c) { strbuf_grow(sb, 1); @@ -75,6 +78,9 @@ static inline void strbuf_addch(struct strbuf *sb, int c) { sb->buf[sb->len] = '\0'; } +/* inserts after pos, or appends if pos >= sb->len */ +extern void strbuf_insert(struct strbuf *, size_t pos, const void *, size_t); + extern void strbuf_add(struct strbuf *, const void *, size_t); static inline void strbuf_addstr(struct strbuf *sb, const char *s) { strbuf_add(sb, s, strlen(s)); -- 1.5.3.1 - To unsubscribe from this list: send the line "unsubscribe git" in the body of a message to majordomo@xxxxxxxxxxxxxxx More majordomo info at http://vger.kernel.org/majordomo-info.html