| #include "../../unity/unity.h" |
| #include <stdlib.h> |
| #include <string.h> |
| #include <stdint.h> |
| #include <unistd.h> |
|
|
| |
| |
| |
| extern void alloc_ibuf(void); |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| extern char *swab_buffer(char *buf, idx_t *nread, int *saved_byte); |
|
|
| |
| |
| |
|
|
| static size_t get_page_size_fallback(void) |
| { |
| long ps = -1; |
| #ifdef _SC_PAGESIZE |
| ps = sysconf(_SC_PAGESIZE); |
| #elif defined(_SC_PAGE_SIZE) |
| ps = sysconf(_SC_PAGE_SIZE); |
| #endif |
| if (ps <= 0) |
| return 4096; |
| return (size_t)ps; |
| } |
|
|
| void setUp(void) |
| { |
| |
| if (ibuf) { |
| free(ibuf); |
| } |
| ibuf = NULL; |
| |
| obuf = NULL; |
|
|
| |
| page_size = (typeof(page_size))get_page_size_fallback(); |
| input_blocksize = 64; |
| conversions_mask = 0; |
| } |
|
|
| void tearDown(void) |
| { |
| if (ibuf) { |
| free(ibuf); |
| ibuf = NULL; |
| } |
| obuf = NULL; |
| } |
|
|
| static void assert_pointer_aligned(void *p, size_t align) |
| { |
| |
| TEST_ASSERT_NOT_NULL_MESSAGE(p, "Pointer is NULL; expected an allocated buffer"); |
| TEST_ASSERT_EQUAL_UINT64_MESSAGE(0ULL, ((uintptr_t)p) % align, |
| "Allocated buffer is not aligned to page_size"); |
| } |
|
|
| void test_alloc_ibuf_basic_allocation_and_alignment(void) |
| { |
| |
| alloc_ibuf(); |
|
|
| |
| assert_pointer_aligned(ibuf, (size_t)page_size); |
|
|
| |
| ibuf[0] = (char)0xAA; |
| ibuf[input_blocksize - 1] = (char)0x55; |
| TEST_ASSERT_EQUAL_HEX8((char)0xAA, ibuf[0]); |
| TEST_ASSERT_EQUAL_HEX8((char)0x55, ibuf[input_blocksize - 1]); |
| } |
|
|
| void test_alloc_ibuf_idempotent_no_realloc(void) |
| { |
| |
| alloc_ibuf(); |
| char *first = ibuf; |
| TEST_ASSERT_NOT_NULL(first); |
|
|
| |
| |
| input_blocksize = 128; |
| conversions_mask = C_SWAB; |
| alloc_ibuf(); |
|
|
| |
| TEST_ASSERT_EQUAL_PTR(first, ibuf); |
| } |
|
|
| void test_alloc_ibuf_with_swab_extra_byte_supports_swab_buffer(void) |
| { |
| |
| conversions_mask = C_SWAB; |
| input_blocksize = 6; |
|
|
| alloc_ibuf(); |
| assert_pointer_aligned(ibuf, (size_t)page_size); |
|
|
| |
| const char pattern[6] = { 'A', 'B', 'C', 'D', 'E', 'F' }; |
| memcpy(ibuf, pattern, sizeof(pattern)); |
|
|
| |
| |
| int saved_byte = -1; |
| typeof(input_blocksize) nread = input_blocksize; |
|
|
| char *start = swab_buffer(ibuf, &nread, &saved_byte); |
|
|
| |
| |
| TEST_ASSERT_EQUAL_PTR(ibuf + 1, start); |
| TEST_ASSERT_EQUAL_INT64(6, nread); |
| TEST_ASSERT_EQUAL_INT(-1, saved_byte); |
|
|
| const char expected[6] = { 'B', 'A', 'D', 'C', 'F', 'E' }; |
| TEST_ASSERT_EQUAL_MEMORY(expected, start, sizeof(expected)); |
| } |
|
|
| int main(void) |
| { |
| UNITY_BEGIN(); |
| RUN_TEST(test_alloc_ibuf_basic_allocation_and_alignment); |
| RUN_TEST(test_alloc_ibuf_idempotent_no_realloc); |
| RUN_TEST(test_alloc_ibuf_with_swab_extra_byte_supports_swab_buffer); |
| return UNITY_END(); |
| } |