strbuf: added strbuf_setlen
This commit is contained in:
parent
3ed80a13ae
commit
6538fd9369
4 changed files with 45 additions and 0 deletions
|
|
@ -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'
|
||||
|
|
|
|||
11
src/strbuf.c
11
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;
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
|
|
|
|||
Reference in a new issue