Merge pull request #5813 from EmergReanimator/code_improvements

Introduced ringbuf_init to perform static buffer initialisation
This commit is contained in:
Scott Shawcroft 2022-01-10 12:12:25 -08:00 committed by GitHub
commit 838a007ca9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 18 additions and 6 deletions

View File

@ -527,7 +527,8 @@ STATIC mp_obj_t extra_coverage(void) {
// ringbuf
{
byte buf[100];
ringbuf_t ringbuf = {buf, sizeof(buf), 0, 0};
ringbuf_t ringbuf;
ringbuf_init(&ringbuf, &buf[0], sizeof(buf));
mp_printf(&mp_plat_print, "# ringbuf\n");

View File

@ -27,11 +27,20 @@
#include "ringbuf.h"
bool ringbuf_init(ringbuf_t *r, uint8_t *buf, size_t capacity) {
r->heap = false;
r->buf = buf;
r->size = capacity;
r->iget = r->iput = 0;
return r->buf != NULL;
}
// Dynamic initialization. This should be accessible from a root pointer.
// capacity is the number of bytes the ring buffer can hold. The actual
// size of the buffer is one greater than that, due to how the buffer
// handles empty and full statuses.
bool ringbuf_alloc(ringbuf_t *r, size_t capacity, bool long_lived) {
r->heap = true;
r->buf = gc_alloc(capacity + 1, false, long_lived);
r->size = capacity + 1;
r->iget = r->iput = 0;
@ -39,7 +48,10 @@ bool ringbuf_alloc(ringbuf_t *r, size_t capacity, bool long_lived) {
}
void ringbuf_free(ringbuf_t *r) {
gc_free(r->buf);
if (r->heap) {
gc_free(r->buf);
}
r->buf = (uint8_t *)NULL;
r->size = 0;
ringbuf_clear(r);
}

View File

@ -37,14 +37,13 @@ typedef struct _ringbuf_t {
uint32_t size;
uint32_t iget;
uint32_t iput;
bool heap;
} ringbuf_t;
// Note that the capacity of the buffer is N-1!
// Static initialization:
// byte buf_array[N];
// ringbuf_t buf = {buf_array, sizeof(buf_array)};
// For static initialization use ringbuf_init()
bool ringbuf_init(ringbuf_t *r, uint8_t *buf, size_t capacity);
bool ringbuf_alloc(ringbuf_t *r, size_t capacity, bool long_lived);
void ringbuf_free(ringbuf_t *r);
size_t ringbuf_capacity(ringbuf_t *r);