| 545 | } |
| 546 | |
| 547 | void cbm_result_compact(CBMFileResult *result) { |
| 548 | if (!result || result->arena.nblocks == 0 || |
| 549 | !cbm_py_namespace_facts_valid(&result->py_namespace)) { |
| 550 | return; |
| 551 | } |
| 552 | cr_ctx_t c; |
| 553 | memset(&c, 0, sizeof(c)); |
| 554 | |
| 555 | /* Work on a copy of the header: every pointer rewrite lands here and the |
| 556 | * caller's result is replaced only once everything succeeded. */ |
| 557 | CBMFileResult tmp = *result; |
| 558 | |
| 559 | c.phase = CR_COUNT; |
| 560 | cr_walk(&c, &tmp); |
| 561 | /* Bound intern-table/replay sizing before the existing power-of-two step. */ |
| 562 | if (c.failed || c.refs > (SIZE_MAX / (sizeof(cr_slot_t) * 8) - CR_MIN_TABLE)) |
| 563 | return; |
| 564 | |
| 565 | c.cap = cr_pow2_at_least(c.refs * CR_TABLE_LOAD + CR_MIN_TABLE); |
| 566 | if (c.cap > UINT32_MAX) /* replay entries store slot indexes in uint32_t */ |
| 567 | return; |
| 568 | if (!cr_scratch_get(&c)) { |
| 569 | return; |
| 570 | } |
| 571 | |
| 572 | c.phase = CR_MEASURE; |
| 573 | cr_walk(&c, &tmp); |
| 574 | if (c.failed) { |
| 575 | cr_scratch_put(&c); |
| 576 | return; |
| 577 | } |
| 578 | for (size_t i = 0; i < c.cap; i++) { |
| 579 | c.slots[i].dst = NULL; /* MEASURE used dst as a booked marker */ |
| 580 | } |
| 581 | |
| 582 | CBMArena fresh; |
| 583 | cbm_arena_init_exact(&fresh, c.bytes); |
| 584 | if (fresh.nblocks == 0) { |
| 585 | cr_scratch_put(&c); |
| 586 | return; |
| 587 | } |
| 588 | |
| 589 | c.phase = CR_COPY; |
| 590 | c.dst = &fresh; |
| 591 | cr_walk(&c, &tmp); |
| 592 | cr_scratch_put(&c); |
| 593 | if (c.failed) { |
| 594 | cbm_arena_destroy(&fresh); |
| 595 | return; |
| 596 | } |
| 597 | |
| 598 | /* Exact-count arrays: nothing may append into the dead headroom. */ |
| 599 | tmp.defs.cap = tmp.defs.count; |
| 600 | tmp.calls.cap = tmp.calls.count; |
| 601 | tmp.imports.cap = tmp.imports.count; |
| 602 | tmp.py_namespace.cap = tmp.py_namespace.count; |
| 603 | tmp.usages.cap = tmp.usages.count; |
| 604 | tmp.throws.cap = tmp.throws.count; |