MCPcopy Create free account
hub / github.com/DeusData/codebase-memory-mcp / pb_flush_leaf

Function pb_flush_leaf

internal/cbm/sqlite_writer.c:588–640  ·  view source on GitHub ↗

Flush current leaf page to file

Source from the content-addressed store, hash-verified

586
587// Flush current leaf page to file
588static void pb_flush_leaf(PageBuilder *pb) {
589 if (pb->cell_count == 0) {
590 return;
591 }
592
593 int hdr = pb->page1_offset;
594 // Write leaf page header
595 pb->page[hdr + 0] = pb->is_index ? BTREE_LEAF_INDEX : BTREE_LEAF_TABLE; // leaf flag
596 put_u16(pb->page + hdr + HDR_FREEBLOCK_OFF, 0); // first freeblock
597 put_u16(pb->page + hdr + HDR_CELLCOUNT_OFF, (uint16_t)pb->cell_count);
598 put_u16(pb->page + hdr + HDR_CONTENT_OFF, (uint16_t)pb->content_offset);
599 pb->page[hdr + HDR_FRAGBYTES_OFF] = 0; // fragmented free bytes
600
601 // Write page to file. Skip the pending byte page (SQLite reserved).
602 pb->next_page = cbm_skip_pending_byte(pb->next_page);
603 uint32_t page_num = pb->next_page;
604 long offset = (long)(page_num - SKIP_ONE) * CBM_PAGE_SIZE;
605 (void)fseek(pb->fp, offset, SEEK_SET);
606 (void)fwrite(pb->page, SKIP_ONE, CBM_PAGE_SIZE, pb->fp);
607
608 // Record this leaf for interior page building
609 if (pb->leaf_count >= pb->leaf_cap) {
610 int old_cap = pb->leaf_cap;
611 pb->leaf_cap = old_cap == 0 ? INITIAL_LEAF_CAP : old_cap * GROWTH_FACTOR;
612 void *tmp = realloc(pb->leaves, (size_t)pb->leaf_cap * sizeof(PageRef));
613 if (!tmp) {
614 /* Leave a CONSISTENT empty state: leaf_count stale at >=1 with a
615 * NULL leaves array walked pb_finalize_* straight into
616 * leaves[0] (null deref, clang-analyzer traced it) whenever the
617 * final cell block was already flushed. Empty state routes every
618 * finalize path to its existing root=0 failure return. */
619 free(pb->leaves);
620 pb->leaves = NULL;
621 pb->leaf_count = 0;
622 pb->leaf_cap = 0;
623 return;
624 }
625 pb->leaves = (PageRef *)tmp;
626 /* Zero-init new slots */
627 memset(&pb->leaves[old_cap], 0, ((size_t)pb->leaf_cap - (size_t)old_cap) * sizeof(PageRef));
628 }
629 pb->leaves[pb->leaf_count].page_num = page_num;
630 // max_key is set by caller before flush
631 pb->leaf_count++;
632
633 // Reset for next page
634 pb->next_page++;
635 pb->cell_count = 0;
636 pb->content_offset = CBM_PAGE_SIZE;
637 pb->page1_offset = 0; // only page 1 has the 100-byte header
638 pb->ptr_offset = BTREE_HEADER_SIZE; // standard B-tree header size for non-page-1
639 memset(pb->page, 0, CBM_PAGE_SIZE);
640}
641
642// Check if a cell of given size fits in the current page
643static bool pb_cell_fits(PageBuilder *pb, int cell_len) {

Callers 4

pb_place_table_cellFunction · 0.85
pb_finalize_tableFunction · 0.85
pb_promote_and_flushFunction · 0.85
write_index_btreeFunction · 0.85

Calls 3

put_u16Function · 0.85
cbm_skip_pending_byteFunction · 0.85
fwriteFunction · 0.85

Tested by

no test coverage detected