#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
#define RING_BUFFER_INIT_CAP 4096
#define LOG_DEBUG printf("\n%s:%d\n", __FUNCTION__, __LINE__)
class RingBuffer
{
public:
RingBuffer(uint32_t cap);
~RingBuffer();
uint32_t data_len(void);
void clear(void);
uint32_t push(uint8_t *buffer, uint32_t size);
uint32_t pop(uint8_t *buffer, uint32_t size);
private:
uint8_t* buffer;
uint32_t cap;
uint32_t write;
uint32_t read;
uint32_t get_power2(uint32_t n);
};
uint32_t RingBuffer::pop(uint8_t* buffer, uint32_t size)
{
if(!buffer)
{
return 0;
}
uint32_t len = 0;
size = MIN(size, this->data_len());
len = MIN(size, this->cap - (this->read & (this->cap - 1)));
memcpy(buffer, this->buffer + (this->read & (this->cap - 1)), len);
memcpy((uint8_t *)buffer + len, this->buffer, size - len);
this->read += size;
printf("pop data len = %d\n", size);
return size;
}
uint32_t RingBuffer::push(uint8_t *buffer, uint32_t size)
{
if(!buffer)
{
return 0;
}
uint32_t len = 0;
size = MIN(size, this->cap - this->data_len());
len = MIN(size, this->cap - (this->write & (this->cap - 1)));
memcpy(this->buffer + (this->write & (this->cap - 1)), buffer, len);
memcpy(this->buffer, (uint8_t *)buffer + len, size - len);
this->write += size;
printf("push data len = %d\n", size);
return size;
}
void RingBuffer::clear(void)
{
this->read = 0;
this->write = 0;
printf("rb clear\n");
}
uint32_t RingBuffer::data_len(void)
{
return (this->write - this->read);
}
uint32_t RingBuffer::get_power2(uint32_t n)
{
uint32_t power_of_2 = 1;
if(n)
{
if(n & (n - 1))
{
while (n > power_of_2)
{
power_of_2 <<= 1;
}
}
else
{
power_of_2 = n;
}
}
else
{
power_of_2 = RING_BUFFER_INIT_CAP;
}
return power_of_2;
}
RingBuffer::RingBuffer(uint32_t cap)
{
this->cap = get_power2(cap);
this->read = 0;
this->write = 0;
this->buffer = (uint8_t*)malloc(this->cap);
if(!this->buffer)
{
//exception
}
printf("rb ctor this->cap = %d\n", this->cap);
}
RingBuffer::~RingBuffer()
{
if(this->buffer)
{
free(this->buffer);
printf("rb xtor\n");
}
}
基于linux内核kfifo修改的环形缓冲区的C++程序
于 2023-09-13 09:10:57 首次发布