8000 Merge pull request #5813 from EmergReanimator/code_improvements · adafruit/circuitpython@838a007 · GitHub
[go: up one dir, main page]

Skip to content

Commit 838a007

Browse files
authored
Merge pull request #5813 from EmergReanimator/code_improvements
Introduced ringbuf_init to perform static buffer initialisation
2 parents 49451c0 + e712e50 commit 838a007

File tree

3 files changed

+18
-6
lines changed

3 files changed

+18
-6
lines changed

ports/unix/coverage.c

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -527,7 +527,8 @@ STATIC mp_obj_t extra_coverage(void) {
527527
// ringbuf
528528
{
529529
byte buf[100];
530-
ringbuf_t ringbuf = {buf, sizeof(buf), 0, 0};
530+
ringbuf_t ringbuf;
531+
ringbuf_init(&ringbuf, &buf[0], sizeof(buf));
531532

532533
mp_printf(&mp_plat_print, "# ringbuf\n");
533534

py/ringbuf.c

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,19 +27,31 @@
2727

2828
#include "ringbuf.h"
2929

30+
bool ringbuf_init(ringbuf_t *r, uint8_t *buf, size_t capacity) {
31+
r->heap = false;
32+
r->buf = buf;
33+
r->size = capacity;
34+
r->iget = r->iput = 0;
35+
return r->buf != NULL;
36+
}
37+
3038
// Dynamic initialization. This should be accessible from a root pointer.
3139
// capacity is the number of bytes the ring buffer can hold. The actual
3240
// size of the buffer is one greater than that, due to how the buffer
3341
// handles empty and full statuses.
3442
bool ringbuf_alloc(ringbuf_t *r, size_t capacity, bool long_lived) {
43+
r->heap = true;
3544
r->buf = gc_alloc(capacity + 1, false, long_lived);
3645
r->size = capacity + 1;
3746
r->iget = r->iput = 0;
3847
return r->buf != NULL;
3948
}
4049

4150
void ringbuf_free(ringbuf_t *r) {
42-
gc_free(r->buf);
51+
if (r->heap) {
52+
gc_free(r->buf);
53+
}
54+
r->buf = (uint8_t *)NULL;
4355
r->size = 0;
4456
ringbuf_clear(r);
4557
}

py/ringbuf.h

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,14 +37,13 @@ typedef struct _ringbuf_t {
3737
uint32_t size;
3838
uint32_t iget;
3939
uint32_t iput;
40+
bool heap;
4041
} ringbuf_t;
4142

4243
// Note that the capacity of the buffer is N-1!
4344

44-
// Static initialization:
45-
// byte buf_array[N];
46-
// ringbuf_t buf = {buf_array, sizeof(buf_array)};
47-
45+
// For static initialization use ringbuf_init()
46+
bool ringbuf_init(ringbuf_t *r, uint8_t *buf, size_t capacity);
4847
bool ringbuf_alloc(ringbuf_t *r, size_t capacity, bool long_lived);
4948
void ringbuf_free(ringbuf_t *r);
5049
size_t ringbuf_capacity(ringbuf_t *r);

0 commit comments

Comments
 (0)
0