sos is an implementation of Small-buffer Optimized String for C, written in ISO C99.
An sos string is able to store short strings inline within itself, and allocate additional memory as the string grows.
This reduces dynamic memory allocations especially when dealing with large amount of short strings.
The small buffer optimization is achieved with a union of short and long string representations.
The union is tagged with a special bit, to distinguish sos strings in short / long mode at runtime.
The idea is inspired by the std::string implementation in libc++.
The internal string buffer is always null-terminated like std::string, so sos can be used as C string at no cost.
On typical 64-bit platforms, sos takes 24 bytes, and is able to hold short strings with length up to 22 chars (excluding the null character).
The remaining byte tracks the length of the string, so length access is always O(1).
(Although technically, counting until NUL is also O(1) since there's a compile-time limit to the length of the short string, and it shouldn't be significantly slower. Some implementations choose to not use an extra byte for length tracking.)
Minimal example:
Sos s1, s2;
sos_init_from_cstr(&s1, "Hello!");
sos_init_with_cap(&s2, 16);
sos_pop(&s1);
sos_append_cstr(&s2, ", world");
sos_append(&s1, &s2);
sos_push(&s1, '!');
printf("%s\n", sos_cstr(&s1));
Sos s3;
sos_init_format(&s3, "The answer is %d", 42);
sos_finish(&s3);
sos_finish(&s2);
sos_finish(&s1);See sos.h for more.
sos employs explicit lifetime/buffer management, to give the programmer granular control.
- Configurable small buffer size
- Some missing checks for max length
- Test coverage