其他分享
首页 > 其他分享> > 环形队列 - stream_buffer

环形队列 - stream_buffer

作者:互联网

  环形队列是一种线性空间的FIFO数据结构,能实现个任务之间的快速数据通信,通常应用于uart、usb等通信中。

  环形队列是将数组空间的最后一个元素和第一个元素链接起来的一种环形结构,即数据到达最后一个元素时,就跳转至第一个元素。

  环形队列判断空和满的方法:

  a.附加一个标志位tag


  b.限制tail赶上head,即队尾结点与队首结点之间至少留有一个元素的空间。

代码实现:

stream_buffer.h

 1 #ifndef __STREAM_BUFFER_H
 2 #define __STREAM_BUFFER_H
 3 #include "def.h"
 4 
 5 typedef struct {
 6     uint8_t *buf;
 7     uint32_t size;
 8     uint32_t read_off;
 9     uint32_t write_off;
10 } StreamBuffer;
11 
12 int sbInit(StreamBuffer *sb, uint8_t *buf, uint32_t sz);
13 uint32_t sbRead(StreamBuffer *sb, uint8_t *buf, uint32_t sz);
14 uint32_t sbWrite(StreamBuffer *sb, uint8_t *buf, uint32_t sz);
15 uint32_t sbGetAvailableBytes(StreamBuffer *sb);
16 void sbReset(StreamBuffer *sb);
17 
18 #endif

stream_buffer.c

 1 #include "stream_buffer.h"
 2 
 3 int
 4 sbInit(StreamBuffer *sb, uint8_t *buf, uint32_t sz)
 5 {
 6     if(buf == NULL || sz <= 1) {
 7         return EC_FAIL;
 8     }
 9     
10     sb->size = sz;
11     sb->buf = buf;
12     sb->read_off = 0;
13     sb->write_off = 0;
14     return EC_OK;
15 }
16 
17 uint32_t
18 sbRead(StreamBuffer *sb, uint8_t *buf, uint32_t sz)
19 {
20     uint32_t request_sz = sz;
21     uint32_t read_sz = 0;
22     
23     while(request_sz) {
24         if(sb->read_off == sb->write_off) {
25             break;
26         }
27         *buf ++ = sb->buf[sb->read_off ++];
28         sb->read_off %= sb->size;
29         request_sz --;
30         read_sz ++;
31     }
32     return read_sz;
33 }
34 
35 uint32_t
36 sbWrite(StreamBuffer *sb, uint8_t *buf, uint32_t sz)
37 {
38     uint32_t post_sz = sz;
39     uint32_t write_sz = 0;
40     
41     while(post_sz) {
42         if(sb->read_off == ((sb->write_off + 1) % sb->size)) {
43             break;
44         }
45         sb->buf[sb->write_off ++] = *buf ++;
46         sb->write_off %= sb->size;
47         post_sz --;
48         write_sz ++;
49     }
50     return write_sz;
51 }
52 
53 uint32_t
54 sbGetAvailableBytes(StreamBuffer *sb)
55 {
56     if(sb->write_off >= sb->read_off) {
57         return sb->write_off - sb->read_off;
58     }
59     return sb->size - (sb->read_off - sb->write_off);
60 }
61 
62 void
63 sbReset(StreamBuffer *sb)
64 {
65     sb->read_off = 0;
66     sb->write_off = 0;
67 }

 

标签:sz,off,stream,buffer,write,队列,sb,buf,uint32
来源: https://www.cnblogs.com/ivan0512/p/16280126.html