Files: 033d2aa1890af2ff80fde819e83b034484c47cbc / foobuf.c
845 bytesRaw
1 | |
2 | |
3 | |
4 | |
5 | |
6 | int foobuf_init(struct foobuf **bufp, size_t len) |
7 | { |
8 | struct foobuf *buf = *bufp; |
9 | if (!buf) buf = calloc(sizeof *buf, 1); |
10 | if (!buf) return 1; |
11 | if (buf->len != len) { |
12 | buf->data = realloc(buf->data, len * sizeof(buf->data[0])); |
13 | if (len > buf->len) { |
14 | memset(&buf->data[buf->len], 0, len - buf->len); |
15 | } else { |
16 | if (buf->offset >= len) buf->offset = 0; |
17 | } |
18 | buf->len = len; |
19 | } |
20 | *bufp = buf; |
21 | return 0; |
22 | } |
23 | |
24 | float foobuf_read(struct foobuf *buf, size_t offset) |
25 | { |
26 | size_t len = buf->len; |
27 | return buf->data[((buf->offset - offset) + len) % len]; |
28 | } |
29 | |
30 | void foobuf_write(struct foobuf *buf, float val) |
31 | { |
32 | if (!buf || !buf->data) return; |
33 | size_t offset = buf->offset; |
34 | buf->data[offset] = val; |
35 | offset++; |
36 | if (offset == buf->len) offset = 0; |
37 | buf->offset = offset; |
38 | } |
39 |
Built with git-ssb-web