by ATsch · 6y ago · 0 comments
typedef struct {
size_t len;
uint8_t data[];
} ByteBuf;
Then, allocation becomes ByteBuf *b = malloc(sizeof(*b) + sizeof(uint8_t) * array_size);
b->len = array_size;
and data is no longer a pointer.Thing is, you rarely want to share just a buffer anyway. You probably have additional state, locks, etc. So what I do is embed my ByteBuf directly into another structure, which then owns it completely:
typedef struct {
...
ByteBuf mybuffer;
...
} SomeThing;
So we end up with the same amount of pointers (1), but with some unique advantages.Makes it easier to take subranges out of it
typedef struct {uint8_t *data, *dataend}
if I'm not mistaken :)With the length you would need to do data += k; length -= k
Especially if you want to use it as safe iterator, you can do data++ in a loop
A possible tiny advantage for this layout is that a pointer to this struct can be used as a pointer to a pointer-to-bytes, without having to adjust it. Although i'm not sure that's not undefined behaviour.
https://github.com/python/cpython/blob/master/Include/object...