diff options
Diffstat (limited to 'include/ring.h')
-rw-r--r-- | include/ring.h | 79 |
1 files changed, 79 insertions, 0 deletions
diff --git a/include/ring.h b/include/ring.h new file mode 100644 index 0000000..b64f462 --- /dev/null +++ b/include/ring.h @@ -0,0 +1,79 @@ +/* + * (C) Copyright 2014 Leo C. <erbl259-lmu@yahoo.de> + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +#ifndef RING_H +#define RING_H + +struct ring { + uint8_t *data; + uint_fast8_t mask; + volatile uint_fast8_t begin; + volatile uint_fast8_t end; +}; + + +static inline +void ring_init(struct ring *ring, uint8_t *buf, int size) +{ + ring->data = buf; + ring->mask = (size-1) & 0xff; + ring->begin = 0; + ring->end = 0; +} + +static inline +int ring_write_ch(struct ring *ring, uint8_t ch) +{ + uint_fast8_t ep = ring->end; + + ring->data[ep] = ch; + ep = (ep + 1) & ring->mask; + + if ((ep) != ring->begin) { + ring->end = ep; + return 1; + } + + return -1; +} + +#if 0 +static inline +int ring_write(struct ring *ring, uint8_t *data, int size) +{ + int i; + + for (i = 0; i < size; i++) { + if (ring_write_ch(ring, data[i]) < 0) + return -i; + } + + return i; +} +#endif + +static inline +int ring_read_ch(struct ring *ring) +{ + int ret = -1; + uint_fast8_t bp = ring->begin; + + if (bp != ring->end) { + ret = ring->data[bp]; + ring->begin = (bp + 1) & ring->mask; + } + + return ret; +} + + +static inline +int_fast8_t ring_is_empty(struct ring *ring) +{ + return ring->begin == ring->end; +} + +#endif /* RING_H */ |