ES version is available. Content is displayed in original English for accuracy.
Advertisement
Advertisement
⚡ Community Insights
Discussion Sentiment
87% Positive
Analyzed from 828 words in the discussion.
Trending Topics
#array#struct#capacity#type#len#same#using#need#int#clever

Discussion (21 Comments)Read Original on HackerNews
The 'public handle' is a pointer to the array elements so it has the same semantics as a regular C array, the meta-data (capacity and length) are stored directly in front of the array items. Growing the array has the same behaviour as realloc (e.g. you may get a new pointer back).
With some clever use of _Generic you could even build specialised functions for that type and get pretty good type checking
I can't make any sense of the aversion to a struct. Use a struct. You don't have to give its type a name, if that's the motivation here.
With a struct we would need one struct for each element type - at least prior to C23 which provides a better approach where we can declare the same struct multiple times in a translation unit.
We can use `Array(int)` in multiple places in the same TU - but in C11 or earlier, this is an error.But since it’s storing a void pointer any way, they wouldn’t need separate names right? You could use one struct everywhere regardless of the type of the items
Which IMO is a better idea than using an array here because the fields can be properly named and typed to prevent accidental misuse
https://github.com/gritzko/libabc/blob/main/S.md
ABC uses s[2] for slices, g[3] for gauges, b[4] for (ring) buffers. Also containers on top of those (heaps, hash sets, etc etc)
Brilliant insight. This is the first time I've seen this observation in over 3 decades of working with C.
stdc_bit_ceil(len) gets the smallest power of 2 not less than len, which is our capacity. This is usually implemented with a clz instruction.
stdc_has_single_bit(len) determines if it's a power of 2 - typically implemented with a popcount instruction (popcount(len)==1).
The approach isn't used in older (90s and earlier) texts because hardware support for popcount/clz wasn't commonplace and the cost to do it in software wasn't worth it, but it is mentioned in some texts.
You can use the trick if the array can shrink as long as you always shrink it when length goes below the next power of 2 not greater than len (which may make use of stdc_bit_floor).
[1]:https://cl-pdx.com/static/techlists.pdf
I know about XOR-linked lists and a few other tricks for very efficient memory usage in embedded systems, but it's my first time seeing implicit allocation lengths.
However, using an 2-element array to avoid using a struct is silly.