2015-09-24 21:51:00 +02:00
|
|
|
/*
|
|
|
|
* Copyright (C) 2015 Kaspar Schleiser <kaspar@schleiser.de>
|
|
|
|
*
|
|
|
|
* This file is subject to the terms and conditions of the GNU Lesser
|
|
|
|
* General Public License v2.1. See the file LICENSE in the top level
|
|
|
|
* directory for more details.
|
|
|
|
*/
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @ingroup sys
|
|
|
|
* @{
|
|
|
|
* @file
|
|
|
|
* @brief thread-safe ringbuffer implementation
|
|
|
|
*
|
|
|
|
* @author Kaspar Schleiser <kaspar@schleiser.de>
|
|
|
|
*
|
|
|
|
* @}
|
|
|
|
*/
|
|
|
|
|
|
|
|
#include "tsrb.h"
|
|
|
|
|
2019-06-05 12:25:12 +02:00
|
|
|
static void _push(tsrb_t *rb, uint8_t c)
|
2015-09-24 21:51:00 +02:00
|
|
|
{
|
|
|
|
rb->buf[rb->writes++ & (rb->size - 1)] = c;
|
|
|
|
}
|
|
|
|
|
2019-06-05 12:25:12 +02:00
|
|
|
static uint8_t _pop(tsrb_t *rb)
|
2015-09-24 21:51:00 +02:00
|
|
|
{
|
|
|
|
return rb->buf[rb->reads++ & (rb->size - 1)];
|
|
|
|
}
|
|
|
|
|
|
|
|
int tsrb_get_one(tsrb_t *rb)
|
|
|
|
{
|
|
|
|
if (!tsrb_empty(rb)) {
|
2019-06-05 12:50:38 +02:00
|
|
|
return _pop(rb);
|
2015-09-24 21:51:00 +02:00
|
|
|
}
|
|
|
|
else {
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-06-05 12:25:12 +02:00
|
|
|
int tsrb_get(tsrb_t *rb, uint8_t *dst, size_t n)
|
2015-09-24 21:51:00 +02:00
|
|
|
{
|
|
|
|
size_t tmp = n;
|
|
|
|
while (tmp && !tsrb_empty(rb)) {
|
|
|
|
*dst++ = _pop(rb);
|
|
|
|
tmp--;
|
|
|
|
}
|
|
|
|
return (n - tmp);
|
|
|
|
}
|
|
|
|
|
2018-08-31 10:35:02 +02:00
|
|
|
int tsrb_drop(tsrb_t *rb, size_t n)
|
|
|
|
{
|
|
|
|
size_t tmp = n;
|
|
|
|
while (tmp && !tsrb_empty(rb)) {
|
|
|
|
_pop(rb);
|
|
|
|
tmp--;
|
|
|
|
}
|
|
|
|
return (n - tmp);
|
|
|
|
}
|
|
|
|
|
2019-06-05 12:25:12 +02:00
|
|
|
int tsrb_add_one(tsrb_t *rb, uint8_t c)
|
2015-09-24 21:51:00 +02:00
|
|
|
{
|
|
|
|
if (!tsrb_full(rb)) {
|
|
|
|
_push(rb, c);
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-06-05 12:25:12 +02:00
|
|
|
int tsrb_add(tsrb_t *rb, const uint8_t *src, size_t n)
|
2015-09-24 21:51:00 +02:00
|
|
|
{
|
|
|
|
size_t tmp = n;
|
|
|
|
while (tmp && !tsrb_full(rb)) {
|
|
|
|
_push(rb, *src++);
|
|
|
|
tmp--;
|
|
|
|
}
|
|
|
|
return (n - tmp);
|
|
|
|
}
|