FFstrbuf: optimises ffStrbufEnsureFreeNoCheck

This commit is contained in:
李通洲
2026-07-07 19:15:36 +08:00
parent 11d77e0d09
commit 6358bd7844
2 changed files with 33 additions and 6 deletions
+7 -6
View File
@@ -64,13 +64,14 @@ FFstrbuf ffStrbufCreateF(const char* format, ...) {
}
void ffStrbufEnsureFreeNoCheck(FFstrbuf* strbuf, uint32_t free) {
uint32_t allocate = strbuf->allocated;
if (allocate < FASTFETCH_STRBUF_DEFAULT_ALLOC) {
uint32_t allocate = strbuf->length + free;
if (allocate < FASTFETCH_STRBUF_DEFAULT_ALLOC) { // `<` for null terminator
allocate = FASTFETCH_STRBUF_DEFAULT_ALLOC;
}
while ((strbuf->length + free + 1) > allocate) { // + 1 for the null byte
allocate *= 2;
} else {
// Round up to the next power of 2.
// If the value is already a power of 2, it will be rounded up to the next power of 2.
assert(allocate < (UINT32_MAX >> 1));
allocate = 1U << (32 - __builtin_clz(allocate));
}
if (strbuf->allocated == 0) {
+26
View File
@@ -1139,6 +1139,32 @@ int main(void) {
VERIFY(strbuf.allocated == 0);
ffStrbufDestroy(&strbuf);
#if FASTFETCH_STRBUF_DEFAULT_ALLOC == 32
ffStrbufEnsureFreeNoCheck(&strbuf, 1);
VERIFY(strbuf.allocated == 32);
ffStrbufDestroy(&strbuf);
ffStrbufEnsureFreeNoCheck(&strbuf, 31);
VERIFY(strbuf.allocated == 32);
ffStrbufDestroy(&strbuf);
ffStrbufEnsureFreeNoCheck(&strbuf, 32);
VERIFY(strbuf.allocated == 64);
ffStrbufDestroy(&strbuf);
ffStrbufEnsureFreeNoCheck(&strbuf, 33);
VERIFY(strbuf.allocated == 64);
ffStrbufDestroy(&strbuf);
ffStrbufEnsureFreeNoCheck(&strbuf, 63);
VERIFY(strbuf.allocated == 64);
ffStrbufDestroy(&strbuf);
ffStrbufEnsureFreeNoCheck(&strbuf, 64);
VERIFY(strbuf.allocated == 128);
ffStrbufDestroy(&strbuf);
#endif
// Success
puts("\e[32mAll tests passed!" FASTFETCH_TEXT_MODIFIER_RESET);
}