Build master records, write page 1 B-tree + file header. */
| 1839 | |
| 1840 | /* Build master records, write page 1 B-tree + file header. */ |
| 1841 | static int write_master_page1(FILE *fp, MasterEntry *master, int master_count, uint32_t next_page) { |
| 1842 | const uint8_t **master_records = (const uint8_t **)malloc(master_count * sizeof(uint8_t *)); |
| 1843 | int *master_lens = (int *)malloc(master_count * sizeof(int)); |
| 1844 | int64_t *master_rowids = (int64_t *)malloc(master_count * sizeof(int64_t)); |
| 1845 | for (int i = 0; i < master_count; i++) { |
| 1846 | master_rowids[i] = i + SKIP_ONE; |
| 1847 | master_records[i] = build_master_record(&master[i], &master_lens[i]); |
| 1848 | } |
| 1849 | |
| 1850 | uint8_t page1[CBM_PAGE_SIZE]; |
| 1851 | memset(page1, 0, CBM_PAGE_SIZE); |
| 1852 | int hdr = SQLITE_HEADER_SIZE; |
| 1853 | page1[hdr] = BTREE_LEAF_TABLE; |
| 1854 | int content_off = CBM_PAGE_SIZE; |
| 1855 | int ptr_off = hdr + BTREE_HEADER_SIZE; |
| 1856 | int mcell_count = 0; |
| 1857 | |
| 1858 | for (int i = 0; i < master_count; i++) { |
| 1859 | int cell_len = 0; |
| 1860 | uint8_t *cell = |
| 1861 | build_table_cell(master_rowids[i], master_records[i], master_lens[i], &cell_len); |
| 1862 | int available = content_off - ptr_off - CELL_PTR_SIZE; |
| 1863 | if (!cell || cell_len > available) { |
| 1864 | free(cell); |
| 1865 | for (int j = 0; j < master_count; j++) { |
| 1866 | free((void *)master_records[j]); |
| 1867 | } |
| 1868 | free(master_records); |
| 1869 | free(master_lens); |
| 1870 | free(master_rowids); |
| 1871 | return ERR_MASTER_OVERFLOW; |
| 1872 | } |
| 1873 | content_off -= cell_len; |
| 1874 | memcpy(page1 + content_off, cell, cell_len); |
| 1875 | put_u16(page1 + ptr_off, (uint16_t)content_off); |
| 1876 | ptr_off += CELL_PTR_SIZE; |
| 1877 | mcell_count++; |
| 1878 | free(cell); |
| 1879 | } |
| 1880 | |
| 1881 | put_u16(page1 + hdr + HDR_FREEBLOCK_OFF, 0); |
| 1882 | put_u16(page1 + hdr + HDR_CELLCOUNT_OFF, (uint16_t)mcell_count); |
| 1883 | put_u16(page1 + hdr + HDR_CONTENT_OFF, (uint16_t)content_off); |
| 1884 | page1[hdr + HDR_FRAGBYTES_OFF] = 0; |
| 1885 | |
| 1886 | write_sqlite_file_header(page1, next_page - SKIP_ONE); |
| 1887 | |
| 1888 | (void)fseek(fp, 0, SEEK_SET); |
| 1889 | (void)fwrite(page1, SKIP_ONE, CBM_PAGE_SIZE, fp); |
| 1890 | |
| 1891 | for (int i = 0; i < master_count; i++) { |
| 1892 | free((void *)master_records[i]); |
| 1893 | } |
| 1894 | free(master_records); |
| 1895 | free(master_lens); |
| 1896 | free(master_rowids); |
| 1897 | return 0; |
| 1898 | } |
no test coverage detected