Build master records, write page 1 B-tree + file header. */
| 1974 | |
| 1975 | /* Build master records, write page 1 B-tree + file header. */ |
| 1976 | static 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 | } |
no test coverage detected