diff --git a/docs/technical/strbuf.txt b/docs/technical/strbuf.txt index ddbe4c1..efb374b 100644 --- a/docs/technical/strbuf.txt +++ b/docs/technical/strbuf.txt @@ -24,6 +24,12 @@ NOTE: ->alloc_size and ->len should *not* be messed with, only `strbuf_*` functi Functions ~~~~~~~~~ +`strbuf_setlen()`:: + + Sets the length of the buffer. + + This function will not allocate memory, it only sets ->len and + assure that the string is null-terminated at the new position. + `strbuf_append()`:: This function will append the buffer with the contents of 'ptr' diff --git a/src/strbuf.c b/src/strbuf.c index 89c8e1f..61229d4 100644 --- a/src/strbuf.c +++ b/src/strbuf.c @@ -46,6 +46,17 @@ void strbuf_reduce(strbuf_t *s, size_t len) { s->buf[s->len] = '\0'; } +void strbuf_setlen(strbuf_t *s, size_t len) { + + if (!s->alloc_size) + return; + + if (len >= s->alloc_size) + len = s->alloc_size - 1; + s->len = len; + s->buf[s->len] = '\0'; +} + char* strbuf_release(strbuf_t *s) { char *ret; diff --git a/src/strbuf.h b/src/strbuf.h index 3a6b668..bf29f50 100644 --- a/src/strbuf.h +++ b/src/strbuf.h @@ -29,6 +29,8 @@ void strbuf_expand(strbuf_t *s, size_t len); void strbuf_reduce(strbuf_t *s, size_t len); +void strbuf_setlen(strbuf_t *s, size_t len); + char* strbuf_release(strbuf_t *s); void strbuf_free(strbuf_t *s); diff --git a/test/t_strbuf.c b/test/t_strbuf.c index 61ed4c9..514335a 100644 --- a/test/t_strbuf.c +++ b/test/t_strbuf.c @@ -14,6 +14,31 @@ void print_strbuf(strbuf_t *s) { printf("block: %u, len: %u |%s|\n", (uint)s->alloc_size, (uint)s->len, s->buf); } +void test_setlen() { + + strbuf_t b = STRBUF_INIT; + + strbuf_setlen(&b, 25); + assert(b.len == 0); + + strbuf_expand(&b, 25); + strbuf_setlen(&b, b.alloc_size); + assert(b.len == b.alloc_size-1); + + strbuf_setlen(&b, 0); + assert(b.len == 0); + + strbuf_append_str(&b, "testing..."); + print_strbuf(&b); + + strbuf_setlen(&b, 7); + assert(b.len == 7); + + print_strbuf(&b); + + strbuf_free(&b); +} + void test_release() { strbuf_t b = STRBUF_INIT; @@ -193,6 +218,7 @@ int main() { test_release_empty(); test_release(); + test_setlen(); test_reduce(); test_rev(); test_squeeze();