How to implement circular buffer using memcpy in C

395 views Asked by At

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;
}
0

There are 0 answers