C语言实现环形队列(Circular Queue)
程序员文章站
2024-03-18 08:50:22
...
ring.c文件的内容:
void dma_ring_init(struct dma_ring_buf *ring)
{
ring->buf_size = RING_BUF_SIZE;
ring->w_ptr = 0;
ring->r_ptr = 0;
ring->overwrite_cnt = 0;
}
int dma_ring_getc(struct dma_ring_buf *ring, uint8_t *c)
{
if (ring->r_ptr == ring->w_ptr)
return RING_FAIL;
uint16_t next_ptr = ring->r_ptr + 1;
if (next_ptr >= ring->buf_size)
next_ptr = 0;
*c = ring->buf[ring->r_ptr];
ring->r_ptr = next_ptr;
return RING_SUCCESS;
}
int dma_ring_putc(struct dma_ring_buf *ring, uint8_t c)
{
uint16_t next_ptr = ring->w_ptr + 1;
if (next_ptr >= ring->buf_size)
next_ptr = 0;
if (next_ptr == ring->r_ptr)
{
ring->overwrite_cnt++;
return RING_FAIL;
}
ring->buf[ring->w_ptr] = c;
ring->w_ptr = next_ptr;
return RING_SUCCESS;
}
int dma_ring_available(struct dma_ring_buf *ring)
{
if (ring->w_ptr >= ring->r_ptr)
{
return ring->w_ptr - ring->r_ptr;
}
else
{
return ring->w_ptr + ring->buf_size - ring->r_ptr;
}
}
int dma_ring_available_linear(struct dma_ring_buf *ring)
{
if (ring->w_ptr >= ring->r_ptr)
{
return ring->w_ptr - ring->r_ptr;
}
else
{
return ring->buf_size - ring->r_ptr;
}
}
uint16_t dma_ring_get_w_ptr(struct dma_ring_buf *ring)
{
return ring->w_ptr;
}
uint16_t dma_ring_get_r_ptr(struct dma_ring_buf *ring)
{
return ring->r_ptr;
}
void dma_ring_forward_r_ptr(struct dma_ring_buf *ring, int len)
{
ring->r_ptr = (ring->r_ptr + len + ring->buf_size) % ring->buf_size;
}
void dma_ring_set_w_ptr(struct dma_ring_buf *ring, uint16_t w_ptr)
{
ring->w_ptr = w_ptr;
}
ring.h
#define RING_SUCCESS 0
#define RING_FAIL 1
#define RING_BUF_SIZE 2000
struct dma_ring_buf
{
uint8_t buf[RING_BUF_SIZE];
uint16_t buf_size;
uint16_t w_ptr, r_ptr;
uint16_t overwrite_cnt;
};
void dma_ring_init(struct dma_ring_buf *ring);
int dma_ring_getc(struct dma_ring_buf *ring, uint8_t *c);
int dma_ring_putc(struct dma_ring_buf *ring, uint8_t c);
int dma_ring_available(struct dma_ring_buf *ring);
int dma_ring_available_linear(struct dma_ring_buf *ring);
uint16_t dma_ring_get_w_ptr(struct dma_ring_buf *ring);
uint16_t dma_ring_get_r_ptr(struct dma_ring_buf *ring);
void dma_ring_forward_r_ptr(struct dma_ring_buf *ring, int len);
void dma_ring_set_w_ptr(struct dma_ring_buf *ring, uint16_t w_ptr);
上一篇: scapy模块分析数据包
下一篇: Linux网络----数据包的接收过程