forked from zephyrproject-rtos/zephyr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ring_buffer.c
94 lines (80 loc) · 2.21 KB
/
ring_buffer.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/* ring_buffer.c: Simple ring buffer API */
/*
* Copyright (c) 2015 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <misc/ring_buffer.h>
/**
* Internal data structure for a buffer header.
*
* We want all of this to fit in a single uint32_t. Every item stored in the
* ring buffer will be one of these headers plus any extra data supplied
*/
struct ring_element {
uint32_t type :16; /**< Application-specific */
uint32_t length :8; /**< length in 32-bit chunks */
uint32_t value :8; /**< Room for small integral values */
};
int sys_ring_buf_put(struct ring_buf *buf, uint16_t type, uint8_t value,
uint32_t *data, uint8_t size32)
{
uint32_t i, space, index, rc;
space = sys_ring_buf_space_get(buf);
if (space >= (size32 + 1)) {
struct ring_element *header =
(struct ring_element *)&buf->buf[buf->tail];
header->type = type;
header->length = size32;
header->value = value;
if (likely(buf->mask)) {
for (i = 0; i < size32; ++i) {
index = (i + buf->tail + 1) & buf->mask;
buf->buf[index] = data[i];
}
buf->tail = (buf->tail + size32 + 1) & buf->mask;
} else {
for (i = 0; i < size32; ++i) {
index = (i + buf->tail + 1) % buf->size;
buf->buf[index] = data[i];
}
buf->tail = (buf->tail + size32 + 1) % buf->size;
}
rc = 0;
} else {
buf->dropped_put_count++;
rc = -EMSGSIZE;
}
return rc;
}
int sys_ring_buf_get(struct ring_buf *buf, uint16_t *type, uint8_t *value,
uint32_t *data, uint8_t *size32)
{
struct ring_element *header;
uint32_t i, index;
if (sys_ring_buf_is_empty(buf)) {
return -EAGAIN;
}
header = (struct ring_element *) &buf->buf[buf->head];
if (header->length > *size32) {
*size32 = header->length;
return -EMSGSIZE;
}
*size32 = header->length;
*type = header->type;
*value = header->value;
if (likely(buf->mask)) {
for (i = 0; i < header->length; ++i) {
index = (i + buf->head + 1) & buf->mask;
data[i] = buf->buf[index];
}
buf->head = (buf->head + header->length + 1) & buf->mask;
} else {
for (i = 0; i < header->length; ++i) {
index = (i + buf->head + 1) % buf->size;
data[i] = buf->buf[index];
}
buf->head = (buf->head + header->length + 1) % buf->size;
}
return 0;
}