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

Function write_master_page1

internal/cbm/sqlite_writer.c:1976–2033  ·  view source on GitHub ↗

Build master records, write page 1 B-tree + file header. */

Source from the content-addressed store, hash-verified

1974
1975/* Build master records, write page 1 B-tree + file header. */
1976static int write_master_page1(FILE *fp, MasterEntry *master, int master_count, uint32_t next_page) {
1977 const uint8_t **master_records = (const uint8_t **)malloc(master_count * sizeof(uint8_t *));
1978 int *master_lens = (int *)malloc(master_count * sizeof(int));
1979 int64_t *master_rowids = (int64_t *)malloc(master_count * sizeof(int64_t));
1980 for (int i = 0; i < master_count; i++) {
1981 master_rowids[i] = i + SKIP_ONE;
1982 master_records[i] = build_master_record(&master[i], &master_lens[i]);
1983 }
1984
1985 uint8_t page1[CBM_PAGE_SIZE];
1986 memset(page1, 0, CBM_PAGE_SIZE);
1987 int hdr = SQLITE_HEADER_SIZE;
1988 page1[hdr] = BTREE_LEAF_TABLE;
1989 int content_off = CBM_PAGE_SIZE;
1990 int ptr_off = hdr + BTREE_HEADER_SIZE;
1991 int mcell_count = 0;
1992
1993 for (int i = 0; i < master_count; i++) {
1994 int cell_len = 0;
1995 uint8_t *cell =
1996 build_table_cell(master_rowids[i], master_records[i], master_lens[i], &cell_len);
1997 int available = content_off - ptr_off - CELL_PTR_SIZE;
1998 if (!cell || cell_len > available) {
1999 free(cell);
2000 for (int j = 0; j < master_count; j++) {
2001 free((void *)master_records[j]);
2002 }
2003 free(master_records);
2004 free(master_lens);
2005 free(master_rowids);
2006 return ERR_MASTER_OVERFLOW;
2007 }
2008 content_off -= cell_len;
2009 memcpy(page1 + content_off, cell, cell_len);
2010 put_u16(page1 + ptr_off, (uint16_t)content_off);
2011 ptr_off += CELL_PTR_SIZE;
2012 mcell_count++;
2013 free(cell);
2014 }
2015
2016 put_u16(page1 + hdr + HDR_FREEBLOCK_OFF, 0);
2017 put_u16(page1 + hdr + HDR_CELLCOUNT_OFF, (uint16_t)mcell_count);
2018 put_u16(page1 + hdr + HDR_CONTENT_OFF, (uint16_t)content_off);
2019 page1[hdr + HDR_FRAGBYTES_OFF] = 0;
2020
2021 write_sqlite_file_header(page1, next_page - SKIP_ONE);
2022
2023 (void)fseek(fp, 0, SEEK_SET);
2024 (void)fwrite(page1, SKIP_ONE, CBM_PAGE_SIZE, fp);
2025
2026 for (int i = 0; i < master_count; i++) {
2027 free((void *)master_records[i]);
2028 }
2029 free(master_records);
2030 free(master_lens);
2031 free(master_rowids);
2032 return 0;
2033}

Callers 1

write_db_after_nodesFunction · 0.85

Calls 5

build_master_recordFunction · 0.85
build_table_cellFunction · 0.85
put_u16Function · 0.85
write_sqlite_file_headerFunction · 0.85
fwriteFunction · 0.85

Tested by

no test coverage detected