Discussion on: zbor - a CBOR en-/ decoder

r4gus profile image
David Sugar

Hi, thanks for you comment. I've thought about that too (at least for the u8 ArrayLists).

The one thing I want to avoid are dangling pointers, e.g. a byte (mt 2) u8 slice that references some section of a CBOR byte string which gets freed before the referencing DataItem gets freed. I'd argue that that's not an unlikely scenario.

To avoid this I need to allocate a unknown amount of memory at runtime, copy the bytes and reference the allocated memory section with my slice. If DataItem were a struct I could just add an allocator member with a default value (e.g. GPA) but DataItem is a tagged union, so I need to store the used Allocator with each union field that requires one. Because a tagged union feels quite 'natural' as type for DataItem, I would be reluctant to deviate from it.

So I need to store an Allocator for each field, allocate the memory myself, and copy the data from one place to another. A ArrayList offers that too.

I'm new to Zig and read through ziglearn.org and the Zig Language Reference but couldn't find anything that would hint me to a satisfying solution. If you know of a example or blog post that deals with something similar I'd be very grateful if you could comment with a link below.

Sry for the lengthy answer and thanks for this awesome platform :)

kristoff profile image
Loris Cro

One approach adopted by some stdlib APIs is to never store the allocator anywhere and ask the user to provide it to any function call that might need it. This way you also avoid paying the (admittedly small) price of storing mutliple copies of the same allocator interface.

Anyway I just wanted to point out some potentially non-obvious design choices that can make sense in Zig.

Thread Thread
r4gus profile image
David Sugar

I really like that idea. Falls apart as soon as one uses more than one allocator for a nested data structure, but should fit my use case. Thanks for the suggestion.