Buffet – An All-inclusive Buffer for C
I&#x27;m going to be skeptical on this. Shoving refcounting + SBO + non owning views into a single type is not a smart decision.<p>Before going into why I think so, some general implementation things to look into:<p><pre><code>  * Power of 2 exponent is not optimal. You will never be able to reallocate into the same stretch of memory that the arrays have previously occupied, as the sum of their sizes will always be smaller than the next one. C++ stdlibs have switched to values closer to 1.5.
  * Extra care should be taken when using memcpy. It&#x27;s possible to copy overlapping buffers which is not allowed. using memmove instead is a simple solution. Also note the case when appending the Buffet structure itself to its array.
  * You can&#x27;t yet count on all machines having ctlz&#x2F;lzcnt instruction. There have been quite a few cases of this instruction crashing software because no fallback was provided lately.
  * If someone asks for bft_new(bft, 0x1000) you&#x27;ll end up allocating 0x2000 bytes even though an exact size was specified. IMO scaling should be done only on appends.
  * If you force the structure alignment to 16 you might as well say that your type is 24 bytes in size, because you&#x27;ll very likely be adding tons of padding to structures that include your buffer.
  * Seems like quite a few checks for malloc failure are missing + proper reporting for that.
</code></pre>
Now why I think this is a terrible idea:<p><pre><code>  * The model of your reference counting is a minefield and will 100% lead to problems when used in real world.
    - Free&#x27;ing OWN before all refs = leak (although this could be fixed by giving OWN refcount of 1 instead of 0)
    - Reference count is non-atomic = potential corruption
    - bft_view() has differing behaviors of output depending on what state it&#x27;s in = hard to reproduce bugs.
  * You won&#x27;t be fast just because you fit into 16 bytes.
    - Your code has branches on every single hot path that is virtually free on other implementations. There isn&#x27;t really even anything you can optimize as all the branches essentially have equal weight, so you&#x27;ll be having mispredictions by design.
    - You have multiple levels of indirection for data pointers so you&#x27;ll be stalling the pipeline on cache misses and dependent loads as well as bad speculation.
  * SBO - OK, refcount - OK, but why add non-owning view into the equation? What&#x27;s wrong with good old pointer+size or pointer start+pointer end for that. There already are enough footguns to worry about with 3 states.</code></pre>