Skip to content

Commit b003888

Browse files
committed
Make __demangle() heap 10% more compact
1 parent 2ca491d commit b003888

File tree

1 file changed

+16
-8
lines changed

1 file changed

+16
-8
lines changed

libc/intrin/demangle.c

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -68,11 +68,11 @@ Copyright (c) 2024 Justine Tunney <[email protected]>");
6868
* and 100% lockless, and uses absolutely no writable static memory.
6969
* That makes it also great for kernel and embedded development.
7070
*
71-
* - We made it go 3x faster. It's almost as fast as libcxxabi now. The
71+
* - We made it go 2x faster. It's almost as fast as libcxxabi now. The
7272
* lightweight Dennis Ritchie style demangle_malloc() implementation
7373
* helped. What also helped is introducing stack_str and strlcpy().
7474
*
75-
* - We made it use 4x less memory. This came with the tradeoff of
75+
* - We made it use 3x less memory. This came with the tradeoff of
7676
* imposing limitations similar to embedded software. Rather than
7777
* using pointers, we use 16-bit indexes into a heap that can grow no
7878
* larger than 64kb. Please note that a buffer size of 20kb is more
@@ -383,7 +383,7 @@ static privileged returnspointerwithnoaliases returnsnonnull void *
383383
demangle_malloc(struct demangle_data *h, int a, int n)
384384
{
385385
uintptr_t ptr;
386-
int next, next2;
386+
int rem, next, next2;
387387
index_t *link, *link2;
388388
int b = sizeof(index_t);
389389

@@ -397,12 +397,20 @@ demangle_malloc(struct demangle_data *h, int a, int n)
397397
next = h->free;
398398
link = &h->free;
399399
while (next) {
400-
next2 = *(index_t *)(h->heap + next);
401400
link2 = (index_t *)(h->heap + next);
402-
if (!(next & (a - 1)) &&
403-
n <= ((index_t *)(h->heap + next))[-1]) {
404-
*link = next2;
405-
return (void *)(h->heap + next);
401+
next2 = *link2;
402+
if (!(next & (a - 1)) && (rem = link2[-1] - n) >= 0) {
403+
if (rem < (b << 1)) {
404+
*link = next2;
405+
} else {
406+
/* Split chunk. */
407+
link2[-1] = n;
408+
*link = next + n + b;
409+
link = (index_t *)(h->heap + next + n + b);
410+
link[-1] = rem - b;
411+
link[0] = next2;
412+
}
413+
return link2;
406414
}
407415
next = next2;
408416
link = link2;

0 commit comments

Comments
 (0)