summaryrefslogtreecommitdiff
path: root/tests/usb-serial-rs485/ringb.c
blob: 245325bbd39ff44c9a045fde4f445197f0707e79 (plain)
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
#include "ringb.h"
void ringb_init(struct ringb *ring, uint8_t *buf, int len)
{
	ring->buf_len = len;
	ring->buf = buf;
	ring->idx_r = 0;
	ring->idx_w = 0;
}

int ringb_get(struct ringb *ring) {
#if 1
	int rval;
	if (ring->idx_r != ring->idx_w) {
		rval = ring->buf[ring->idx_r];
		ring->idx_r = (ring->idx_r + 1) % ring->buf_len;
		return rval;
	}
	return -1;
#else
	if (((ring->idx_w - ring->idx_r) % ring->buf_len) >= 0) {
		int rval = ring->buf[ring->idx_r];
		ring->idx_r = (ring->idx_r + 1) % ring->buf_len;
		return rval;
	} else {
		return -1;
	}
#endif
}

bool ringb_put(struct ringb *ring, uint8_t c) {
#if 1
	unsigned int next = (ring->idx_w + 1) % ring->buf_len;
	if (next != ring->idx_r) {
		ring->buf[ring->idx_w] = c;
		ring->idx_w = next;
		return true;
	}
	return false;
#else
	if (((ring->idx_w - ring->idx_r) % ring->buf_len) == 0) {
		return false;
	}
	ring->buf[ring->idx_w] = c;
	ring->idx_w = (ring->idx_w + 1) % ring->buf_len;
	return true;
#endif
	
}


void ringb_flush(struct ringb *ring) {
	ring->idx_r = 0;
	ring->idx_w = 0;
}

int ringb_depth(struct ringb *ring) {
	return ((unsigned int)(ring->idx_w - ring->idx_r) % ring->buf_len);
}