0002-consume-append.c (1875B)
1 #include <stdlib.h> 2 #include <string.h> 3 4 #include "assert.h" 5 #include "buf.h" 6 7 // Append paths after buf_consume moved dat past alloc 8 9 void test_append_reuses_tail_capacity() { 10 struct buf subject; 11 memset(&subject, 0, sizeof subject); 12 13 ASSERT("Fill buffer", buf_append(&subject, "0123456789", 10) == 0); 14 ASSERT("Consume head of buffer", buf_consume(&subject, 4) == 4); 15 16 // 6 + 20 <= 28 available, so neither eject nor grow may run 17 ASSERT("Append into remaining tail capacity", buf_append(&subject, "ABCDEFGHIJKLMNOPQRST", 20) == 0); 18 19 ASSERT("Data pointer unchanged by in-place append", subject.dat - subject.alloc == 4); 20 ASSERT("Capacity unchanged by in-place append", subject.cap == 28); 21 ASSERT("Length includes append", subject.len == 26); 22 ASSERT("Appended data follows unconsumed data", memcmp(subject.dat, "456789ABCDEFGHIJKLMNOPQRST", 26) == 0); 23 24 buf_clear(&subject); 25 } 26 27 void test_append_ejects_without_growing() { 28 struct buf subject; 29 memset(&subject, 0, sizeof subject); 30 31 ASSERT("Fill buffer", buf_append(&subject, "0123456789", 10) == 0); 32 ASSERT("Consume head of buffer", buf_consume(&subject, 8) == 8); 33 34 // 2 + 25 > 24 available, but the 8 consumed bytes reclaim enough: 35 // eject must run and grow must not 36 ASSERT("Append forcing eject", buf_append(&subject, "abcdefghijklmnopqrstuvwxy", 25) == 0); 37 38 ASSERT("Data pointer reset to allocation start", subject.dat == subject.alloc); 39 ASSERT("Eject reclaimed consumed head space", subject.cap == 32); 40 ASSERT("Length includes append", subject.len == 27); 41 ASSERT("Appended data follows unconsumed data", memcmp(subject.dat, "89abcdefghijklmnopqrstuvwxy", 27) == 0); 42 43 buf_clear(&subject); 44 } 45 46 int main(int argc, const char *argv[]) { 47 buf_set_allocator(realloc, free); 48 49 RUN(test_append_reuses_tail_capacity); 50 RUN(test_append_ejects_without_growing); 51 return TEST_REPORT(); 52 }