commit | author | age
|
d6b4a7
|
1 |
/********************************************************************************* |
G |
2 |
* Copyright: (C) 2023 LingYun IoT System Studio. |
|
3 |
* All rights reserved. |
|
4 |
* |
|
5 |
* Filename: ringbuf.c |
|
6 |
* Description: This file is common ring buffer API functions |
|
7 |
* |
|
8 |
* Version: 1.0.0(11/08/23) |
|
9 |
* Author: Guo Wenxue <guowenxue@gmail.com> |
|
10 |
* ChangeLog: 1, Release initial version on "11/08/23 16:18:43" |
|
11 |
* |
|
12 |
********************************************************************************/ |
|
13 |
|
|
14 |
#include <string.h> |
|
15 |
#include <assert.h> |
|
16 |
#include "ringbuf.h" |
|
17 |
|
|
18 |
void rb_init (struct ring_buffer *ring, unsigned char* buff, int size) |
|
19 |
{ |
|
20 |
memset (ring, 0, sizeof (struct ring_buffer)); |
|
21 |
ring->rd_pointer = 0; |
|
22 |
ring->wr_pointer = 0; |
|
23 |
ring->buffer= buff; |
|
24 |
ring->size = size; |
|
25 |
} |
|
26 |
|
|
27 |
|
|
28 |
int rb_write (struct ring_buffer *rb, unsigned char * buf, int len) |
|
29 |
{ |
|
30 |
int total; |
|
31 |
int i; |
|
32 |
|
|
33 |
/* total = len = min(space, len) */ |
|
34 |
total = rb_free_size(rb); |
|
35 |
if(len > total) |
|
36 |
len = total; |
|
37 |
else |
|
38 |
total = len; |
|
39 |
|
|
40 |
i = rb->wr_pointer; |
|
41 |
if(i + len > rb->size) |
|
42 |
{ |
|
43 |
memcpy(rb->buffer + i, buf, rb->size - i); |
|
44 |
buf += rb->size - i; |
|
45 |
len -= rb->size - i; |
|
46 |
i = 0; |
|
47 |
} |
|
48 |
|
|
49 |
memcpy(rb->buffer + i, buf, len); |
|
50 |
rb->wr_pointer = i + len; |
|
51 |
return total; |
|
52 |
} |
|
53 |
|
|
54 |
|
|
55 |
int rb_free_size (struct ring_buffer *rb) |
|
56 |
{ |
|
57 |
return (rb->size - 1 - rb_data_size(rb)); |
|
58 |
} |
|
59 |
|
|
60 |
|
|
61 |
int rb_read (struct ring_buffer *rb, unsigned char * buf, int max) |
|
62 |
{ |
|
63 |
int total; |
|
64 |
int i; |
|
65 |
|
|
66 |
/* total = len = min(used, len) */ |
|
67 |
total = rb_data_size(rb); |
|
68 |
|
|
69 |
if(max > total) |
|
70 |
max = total; |
|
71 |
else |
|
72 |
total = max; |
|
73 |
|
|
74 |
|
|
75 |
i = rb->rd_pointer; |
|
76 |
if(i + max > rb->size) |
|
77 |
{ |
|
78 |
memcpy(buf, rb->buffer + i, rb->size - i); |
|
79 |
buf += rb->size - i; |
|
80 |
max -= rb->size - i; |
|
81 |
i = 0; |
|
82 |
} |
|
83 |
|
|
84 |
memcpy(buf, rb->buffer + i, max); |
|
85 |
rb->rd_pointer = i + max; |
|
86 |
|
|
87 |
return total; |
|
88 |
} |
|
89 |
|
|
90 |
int rb_data_size (struct ring_buffer *rb) |
|
91 |
{ |
|
92 |
return ((rb->wr_pointer - rb->rd_pointer) & (rb->size-1)); |
|
93 |
} |
|
94 |
|
|
95 |
void rb_clear (struct ring_buffer *rb) |
|
96 |
{ |
|
97 |
memset(rb->buffer,0,rb->size); |
|
98 |
rb->rd_pointer=0; |
|
99 |
rb->wr_pointer=0; |
|
100 |
} |
|
101 |
|
|
102 |
unsigned char rb_peek(struct ring_buffer* rb, int index) |
|
103 |
{ |
|
104 |
assert(index < rb_data_size(rb)); |
|
105 |
|
|
106 |
return rb->buffer[((rb->rd_pointer + index) % rb->size)]; |
|
107 |
} |