Skip to content

Commit

Permalink
data/buffer.[ch]: Fix buffer_remove().
Browse files Browse the repository at this point in the history
  • Loading branch information
mity committed Dec 11, 2023
1 parent 018ad60 commit 1826062
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 11 deletions.
11 changes: 7 additions & 4 deletions data/buffer.c
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ void
buffer_remove(BUFFER* buf, size_t off, size_t n)
{
if(off + n < buf->size) {
memmove((uint8_t*)buf->data + off, (uint8_t*)buf->data + off + n, n);
memmove((uint8_t*)buf->data + off, (uint8_t*)buf->data + off + n, buf->size - off - n);
buf->size -= n;
} else {
buf->size = off;
Expand All @@ -148,9 +148,12 @@ buffer_remove(BUFFER* buf, size_t off, size_t n)
buf->data = NULL;
buf->alloc = 0;
} else if(buf->size < buf->alloc / 4) {
/* No error checking here: If the realloc fails, we still have valid
* albeit bloated buffer. */
buffer_realloc(buf, buffer_good_alloc_size(buf->size * 2));
size_t new_alloc = buffer_good_alloc_size(buf->size * 2);
if(new_alloc < buf->alloc / 2) {
/* No error checking here: If the realloc fails, we still have valid
* albeit bloated buffer. */
buffer_realloc(buf, new_alloc);
}
}
}

45 changes: 38 additions & 7 deletions tests/test-buffer.c
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* C Reusables
* <http://github.com/mity/c-reusables>
*
* Copyright (c) 2018 Martin Mitas
* Copyright (c) 2018-2023 Martin Mitas
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
Expand Down Expand Up @@ -129,13 +129,44 @@ test_remove(void)
buffer_fini(&buf);
}

static void
test_remove_most(void)
{
BUFFER buf = BUFFER_INITIALIZER;
int i;

for(i = 0; i < 1000; i++)
buffer_append(&buf, "1234567890", 10);
buffer_remove(&buf, 1, 10*1000 - 3);
TEST_CHECK(buffer_size(&buf) == 3);
TEST_CHECK(buf.alloc < 100);

buffer_fini(&buf);
}

static void
test_remove_all(void)
{
BUFFER buf = BUFFER_INITIALIZER;

buffer_append(&buf, "1234567890", 10);
buffer_remove(&buf, 0, 10);
TEST_CHECK(buffer_size(&buf) == 0);
TEST_CHECK(buf.alloc == 0);
TEST_CHECK(buf.data == NULL);

buffer_fini(&buf);
}


TEST_LIST = {
{ "init", test_init },
{ "grow", test_grow },
{ "reserve", test_reserve },
{ "shrink", test_shrink },
{ "insert", test_insert },
{ "remove", test_remove },
{ "init", test_init },
{ "grow", test_grow },
{ "reserve", test_reserve },
{ "shrink", test_shrink },
{ "insert", test_insert },
{ "remove", test_remove },
{ "remove-most", test_remove_most },
{ "remove-all", test_remove_all },
{ 0 }
};

0 comments on commit 1826062

Please sign in to comment.