| 1 | #include "structures/tests/test_internal.h" |
| 2 | |
| 3 | TEST_GROUP_DECLARE(spsc_fifo); |
| 4 | |
| 5 | TEST_DECLARE_UNIT(spsc_fifo, byte_stream_and_wraparound) { |
| 6 | struct spsc_fifo fifo; |
| 7 | bool ok = spsc_fifo_init(fifo: &fifo, size: 16); |
| 8 | TEST_ASSERT(ok); |
| 9 | TEST_ASSERT_EQ(fifo.size, 16); |
| 10 | TEST_ASSERT(spsc_fifo_is_empty(&fifo)); |
| 11 | TEST_ASSERT_EQ(spsc_fifo_avail(&fifo), 16); |
| 12 | |
| 13 | const char *msg1 = "Hello, World!" ; |
| 14 | size_t len1 = 13; |
| 15 | size_t written = spsc_fifo_write(fifo: &fifo, src: msg1, len: len1); |
| 16 | TEST_ASSERT_EQ(written, len1); |
| 17 | TEST_ASSERT_EQ(spsc_fifo_len(&fifo), len1); |
| 18 | TEST_ASSERT_EQ(spsc_fifo_avail(&fifo), 3); |
| 19 | |
| 20 | /* Peek without consuming */ |
| 21 | char peek_buf[16] = {0}; |
| 22 | size_t peeked = spsc_fifo_peek(fifo: &fifo, dst: peek_buf, len: len1); |
| 23 | TEST_ASSERT_EQ(peeked, len1); |
| 24 | TEST_ASSERT(!memcmp(peek_buf, msg1, len1)); |
| 25 | TEST_ASSERT_EQ(spsc_fifo_len(&fifo), len1); |
| 26 | |
| 27 | /* Read partial */ |
| 28 | char read_buf[16] = {0}; |
| 29 | size_t read_bytes = spsc_fifo_read(fifo: &fifo, dst: read_buf, len: 7); |
| 30 | TEST_ASSERT_EQ(read_bytes, 7); |
| 31 | TEST_ASSERT(!memcmp(read_buf, "Hello, " , 7)); |
| 32 | TEST_ASSERT_EQ(spsc_fifo_len(&fifo), 6); |
| 33 | |
| 34 | /* Write across ring wraparound boundary */ |
| 35 | const char *msg2 = "12345678" ; |
| 36 | size_t written2 = spsc_fifo_write(fifo: &fifo, src: msg2, len: 8); |
| 37 | TEST_ASSERT_EQ(written2, 8); |
| 38 | TEST_ASSERT_EQ(spsc_fifo_len(&fifo), 14); |
| 39 | |
| 40 | /* Read the remainder of msg1 and all of msg2 */ |
| 41 | char full_read[16] = {0}; |
| 42 | size_t read_total = spsc_fifo_read(fifo: &fifo, dst: full_read, len: 14); |
| 43 | TEST_ASSERT_EQ(read_total, 14); |
| 44 | TEST_ASSERT(!memcmp(full_read, "World!12345678" , 14)); |
| 45 | TEST_ASSERT(spsc_fifo_is_empty(&fifo)); |
| 46 | |
| 47 | spsc_fifo_destroy(fifo: &fifo); |
| 48 | return TEST_SUCCESS; |
| 49 | } |
| 50 | |
| 51 | TEST_DECLARE_UNIT(spsc_fifo, ptr_helpers) { |
| 52 | struct spsc_fifo fifo; |
| 53 | bool ok = spsc_fifo_init(fifo: &fifo, size: 8 * sizeof(void *)); |
| 54 | TEST_ASSERT(ok); |
| 55 | |
| 56 | void *ptrs[4] = {(void *) 0x1000, (void *) 0x2000, (void *) 0x3000, |
| 57 | (void *) 0x4000}; |
| 58 | for (int i = 0; i < 4; i++) { |
| 59 | TEST_ASSERT(spsc_fifo_push_ptr(&fifo, ptrs[i])); |
| 60 | } |
| 61 | |
| 62 | for (int i = 0; i < 4; i++) { |
| 63 | void *out = NULL; |
| 64 | TEST_ASSERT(spsc_fifo_pop_ptr(&fifo, &out)); |
| 65 | TEST_ASSERT_EQ(out, ptrs[i]); |
| 66 | } |
| 67 | |
| 68 | TEST_ASSERT(spsc_fifo_is_empty(&fifo)); |
| 69 | spsc_fifo_destroy(fifo: &fifo); |
| 70 | return TEST_SUCCESS; |
| 71 | } |
| 72 | |