#include "ringbuffer.h"

// ʼλ
void ringbuffer_init(ringbuffer_t *rb)
{
    // öָдָʼֵΪ0
    rb->r = 0;
    rb->w = 0;
    // ڴ
    memset(rb->buffer, 0, sizeof(uint8_t) * RINGBUFFER_SIZE);
    // ʼĿΪ0
    rb->itemCount = 0;
}

// 黷λǷ
uint8_t ringbuffer_is_full(ringbuffer_t *rb)
{
    // ĿڻС1򷵻0δ
    return (rb->itemCount == RINGBUFFER_SIZE);
}

// 黷λǷΪ
uint8_t ringbuffer_is_empty(ringbuffer_t *rb)
{
    // ĿΪ01Ϊգ򷵻0ǿգ
    return (rb->itemCount == 0);
}

// λд
int8_t ringbuffer_write(ringbuffer_t *rb, uint8_t *data, uint32_t num)
{
    // -1
    if(ringbuffer_is_full(rb))
        return -1;
        
    // д뻺
    while(num--)
    {
        rb->buffer[rb->w] = *data++;  // дݲƶдָ
        rb->w = (rb->w + 1) % RINGBUFFER_SIZE;  // дָѭ
        rb->itemCount++;  // Ŀ
    }
    
    return 0;  // дɹ0
}

// ӻλȡ
int8_t ringbuffer_read(ringbuffer_t *rb, uint8_t *data, uint32_t num)
{
    // Ϊգ-1
    if(ringbuffer_is_empty(rb))
        return -1;
    
    // ӻȡ
    while(num--)
    {
        *data++ = rb->buffer[rb->r];  // ȡݲƶָ
        rb->r = (rb->r + 1) % RINGBUFFER_SIZE;  // ָѭ
        rb->itemCount--;  // Ŀ
    }
    return 0;  // ȡɹ0
}
