Build master records, write page 1 B-tree + file header. */
| 1916 | |
| 1917 | /* Build master records, write page 1 B-tree + file header. */ |
| 1918 | static int write_master_page1(FILE *fp, MasterEntry *master, int master_count, uint32_t next_page) { |
| 1919 | const uint8_t **master_records = (const uint8_t **)malloc(master_count * sizeof(uint8_t *)); |
| 1920 | int *master_lens = (int *)malloc(master_count * sizeof(int)); |
| 1921 | int64_t *master_rowids = (int64_t *)malloc(master_count * sizeof(int64_t)); |
| 1922 | for (int i = 0; i < master_count; i++) { |
| 1923 | master_rowids[i] = i + SKIP_ONE; |
| 1924 | master_records[i] = build_master_record(&master[i], &master_lens[i]); |
| 1925 | } |
| 1926 | |
| 1927 | uint8_t page1[CBM_PAGE_SIZE]; |
| 1928 | memset(page1, 0, CBM_PAGE_SIZE); |
| 1929 | int hdr = SQLITE_HEADER_SIZE; |
| 1930 | page1[hdr] = BTREE_LEAF_TABLE; |
| 1931 | int content_off = CBM_PAGE_SIZE; |
| 1932 | int ptr_off = hdr + BTREE_HEADER_SIZE; |
| 1933 | int mcell_count = 0; |
| 1934 | |
| 1935 | for (int i = 0; i < master_count; i++) { |
| 1936 | int cell_len = 0; |
| 1937 | uint8_t *cell = |
| 1938 | build_table_cell(master_rowids[i], master_records[i], master_lens[i], &cell_len); |
| 1939 | int available = content_off - ptr_off - CELL_PTR_SIZE; |
| 1940 | if (!cell || cell_len > available) { |
| 1941 | free(cell); |
| 1942 | for (int j = 0; j < master_count; j++) { |
| 1943 | free((void *)master_records[j]); |
| 1944 | } |
| 1945 | free(master_records); |
| 1946 | free(master_lens); |
| 1947 | free(master_rowids); |
| 1948 | return ERR_MASTER_OVERFLOW; |
| 1949 | } |
| 1950 | content_off -= cell_len; |
| 1951 | memcpy(page1 + content_off, cell, cell_len); |
| 1952 | put_u16(page1 + ptr_off, (uint16_t)content_off); |
| 1953 | ptr_off += CELL_PTR_SIZE; |
| 1954 | mcell_count++; |
| 1955 | free(cell); |
| 1956 | } |
| 1957 | |
| 1958 | put_u16(page1 + hdr + HDR_FREEBLOCK_OFF, 0); |
| 1959 | put_u16(page1 + hdr + HDR_CELLCOUNT_OFF, (uint16_t)mcell_count); |
| 1960 | put_u16(page1 + hdr + HDR_CONTENT_OFF, (uint16_t)content_off); |
| 1961 | page1[hdr + HDR_FRAGBYTES_OFF] = 0; |
| 1962 | |
| 1963 | write_sqlite_file_header(page1, next_page - SKIP_ONE); |
| 1964 | |
| 1965 | (void)fseek(fp, 0, SEEK_SET); |
| 1966 | (void)fwrite(page1, SKIP_ONE, CBM_PAGE_SIZE, fp); |
| 1967 | |
| 1968 | for (int i = 0; i < master_count; i++) { |
| 1969 | free((void *)master_records[i]); |
| 1970 | } |
| 1971 | free(master_records); |
| 1972 | free(master_lens); |
| 1973 | free(master_rowids); |
| 1974 | return 0; |
| 1975 | } |
no test coverage detected