buffer.c 534 Bytes
Newer Older
Jacob Vosmaer's avatar
Jacob Vosmaer committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include "buffer.h"
#include <util/atomic.h>

enum { BUFFER_SIZE = 16 };

static uint8_t _buf[BUFFER_SIZE];
static uint8_t _buf_head;
static uint8_t _buf_tail;

void
buffer_push(uint8_t x)
{
	ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
		_buf[_buf_tail] = x;
		_buf_tail = (_buf_tail + 1) % BUFFER_SIZE;
	}
}

uint8_t
Jacob Vosmaer's avatar
Jacob Vosmaer committed
20
buffer_pop(uint8_t *x)
Jacob Vosmaer's avatar
Jacob Vosmaer committed
21 22
{
	ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
Jacob Vosmaer's avatar
Jacob Vosmaer committed
23
		if (_buf_head == _buf_tail) {
Jacob Vosmaer's avatar
Jacob Vosmaer committed
24
			return 1; // error: buffer is empty
Jacob Vosmaer's avatar
Jacob Vosmaer committed
25
		}
Jacob Vosmaer's avatar
Jacob Vosmaer committed
26

Jacob Vosmaer's avatar
Jacob Vosmaer committed
27 28
		*x = _buf[_buf_head];
		_buf_head = (_buf_head + 1) % BUFFER_SIZE;
Jacob Vosmaer's avatar
Jacob Vosmaer committed
29 30
	}

Jacob Vosmaer's avatar
Jacob Vosmaer committed
31
	return 0;
Jacob Vosmaer's avatar
Jacob Vosmaer committed
32
}