--- a/tests/test_buffer.c Sun Apr 13 12:30:18 2025 +0200 +++ b/tests/test_buffer.c Sun Apr 13 13:02:54 2025 +0200 @@ -187,6 +187,69 @@ cx_testing_allocator_destroy(&talloc); } +CX_TEST(test_buffer_shrink) { + CxTestingAllocator talloc; + cx_testing_allocator_init(&talloc); + CxAllocator *alloc = &talloc.base; + CX_TEST_DO { + CxBuffer buf; + cxBufferInit(&buf, NULL, 16, alloc, CX_BUFFER_FREE_CONTENTS); + cxBufferPutString(&buf, "Testing"); + cxBufferTerminate(&buf); + CX_TEST_ASSERT(buf.capacity == 16); + CX_TEST_ASSERT(buf.size == 7); + cxBufferShrink(&buf, 4); + CX_TEST_ASSERT(buf.capacity == 11); + CX_TEST_ASSERT(buf.size == 7); + CX_TEST_ASSERT(memcmp(buf.space, "Testing", 8) == 0); + cxBufferDestroy(&buf); + CX_TEST_ASSERT(cx_testing_allocator_verify(&talloc)); + } + cx_testing_allocator_destroy(&talloc); +} + +CX_TEST(test_buffer_shrink_copy_on_write) { + CxTestingAllocator talloc; + cx_testing_allocator_init(&talloc); + CxAllocator *alloc = &talloc.base; + CX_TEST_DO { + CxBuffer buf; + const char* space = "Testing"; + cxBufferInit(&buf, (void*)space, 16, alloc, CX_BUFFER_COPY_ON_WRITE); + buf.size = 8; + CX_TEST_ASSERT(buf.capacity == 16); + cxBufferShrink(&buf, 4); + CX_TEST_ASSERT(buf.capacity == 16); + CX_TEST_ASSERT(buf.size == 8); + CX_TEST_ASSERT(memcmp(buf.space, "Testing", 8) == 0); + CX_TEST_ASSERT(talloc.alloc_total == 0); + cxBufferDestroy(&buf); + CX_TEST_ASSERT(cx_testing_allocator_verify(&talloc)); + } + cx_testing_allocator_destroy(&talloc); +} + +CX_TEST(test_buffer_shrink_copy_on_extend) { + CxTestingAllocator talloc; + cx_testing_allocator_init(&talloc); + CxAllocator *alloc = &talloc.base; + CX_TEST_DO { + CxBuffer buf; + char space[16] = "Testing"; + cxBufferInit(&buf, space, 16, alloc, CX_BUFFER_COPY_ON_EXTEND); + buf.size = 8; + CX_TEST_ASSERT(buf.capacity == 16); + cxBufferShrink(&buf, 4); + CX_TEST_ASSERT(buf.capacity == 16); + CX_TEST_ASSERT(buf.size == 8); + CX_TEST_ASSERT(memcmp(buf.space, "Testing", 8) == 0); + CX_TEST_ASSERT(talloc.alloc_total == 0); + cxBufferDestroy(&buf); + CX_TEST_ASSERT(cx_testing_allocator_verify(&talloc)); + } + cx_testing_allocator_destroy(&talloc); +} + CX_TEST(test_buffer_clear) { char space[16]; strcpy(space, "clear test"); @@ -1505,6 +1568,9 @@ cx_test_register(suite, test_buffer_init_on_heap); cx_test_register(suite, test_buffer_minimum_capacity_sufficient); cx_test_register(suite, test_buffer_minimum_capacity_extend); + cx_test_register(suite, test_buffer_shrink); + cx_test_register(suite, test_buffer_shrink_copy_on_write); + cx_test_register(suite, test_buffer_shrink_copy_on_extend); cx_test_register(suite, test_buffer_clear); cx_test_register(suite, test_buffer_clear_copy_on_write); cx_test_register(suite, test_buffer_reset);