#include #include #include #include "foobuf.h" int foobuf_init(struct foobuf **bufp, size_t len) { struct foobuf *buf = *bufp; if (!buf) { buf = calloc(sizeof *buf, 1); if (!buf) return 1; *bufp = buf; buf->data = calloc(len, sizeof(float)); if (!buf->data) return 1; buf->len = len; } else if (buf->len != len) { buf->data = realloc(buf->data, len * sizeof(float)); if (!buf->data) return 1; if (len > buf->len) { memset(&buf->data[buf->len], 0, len - buf->len); } else { if (buf->offset >= len) buf->offset = 0; } buf->len = len; } return 0; } float foobuf_read(struct foobuf *buf, size_t offset) { size_t len = buf->len; return buf->data[((buf->offset - offset) + len) % len]; } void foobuf_write(struct foobuf *buf, float val) { if (!buf || !buf->data) return; size_t offset = buf->offset; buf->data[offset] = val; offset++; if (offset == buf->len) offset = 0; buf->offset = offset; } int _struct_init(void **ptr, size_t size) { if (*ptr) return 0; if ((*ptr = calloc(1, size))) return 0; return 1; }