Firmware SDK
twr_queue.c
1 #include <twr_queue.h>
2 
3 void twr_queue_init(twr_queue_t *queue, void *buffer, size_t size)
4 {
5  memset(queue, 0, sizeof(*queue));
6 
7  queue->_buffer = buffer;
8  queue->_size = size;
9 }
10 
11 bool twr_queue_put(twr_queue_t *queue, const void *buffer, size_t length)
12 {
13  if (length == 0)
14  {
15  return true;
16  }
17 
18  if (sizeof(length) + length > queue->_size - queue->_length)
19  {
20  return false;
21  }
22 
23  uint8_t *p = queue->_buffer;
24 
25  p += queue->_length;
26 
27  memcpy(p, &length, sizeof(length));
28 
29  p += sizeof(length);
30 
31  queue->_length += sizeof(length) + length;
32 
33  if (buffer != NULL)
34  {
35  memcpy(p, buffer, length);
36  }
37  else
38  {
39  memset(p, 0, length);
40  }
41 
42  return true;
43 }
44 
45 bool twr_queue_get(twr_queue_t *queue, void *buffer, size_t *length)
46 {
47  if (queue->_length == 0)
48  {
49  return false;
50  }
51 
52  uint8_t *p = queue->_buffer;
53 
54  memcpy(length, p, sizeof(*length));
55 
56  p += sizeof(*length);
57 
58  queue->_length -= sizeof(*length) + *length;
59 
60  if (buffer != NULL)
61  {
62  memcpy(buffer, p, *length);
63  }
64 
65  memmove(queue->_buffer, p + *length, queue->_length);
66 
67  return true;
68 }
69 
70 void twr_queue_clear(twr_queue_t *queue)
71 {
72  queue->_length = 0;
73 }
void twr_queue_init(twr_queue_t *queue, void *buffer, size_t size)
Initialize queue.
Definition: twr_queue.c:3
bool twr_queue_put(twr_queue_t *queue, const void *buffer, size_t length)
Put buffer to queue.
Definition: twr_queue.c:11
bool twr_queue_get(twr_queue_t *queue, void *buffer, size_t *length)
Get queue to buffer.
Definition: twr_queue.c:45
void twr_queue_clear(twr_queue_t *queue)
Clear queue.
Definition: twr_queue.c:70