Skip to content

Commit

Permalink
Merge pull request #5813 from EmergReanimator/code_improvements
Browse files Browse the repository at this point in the history
Introduced ringbuf_init to perform static buffer initialisation
  • Loading branch information
tannewt authored Jan 10, 2022
2 parents 49451c0 + e712e50 commit 838a007
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 6 deletions.
3 changes: 2 additions & 1 deletion ports/unix/coverage.c
Original file line number Diff line number Diff line change
Expand Up @@ -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");

Expand Down
14 changes: 13 additions & 1 deletion py/ringbuf.c
Original file line number Diff line number Diff line change
Expand Up @@ -27,19 +27,31 @@

#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;
return r->buf != NULL;
}

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);
}
Expand Down
7 changes: 3 additions & 4 deletions py/ringbuf.h
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit 838a007

Please sign in to comment.