Making a StringBuffer in C, and questioning my sanity

23 coneonthefloor 9 7/15/2025, 10:48:34 AM briandouglas.ie ↗

Comments (9)

o11c · 2h ago
Hm, this implementation seems allergic to passing types by value, which eliminates half of the allocations. It also makes the mistake of being mutable-first, and provides some fundamentally-inefficient operations.

The main mistake that this makes in common with most string implementations make is to only provide a single type, rather than a series of mostly-compatible types that can be used generically in common contexts, but which differ in ways that sometimes matter. Ownership, lifetime, representation, etc.

remexre · 1h ago
How would you recommend doing that sort of "subtyping"? _Generic and macros?
amelius · 40m ago
I wonder how an LLM would rate this code.
ranger_danger · 2h ago
You might be interested in https://github.com/antirez/sds
fsckboy · 59m ago
neat, i like it, has some of the same ideas i've used in my string packages

but i did see a place to shave a byte in the sds data struct. The null terminator is a wasted field, that byte (or int) should be used to store the amount of free space left in the buffer (as a proxy for strlen). When there is no space left in the buffer, the free space value will be.... a very convenient 0 heheh

hey, OP said he wants to be a better C programmer!

ranger_danger · 40m ago
> The null terminator is a wasted field

I think that would break its "Compatible with normal C string functions" feature.

fsckboy · 32m ago
nooooo you don't understand. when the buffer is not full, the string will be zero terminated "in buffer" (which is how it works as is anyway). when the buffer is full, the "free count" at the end will do double duty, both as a zero count and a zero terminater
ranger_danger · 21m ago
But calling "normal C string functions" don't know about the "free count" byte, right? So it wouldn't be updated... unless I'm misunderstanding something.
improgrammer007 · 2h ago
I would rather focus on solving the main problem than reinvent the wheel. Just use C++ if perf is critical which gives you all these things for free. In this day and age the reasons for using C as your main language should be almost zero.