ringbuf/driver.c

103 lines
2.1 KiB
C

/* SPDX-License-Identifier: MIT */
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#ifndef DEBUG
#define DEBUG
#endif
// #define rb_size_t size_t
// #define rb_size_t int
#include "ringbuf.h"
typedef int DATATYPE;
int
main(void)
{
struct RingBuf rb;
DATATYPE d;
rb_init(&rb, 10, malloc, sizeof(DATATYPE));
rb_debug_print(&rb);
const DATATYPE arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int arrlen = (rb_size_t)(sizeof(arr) / sizeof(DATATYPE));
// Single writes
printf("\n=== Single writes ===\n\n");
rb_debug_print(&rb);
int idx = 0;
while(idx < 5) {
if(rb_push_back(&rb, &arr[idx], memcpy) != WriteOk) {
printf("Failed to write data to buffer...\n");
}
idx++;
}
rb_debug_print(&rb);
// Pop the last n elements
for(int a = 0; a < 10; a++) {
if(rb_pop_front(&rb, &d, memcpy) != ReadOk) {
printf("Failed to read data from buffer...\n");
break;
}
printf("Data: %d\n", d);
}
rb_debug_print(&rb);
if(rb.read_head == rb.write_head)
printf("OK\n");
printf("idx: %d\n", idx);
// Push the rest
while(idx < arrlen && rb_push_back(&rb, &arr[idx], memcpy) == WriteOk) {
idx++;
}
rb_debug_print(&rb);
printf("Data: [");
while(rb_pop_front(&rb, &d, memcpy) == ReadOk)
printf("%d,", d);
printf("\b]\n");
// Multiple writes
printf("\n=== Multiple writes ===\n\n");
rb_clear(&rb); // Make sure
rb_debug_print(&rb);
int ok = WriteOk; // Assume we can write
if(rb_push_many(&rb, arr, memcpy, 8) != WriteOk) {
printf("Failed to write data to buffer...\n");
}
rb_debug_print(&rb);
rb_debug_empty(&rb);
// Test wrap around
rb_push_many(&rb, arr, memcpy, 10);
rb_debug_print(&rb);
rb_debug_empty(&rb);
// Test clear
rb_clear(&rb);
if(rb_pop_front(&rb, &d, memcpy) != Empty) {
printf("Buffer is not empty after clear...\n");
}
rb_destroy(&rb, free);
enum WriteResult wr = WriteOk;
enum ReadResult rr = ReadOk;
printf("Size of wr: %lu bytes.\n", sizeof(wr));
printf("Size of rr: %lu bytes.\n", sizeof(rr));
return 0;
}