0

I am a beginner programming in C and just starting to work with circular buffers. I have implemented this code and need to adapt the queue and dequeue functions to use memcpy(). Does anyone know the correct way to implement it?

#define BUFFER_SIZE 8
#define MAX_PORT_A_RX_FRAME_SIZE 200
#define MAX_PORT_A_RX_FRAME_ID_SIZE 15

typedef struct {
    unsigned char Frame[MAX_PORT_A_RX_FRAME_SIZE];
    unsigned char Identifier[MAX_PORT_A_RX_FRAME_ID_SIZE];
    uint8_t Size;
    uint8_t IdentifierSize;
} PORT_ARxFrame_t;

typedef struct {
    PORT_ARxFrame_t buffer[BUFFER_SIZE];
    uint8_t head;
    uint8_t tail;
    uint8_t count;
} CircularBuffer;

void init(CircularBuffer *cb) {
    cb->head = 0;
    cb->tail = 0;
    cb->count = 0;
}

int is_empty(CircularBuffer *cb) {
    return (cb->count == 0);
}

int is_full(CircularBuffer *cb) {
    return (cb->count == BUFFER_SIZE);
}

int enqueue(CircularBuffer *cb, PORT_ARxFrame_t data) {
    if (is_full(cb)) {
    //overwrite oldest data
    cb->head = (cb->head + 1) % BUFFER_SIZE;        
    }
    else
    {
    cb->count++;
    }
    cb->buffer[cb->tail] = data;
    cb->tail = (cb->tail + 1) % BUFFER_SIZE; 

    return 1;  // success
}

PORT_ARxFrame_t dequeue(CircularBuffer *cb) {
    if (is_empty(cb)) {
    PORT_ARxFrame_t emptyFrame = { 0 };
    return emptyFrame;
    }
    PORT_ARxFrame_t data = cb->buffer[cb->head];
    cb->head = (cb->head + 1) % BUFFER_SIZE; 
    cb->count--;
    return data;
}
user16217248
  • 3,119
  • 19
  • 19
  • 37
JGS96
  • 1
  • 1
    Your statements `cb->buffer[cb->tail] = data;` and `data = cb->buffer[cb->head];` are essentially doing the same thing `memcpy` does. Why would you want to use `memcpy` here? It'll just make your code harder to read. – paddy Mar 26 '23 at 23:18
  • Why does your buffer only wrap around when full? Do the head and tail pointers not move? – stark Mar 27 '23 at 01:37
  • I suggest you clarify the question. It sounds like a task (reverse engineer two functions and rewrite it using `memcpy()`). – Allan Wind Mar 27 '23 at 04:18

0 Answers0