r/C_Programming • • 11d ago

Tiny strings

https://napcakes.nekoweb.org/posts/tiny-strings/
31 Upvotes

13 comments sorted by

View all comments

7

u/kevkevverson 11d ago

You can use Folly’s trick to fit one more character in the small string. Invert the flag bit so zero = small string, and store it in the last byte, along with the small length stored as 15-len. Then, the full 16 bytes can be used for a small string since the final byte simultaneously acts as the type/length byte AND the null terminator when the string length is 15.

2

u/8d8n4mbo28026ulk 11d ago

The big strings aren't NUL-terminated, so there's no point in doing that for the small ones. Folly devs went to great (crazy) lengths to avoid '\0' too, unsuccessfully. Their hands were tied by the standard, I don't have such constraints.

1

u/Iggyhopper 11d ago

I have a data type which uses 1 byte for the capacity (not length) which is split into bit flags for further separation.

Since its the first byte anyway, it can be used in length (erm, capacity) comparisons without indirection and it's pretty slick.

I'll have to do a writeup at one point. Im still debating the details of how to fit length in the struct.