File: gsd.c

package info (click to toggle)
python-gsd 2.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 904 kB
  • sloc: python: 2,742; ansic: 1,881; makefile: 157; cpp: 109
file content (2468 lines) | stat: -rw-r--r-- 69,226 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
// Copyright (c) 2016-2020 The Regents of the University of Michigan
// This file is part of the General Simulation Data (GSD) project, released under the BSD 2-Clause
// License.

#include <sys/stat.h>
#ifdef _WIN32

#pragma warning(push)
#pragma warning(disable : 4996)

#define GSD_USE_MMAP 0
#include <io.h>

#else // linux / mac

#define _XOPEN_SOURCE 500
#include <sys/mman.h>
#include <unistd.h>
#define GSD_USE_MMAP 1

#endif

#ifdef __APPLE__
#include <limits.h>
#endif

#include <errno.h>
#include <fcntl.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>

#include "gsd.h"

/** @file gsd.c
    @brief Implements the GSD C API
*/

/// Magic value identifying a GSD file
const uint64_t GSD_MAGIC_ID = 0x65DF65DF65DF65DF;

/// Initial index size
enum
    {
    GSD_INITIAL_INDEX_SIZE = 128
    };

/// Initial namelist size
enum
    {
    GSD_INITIAL_NAME_BUFFER_SIZE = 1024
    };

/// Size of initial frame index
enum
    {
    GSD_INITIAL_FRAME_INDEX_SIZE = 16
    };

/// Size of write buffer
enum
    {
    GSD_WRITE_BUFFER_SIZE = 16 * 1024 * 1024
    };

/// Size of copy buffer
enum
    {
    GSD_COPY_BUFFER_SIZE = 128 * 1024
    };

/// Size of hash map
enum
    {
    GSD_NAME_MAP_SIZE = 57557
    };

/// Current GSD file specification
enum
    {
    GSD_CURRENT_FILE_VERSION = 2
    };

// define windows wrapper functions
#ifdef _WIN32
#define lseek _lseeki64
#define open _open
#define ftruncate _chsize
#define fsync _commit
typedef int64_t ssize_t;

int S_IRUSR = _S_IREAD;
int S_IWUSR = _S_IWRITE;
int S_IRGRP = _S_IREAD;
int S_IWGRP = _S_IWRITE;

inline ssize_t pread(int fd, void* buf, size_t count, int64_t offset)
    {
    // Note: _read only accepts unsigned int values
    if (count > UINT_MAX)
        return GSD_ERROR_IO;

    int64_t oldpos = _telli64(fd);
    _lseeki64(fd, offset, SEEK_SET);
    ssize_t result = _read(fd, buf, (unsigned int)count);
    _lseeki64(fd, oldpos, SEEK_SET);
    return result;
    }

inline ssize_t pwrite(int fd, const void* buf, size_t count, int64_t offset)
    {
    // Note: _write only accepts unsigned int values
    if (count > UINT_MAX)
        return GSD_ERROR_IO;

    int64_t oldpos = _telli64(fd);
    _lseeki64(fd, offset, SEEK_SET);
    ssize_t result = _write(fd, buf, (unsigned int)count);
    _lseeki64(fd, oldpos, SEEK_SET);
    return result;
    }

#endif

/** Zero memory

    @param d pointer to memory region
    @param size_to_zero size of the area to zero in bytes
*/
inline static void gsd_util_zero_memory(void* d, size_t size_to_zero)
    {
    memset(d, 0, size_to_zero);
    }

/** @internal
    @brief Write large data buffer to file

    The system call pwrite() fails to write very large data buffers. This method calls pwrite() as
    many times as necessary to completely write a large buffer.

    @param fd File descriptor.
    @param buf Data buffer.
    @param count Number of bytes to write.
    @param offset Location in the file to start writing.

    @returns The total number of bytes written or a negative value on error.
*/
inline static ssize_t gsd_io_pwrite_retry(int fd, const void* buf, size_t count, int64_t offset)
    {
    size_t total_bytes_written = 0;
    const char* ptr = (char*)buf;

    // perform multiple pwrite calls to complete a large write successfully
    while (total_bytes_written < count)
        {
        size_t to_write = count - total_bytes_written;
#if defined(_WIN32) || defined(__APPLE__)
        // win32 and apple raise an error for writes greater than INT_MAX
        if (to_write > INT_MAX / 2)
            to_write = INT_MAX / 2;
#endif

        errno = 0;
        ssize_t bytes_written
            = pwrite(fd, ptr + total_bytes_written, to_write, offset + total_bytes_written);
        if (bytes_written == -1 || (bytes_written == 0 && errno != 0))
            {
            return GSD_ERROR_IO;
            }

        total_bytes_written += bytes_written;
        }

    return total_bytes_written;
    }

/** @internal
    @brief Read large data buffer to file

    The system call pread() fails to read very large data buffers. This method calls pread() as many
    times as necessary to completely read a large buffer.

    @param fd File descriptor.
    @param buf Data buffer.
    @param count Number of bytes to read.
    @param offset Location in the file to start reading.

    @returns The total number of bytes read or a negative value on error.
*/
inline static ssize_t gsd_io_pread_retry(int fd, void* buf, size_t count, int64_t offset)
    {
    size_t total_bytes_read = 0;
    char* ptr = (char*)buf;

    // perform multiple pread calls to complete a large write successfully
    while (total_bytes_read < count)
        {
        size_t to_read = count - total_bytes_read;
#if defined(_WIN32) || defined(__APPLE__)
        // win32 and apple raise errors for reads greater than INT_MAX
        if (to_read > INT_MAX / 2)
            to_read = INT_MAX / 2;
#endif

        errno = 0;
        ssize_t bytes_read = pread(fd, ptr + total_bytes_read, to_read, offset + total_bytes_read);
        if (bytes_read == -1 || (bytes_read == 0 && errno != 0))
            {
            return GSD_ERROR_IO;
            }

        total_bytes_read += bytes_read;

        // handle end of file
        if (bytes_read == 0)
            {
            return total_bytes_read;
            }
        }

    return total_bytes_read;
    }

/** @internal
    @brief Allocate a name/id map

    @param map Map to allocate.
    @param size Number of entries in the map.

    @returns GSD_SUCCESS on success, GSD_* error codes on error.
*/
inline static int gsd_name_id_map_allocate(struct gsd_name_id_map* map, size_t size)
    {
    if (map == NULL || map->v || size == 0 || map->size != 0)
        {
        return GSD_ERROR_INVALID_ARGUMENT;
        }

    map->v = calloc(size, sizeof(struct gsd_name_id_pair));
    if (map->v == NULL)
        {
        return GSD_ERROR_MEMORY_ALLOCATION_FAILED;
        }

    map->size = size;

    return GSD_SUCCESS;
    }

/** @internal
    @brief Free a name/id map

    @param map Map to free.

    @returns GSD_SUCCESS on success, GSD_* error codes on error.
*/
inline static int gsd_name_id_map_free(struct gsd_name_id_map* map)
    {
    if (map == NULL || map->v == NULL || map->size == 0)
        {
        return GSD_ERROR_INVALID_ARGUMENT;
        }

    // free all of the linked lists
    size_t i;
    for (i = 0; i < map->size; i++)
        {
        free(map->v[i].name);

        struct gsd_name_id_pair* cur = map->v[i].next;
        while (cur != NULL)
            {
            struct gsd_name_id_pair* prev = cur;
            cur = cur->next;
            free(prev->name);
            free(prev);
            }
        }

    // free the main map
    free(map->v);

    map->v = 0;
    map->size = 0;

    return GSD_SUCCESS;
    }

/** @internal
    @brief Hash a string

    @param str String to hash

    @returns Hashed value of the string.
*/
inline static unsigned long gsd_hash_str(const unsigned char* str)
    {
    unsigned long hash = 5381; // NOLINT
    int c;

    while ((c = *str++))
        {
        hash = ((hash << 5) + hash) + c; /* hash * 33 + c NOLINT */
        }

    return hash;
    }

/** @internal
    @brief Insert a string into a name/id map

    @param map Map to insert into.
    @param str String to insert.
    @param id ID to associate with the string.

    @returns GSD_SUCCESS on success, GSD_* error codes on error.
*/
inline static int gsd_name_id_map_insert(struct gsd_name_id_map* map, const char* str, uint16_t id)
    {
    if (map == NULL || map->v == NULL || map->size == 0)
        {
        return GSD_ERROR_INVALID_ARGUMENT;
        }

    size_t hash = gsd_hash_str((const unsigned char*)str) % map->size;

    // base case: no conflict
    if (map->v[hash].name == NULL)
        {
        map->v[hash].name = calloc(strlen(str) + 1, sizeof(char));
        if (map->v[hash].name == NULL)
            {
            return GSD_ERROR_MEMORY_ALLOCATION_FAILED;
            }
        memcpy(map->v[hash].name, str, strlen(str) + 1);
        map->v[hash].id = id;
        map->v[hash].next = NULL;
        }
    else
        {
        // go to the end of the conflict list
        struct gsd_name_id_pair* insert_point = map->v + hash;

        while (insert_point->next != NULL)
            {
            insert_point = insert_point->next;
            }

        // allocate and insert a new entry
        insert_point->next = malloc(sizeof(struct gsd_name_id_pair));
        if (insert_point->next == NULL)
            {
            return GSD_ERROR_MEMORY_ALLOCATION_FAILED;
            }

        insert_point->next->name = calloc(strlen(str) + 1, sizeof(char));
        if (insert_point->next->name == NULL)
            {
            return GSD_ERROR_MEMORY_ALLOCATION_FAILED;
            }
        memcpy(insert_point->next->name, str, strlen(str) + 1);
        insert_point->next->id = id;
        insert_point->next->next = NULL;
        }

    return GSD_SUCCESS;
    }

/** @internal
    @brief Find an ID in a name/id mapping

    @param map Map to search.
    @param str String to search.

    @returns The ID if found, or UINT16_MAX if not found.
*/
inline static uint16_t gsd_name_id_map_find(struct gsd_name_id_map* map, const char* str)
    {
    if (map == NULL || map->v == NULL || map->size == 0)
        {
        return UINT16_MAX;
        }

    size_t hash = gsd_hash_str((const unsigned char*)str) % map->size;

    struct gsd_name_id_pair* cur = map->v + hash;

    while (cur != NULL)
        {
        if (cur->name == NULL)
            {
            // not found
            return UINT16_MAX;
            }

        if (strcmp(str, cur->name) == 0)
            {
            // found
            return cur->id;
            }

        // keep looking
        cur = cur->next;
        }

    // not found in any conflict
    return UINT16_MAX;
    }

/** @internal
    @brief Utility function to validate index entry
    @param handle handle to the open gsd file
    @param idx index of entry to validate

    @returns 1 if the entry is valid, 0 if it is not
*/
inline static int gsd_is_entry_valid(struct gsd_handle* handle, size_t idx)
    {
    const struct gsd_index_entry entry = handle->file_index.data[idx];

    // check for valid type
    if (gsd_sizeof_type((enum gsd_type)entry.type) == 0)
        {
        return 0;
        }

    // validate that we don't read past the end of the file
    size_t size = entry.N * entry.M * gsd_sizeof_type((enum gsd_type)entry.type);
    if ((entry.location + size) > (uint64_t)handle->file_size)
        {
        return 0;
        }

    // check for valid frame (frame cannot be more than the number of index entries)
    if (entry.frame >= handle->header.index_allocated_entries)
        {
        return 0;
        }

    // check for valid id
    if (entry.id >= (handle->file_names.n_names + handle->frame_names.n_names))
        {
        return 0;
        }

    // check for valid flags
    if (entry.flags != 0)
        {
        return 0;
        }

    return 1;
    }

/** @internal
    @brief Allocate a write buffer

    @param buf Buffer to allocate.
    @param reserve Number of bytes to allocate.

    @returns GSD_SUCCESS on success, GSD_* error codes on error.
*/
inline static int gsd_byte_buffer_allocate(struct gsd_byte_buffer* buf, size_t reserve)
    {
    if (buf == NULL || buf->data || reserve == 0 || buf->reserved != 0 || buf->size != 0)
        {
        return GSD_ERROR_INVALID_ARGUMENT;
        }

    buf->data = calloc(reserve, sizeof(char));
    if (buf->data == NULL)
        {
        return GSD_ERROR_MEMORY_ALLOCATION_FAILED;
        }

    buf->size = 0;
    buf->reserved = reserve;

    return GSD_SUCCESS;
    }

/** @internal
    @brief Append bytes to a byte buffer

    @param buf Buffer to append to.
    @param data Data to append.
    @param size Number of bytes in *data*.

    @returns GSD_SUCCESS on success, GSD_* error codes on error.
*/
inline static int gsd_byte_buffer_append(struct gsd_byte_buffer* buf, const char* data, size_t size)
    {
    if (buf == NULL || buf->data == NULL || size == 0 || buf->reserved == 0)
        {
        return GSD_ERROR_INVALID_ARGUMENT;
        }

    if (buf->size + size > buf->reserved)
        {
        // reallocate by doubling
        size_t new_reserved = buf->reserved * 2;
        while (buf->size + size >= new_reserved)
            {
            new_reserved = new_reserved * 2;
            }

        char* old_data = buf->data;
        buf->data = realloc(buf->data, sizeof(char) * new_reserved);
        if (buf->data == NULL)
            {
            // this free should not be necessary, but clang-tidy disagrees
            free(old_data);
            return GSD_ERROR_MEMORY_ALLOCATION_FAILED;
            }

        // zero the new memory, but only the portion after the end of the new section to be appended
        gsd_util_zero_memory(buf->data + (buf->size + size),
                             sizeof(char) * (new_reserved - (buf->size + size)));
        buf->reserved = new_reserved;
        }

    memcpy(buf->data + buf->size, data, size);
    buf->size += size;

    return GSD_SUCCESS;
    }

/** @internal
    @brief Free the memory allocated by the write buffer or unmap the mapped memory.

    @param buf Buffer to free.

    @returns GSD_SUCCESS on success, GSD_* error codes on error.
*/
inline static int gsd_byte_buffer_free(struct gsd_byte_buffer* buf)
    {
    if (buf == NULL || buf->data == NULL)
        {
        return GSD_ERROR_INVALID_ARGUMENT;
        }

    free(buf->data);

    gsd_util_zero_memory(buf, sizeof(struct gsd_byte_buffer));
    return GSD_SUCCESS;
    }

/** @internal
    @brief Allocate a buffer of index entries

    @param buf Buffer to allocate.
    @param reserve Number of entries to allocate.

    @post The buffer's data element has *reserve* elements allocated in memory.

    @returns GSD_SUCCESS on success, GSD_* error codes on error.
*/
inline static int gsd_index_buffer_allocate(struct gsd_index_buffer* buf, size_t reserve)
    {
    if (buf == NULL || buf->mapped_data || buf->data || reserve == 0 || buf->reserved != 0
        || buf->size != 0)
        {
        return GSD_ERROR_INVALID_ARGUMENT;
        }

    buf->data = calloc(reserve, sizeof(struct gsd_index_entry));
    if (buf->data == NULL)
        {
        return GSD_ERROR_MEMORY_ALLOCATION_FAILED;
        }

    buf->size = 0;
    buf->reserved = reserve;
    buf->mapped_data = NULL;
    buf->mapped_len = 0;

    return GSD_SUCCESS;
    }

/** @internal
    @brief Map index entries from the file

    @param buf Buffer to map.
    @param handle GSD file handle to map.

    @post The buffer's data element contains the index data from the file.

    On some systems, this will use mmap to efficiently access the file. On others, it may result in
    an allocation and read of the entire index from the file.

    @returns GSD_SUCCESS on success, GSD_* error codes on error.
*/
inline static int gsd_index_buffer_map(struct gsd_index_buffer* buf, struct gsd_handle* handle)
    {
    if (buf == NULL || buf->mapped_data || buf->data || buf->reserved != 0 || buf->size != 0)
        {
        return GSD_ERROR_INVALID_ARGUMENT;
        }

    // validate that the index block exists inside the file
    if (handle->header.index_location
            + sizeof(struct gsd_index_entry) * handle->header.index_allocated_entries
        > (uint64_t)handle->file_size)
        {
        return GSD_ERROR_FILE_CORRUPT;
        }

#if GSD_USE_MMAP
    // map the index in read only mode
    size_t page_size = getpagesize();
    size_t index_size = sizeof(struct gsd_index_entry) * handle->header.index_allocated_entries;
    size_t offset = (handle->header.index_location / page_size) * page_size;
    buf->mapped_data = mmap(NULL,
                            index_size + (handle->header.index_location - offset),
                            PROT_READ,
                            MAP_SHARED,
                            handle->fd,
                            offset);

    if (buf->mapped_data == MAP_FAILED)
        {
        return GSD_ERROR_IO;
        }

    buf->data = (struct gsd_index_entry*)(((char*)buf->mapped_data)
                                          + (handle->header.index_location - offset));

    buf->mapped_len = index_size + (handle->header.index_location - offset);
    buf->reserved = handle->header.index_allocated_entries;
#else
    // mmap not supported, read the data from the disk
    int retval = gsd_index_buffer_allocate(buf, handle->header.index_allocated_entries);
    if (retval != GSD_SUCCESS)
        {
        return retval;
        }

    ssize_t bytes_read = gsd_io_pread_retry(handle->fd,
                                            buf->data,
                                            sizeof(struct gsd_index_entry)
                                                * handle->header.index_allocated_entries,
                                            handle->header.index_location);

    if (bytes_read == -1
        || bytes_read != sizeof(struct gsd_index_entry) * handle->header.index_allocated_entries)
        {
        return GSD_ERROR_IO;
        }
#endif

    // determine the number of index entries in the list
    // file is corrupt if first index entry is invalid
    if (buf->data[0].location != 0 && !gsd_is_entry_valid(handle, 0))
        {
        return GSD_ERROR_FILE_CORRUPT;
        }

    if (buf->data[0].location == 0)
        {
        buf->size = 0;
        }
    else
        {
        // determine the number of index entries (marked by location = 0)
        // binary search for the first index entry with location 0
        size_t L = 0;
        size_t R = buf->reserved;

        // progressively narrow the search window by halves
        do
            {
            size_t m = (L + R) / 2;

            // file is corrupt if any index entry is invalid or frame does not increase
            // monotonically
            if (buf->data[m].location != 0
                && (!gsd_is_entry_valid(handle, m) || buf->data[m].frame < buf->data[L].frame))
                {
                return GSD_ERROR_FILE_CORRUPT;
                }

            if (buf->data[m].location != 0)
                {
                L = m;
                }
            else
                {
                R = m;
                }
            } while ((R - L) > 1);

        // this finds R = the first index entry with location = 0
        buf->size = R;
        }

    return GSD_SUCCESS;
    }

/** @internal
    @brief Free the memory allocated by the index buffer or unmap the mapped memory.

    @param buf Buffer to free.

    @returns GSD_SUCCESS on success, GSD_* error codes on error.
*/
inline static int gsd_index_buffer_free(struct gsd_index_buffer* buf)
    {
    if (buf == NULL || buf->data == NULL)
        {
        return GSD_ERROR_INVALID_ARGUMENT;
        }

#if GSD_USE_MMAP
    if (buf->mapped_data)
        {
        int retval = munmap(buf->mapped_data, buf->mapped_len);

        if (retval != 0)
            {
            return GSD_ERROR_IO;
            }
        }
    else
#endif
        {
        free(buf->data);
        }

    gsd_util_zero_memory(buf, sizeof(struct gsd_index_buffer));
    return GSD_SUCCESS;
    }

/** @internal
    @brief Add a new index entry and provide a pointer to it.

    @param buf Buffer to add too.
    @param entry [out] Pointer to set to the new entry.

    Double the size of the reserved space as needed to hold the new entry. Does not accept mapped
    indices.

    @returns GSD_SUCCESS on success, GSD_* error codes on error.
*/
inline static int gsd_index_buffer_add(struct gsd_index_buffer* buf, struct gsd_index_entry** entry)
    {
    if (buf == NULL || buf->mapped_data || entry == NULL || buf->reserved == 0)
        {
        return GSD_ERROR_INVALID_ARGUMENT;
        }

    if (buf->size == buf->reserved)
        {
        // grow the array
        size_t new_reserved = buf->reserved * 2;
        buf->data = realloc(buf->data, sizeof(struct gsd_index_entry) * new_reserved);
        if (buf->data == NULL)
            {
            return GSD_ERROR_MEMORY_ALLOCATION_FAILED;
            }

        // zero the new memory
        gsd_util_zero_memory(buf->data + buf->reserved,
                             sizeof(struct gsd_index_entry) * (new_reserved - buf->reserved));
        buf->reserved = new_reserved;
        }

    size_t insert_pos = buf->size;
    buf->size++;
    *entry = buf->data + insert_pos;

    return GSD_SUCCESS;
    }

inline static int gsd_cmp_index_entry(const struct gsd_index_entry* a,
                                      const struct gsd_index_entry* b)
    {
    int result = 0;

    if (a->frame < b->frame)
        {
        result = -1;
        }

    if (a->frame > b->frame)
        {
        result = 1;
        }

    if (a->frame == b->frame)
        {
        if (a->id < b->id)
            {
            result = -1;
            }

        if (a->id > b->id)
            {
            result = 1;
            }

        if (a->id == b->id)
            {
            result = 0;
            }
        }

    return result;
    }

/** @internal
    @brief Compute heap parent node.
    @param i Node index.
*/
inline static size_t gsd_heap_parent(size_t i)
    {
    return (i - 1) / 2;
    }

/** @internal
    @brief Compute heap left child.
    @param i Node index.
*/
inline static size_t gsd_heap_left_child(size_t i)
    {
    return 2 * i + 1;
    }

/** @internal
    @brief Swap the nodes *a* and *b* in the buffer
    @param buf Buffer.
    @param a First index to swap.
    @param b Second index to swap.
*/
inline static void gsd_heap_swap(struct gsd_index_buffer* buf, size_t a, size_t b)
    {
    struct gsd_index_entry tmp = buf->data[a];
    buf->data[a] = buf->data[b];
    buf->data[b] = tmp;
    }

/** @internal
    @brief Shift heap node downward
    @param buf Buffer.
    @param start First index of the valid heap in *buf*.
    @param end Last index of the valid hep in *buf*.
*/
inline static void gsd_heap_shift_down(struct gsd_index_buffer* buf, size_t start, size_t end)
    {
    size_t root = start;

    while (gsd_heap_left_child(root) <= end)
        {
        size_t child = gsd_heap_left_child(root);
        size_t swap = root;

        if (gsd_cmp_index_entry(buf->data + swap, buf->data + child) < 0)
            {
            swap = child;
            }
        if (child + 1 <= end && gsd_cmp_index_entry(buf->data + swap, buf->data + child + 1) < 0)
            {
            swap = child + 1;
            }

        if (swap == root)
            {
            return;
            }

        gsd_heap_swap(buf, root, swap);
        root = swap;
        }
    }

/** @internal
    @brief Convert unordered index buffer to a heap
    @param buf Buffer.
*/
inline static void gsd_heapify(struct gsd_index_buffer* buf)
    {
    ssize_t start = gsd_heap_parent(buf->size - 1);

    while (start >= 0)
        {
        gsd_heap_shift_down(buf, start, buf->size - 1);
        start--;
        }
    }

/** @internal
    @brief Sort the index buffer.

    @param buf Buffer to sort.

    Sorts an in-memory index buffer. Does not accept mapped indices.

    @returns GSD_SUCCESS on success, GSD_* error codes on error.
*/
inline static int gsd_index_buffer_sort(struct gsd_index_buffer* buf)
    {
    if (buf == NULL || buf->mapped_data || buf->reserved == 0)
        {
        return GSD_ERROR_INVALID_ARGUMENT;
        }

    // arrays of size 0 or 1 are already sorted
    if (buf->size <= 1)
        {
        return GSD_SUCCESS;
        }

    gsd_heapify(buf);

    size_t end = buf->size - 1;
    while (end > 0)
        {
        gsd_heap_swap(buf, end, 0);
        end = end - 1;
        gsd_heap_shift_down(buf, 0, end);
        }

    return GSD_SUCCESS;
    }

/** @internal
    @brief Utility function to expand the memory space for the index block in the file.

    @param handle Handle to the open gsd file.
    @param size_required The new index must be able to hold at least this many elements.

    @returns GSD_SUCCESS on success, GSD_* error codes on error.
*/
inline static int gsd_expand_file_index(struct gsd_handle* handle, size_t size_required)
    {
    if (handle->open_flags == GSD_OPEN_READONLY)
        {
        return GSD_ERROR_FILE_MUST_BE_WRITABLE;
        }

    // multiply the index size each time it grows
    // this allows the index to grow rapidly to accommodate new frames
    const int multiplication_factor = 2;

    // save the old size and update the new size
    size_t size_old = handle->header.index_allocated_entries;
    size_t size_new = size_old * multiplication_factor;

    while (size_new <= size_required)
        {
        size_new *= multiplication_factor;
        }

    // Mac systems deadlock when writing from a mapped region into the tail end of that same region
    // unmap the index first and copy it over by chunks
    int retval = gsd_index_buffer_free(&handle->file_index);
    if (retval != 0)
        {
        return retval;
        }

    // allocate the copy buffer
    char* buf = malloc(GSD_COPY_BUFFER_SIZE);

    // write the current index to the end of the file
    int64_t new_index_location = lseek(handle->fd, 0, SEEK_END);
    int64_t old_index_location = handle->header.index_location;
    size_t total_bytes_written = 0;
    size_t old_index_bytes = size_old * sizeof(struct gsd_index_entry);
    while (total_bytes_written < old_index_bytes)
        {
        size_t bytes_to_copy = GSD_COPY_BUFFER_SIZE;
        if (old_index_bytes - total_bytes_written < GSD_COPY_BUFFER_SIZE)
            {
            bytes_to_copy = old_index_bytes - total_bytes_written;
            }

        ssize_t bytes_read = gsd_io_pread_retry(handle->fd,
                                                buf,
                                                bytes_to_copy,
                                                old_index_location + total_bytes_written);

        if (bytes_read == -1 || bytes_read != bytes_to_copy)
            {
            free(buf);
            return GSD_ERROR_IO;
            }

        ssize_t bytes_written = gsd_io_pwrite_retry(handle->fd,
                                                    buf,
                                                    bytes_to_copy,
                                                    new_index_location + total_bytes_written);

        if (bytes_written == -1 || bytes_written != bytes_to_copy)
            {
            free(buf);
            return GSD_ERROR_IO;
            }

        total_bytes_written += bytes_written;
        }

    // fill the new index space with 0s
    gsd_util_zero_memory(buf, GSD_COPY_BUFFER_SIZE);

    size_t new_index_bytes = size_new * sizeof(struct gsd_index_entry);
    while (total_bytes_written < new_index_bytes)
        {
        size_t bytes_to_copy = GSD_COPY_BUFFER_SIZE;
        if (new_index_bytes - total_bytes_written < GSD_COPY_BUFFER_SIZE)
            {
            bytes_to_copy = new_index_bytes - total_bytes_written;
            }

        ssize_t bytes_written = gsd_io_pwrite_retry(handle->fd,
                                                    buf,
                                                    bytes_to_copy,
                                                    new_index_location + total_bytes_written);

        if (bytes_written == -1 || bytes_written != bytes_to_copy)
            {
            free(buf);
            return GSD_ERROR_IO;
            }

        total_bytes_written += bytes_written;
        }

    // sync the expanded index
    retval = fsync(handle->fd);
    if (retval != 0)
        {
        free(buf);
        return GSD_ERROR_IO;
        }

    // free the copy buffer
    free(buf);

    // update the header
    handle->header.index_location = new_index_location;
    handle->file_size = handle->header.index_location + total_bytes_written;
    handle->header.index_allocated_entries = size_new;

    // write the new header out
    ssize_t bytes_written
        = gsd_io_pwrite_retry(handle->fd, &(handle->header), sizeof(struct gsd_header), 0);
    if (bytes_written != sizeof(struct gsd_header))
        {
        return GSD_ERROR_IO;
        }

    // sync the updated header
    retval = fsync(handle->fd);
    if (retval != 0)
        {
        return GSD_ERROR_IO;
        }

    // remap the file index
    retval = gsd_index_buffer_map(&handle->file_index, handle);
    if (retval != 0)
        {
        return retval;
        }

    return GSD_SUCCESS;
    }

/** @internal
    @brief Flush the write buffer.

    gsd_write_frame() writes small data chunks into the write buffer. It adds index entries for
    these chunks to gsd_handle::buffer_index with locations offset from the start of the write
    buffer. gsd_flush_write_buffer() writes the buffer to the end of the file, moves the index
    entries to gsd_handle::frame_index and updates the location to reference the beginning of the
    file.

    @param handle Handle to flush the write buffer.
    @returns GSD_SUCCESS on success or GSD_* error codes on error
*/
inline static int gsd_flush_write_buffer(struct gsd_handle* handle)
    {
    if (handle == NULL)
        {
        return GSD_ERROR_INVALID_ARGUMENT;
        }

    if (handle->write_buffer.size == 0 && handle->buffer_index.size == 0)
        {
        // nothing to do
        return GSD_SUCCESS;
        }

    if (handle->write_buffer.size > 0 && handle->buffer_index.size == 0)
        {
        // error: bytes in buffer, but no index for them
        return GSD_ERROR_INVALID_ARGUMENT;
        }

    // write the buffer to the end of the file
    uint64_t offset = handle->file_size;
    ssize_t bytes_written = gsd_io_pwrite_retry(handle->fd,
                                                handle->write_buffer.data,
                                                handle->write_buffer.size,
                                                offset);

    if (bytes_written == -1 || bytes_written != handle->write_buffer.size)
        {
        return GSD_ERROR_IO;
        }

    handle->file_size += handle->write_buffer.size;

    // reset write_buffer for new data
    handle->write_buffer.size = 0;

    // move buffer_index entries to file_index
    size_t i;
    for (i = 0; i < handle->buffer_index.size; i++)
        {
        struct gsd_index_entry* new_index;
        int retval = gsd_index_buffer_add(&handle->frame_index, &new_index);
        if (retval != GSD_SUCCESS)
            {
            return retval;
            }

        *new_index = handle->buffer_index.data[i];
        new_index->location += offset;
        }

    // clear the buffer index for new entries
    handle->buffer_index.size = 0;

    return GSD_SUCCESS;
    }

/** @internal
    @brief Flush the name buffer.

    gsd_write_frame() adds new names to the frame_names buffer. gsd_flush_name_buffer() flushes
    this buffer at the end of a frame write and commits the new names to the file. If necessary,
    the namelist is written to a new location in the file.

    @param handle Handle to flush the write buffer.
    @returns GSD_SUCCESS on success or GSD_* error codes on error
*/
inline static int gsd_flush_name_buffer(struct gsd_handle* handle)
    {
    if (handle == NULL)
        {
        return GSD_ERROR_INVALID_ARGUMENT;
        }

    if (handle->frame_names.n_names == 0)
        {
        // nothing to do
        return GSD_SUCCESS;
        }

    if (handle->frame_names.data.size == 0)
        {
        // error: bytes in buffer, but no names for them
        return GSD_ERROR_INVALID_ARGUMENT;
        }

    size_t old_reserved = handle->file_names.data.reserved;
    size_t old_size = handle->file_names.data.size;

    // add the new names to the file name list and zero the frame list
    int retval = gsd_byte_buffer_append(&handle->file_names.data,
                                        handle->frame_names.data.data,
                                        handle->frame_names.data.size);
    if (retval != GSD_SUCCESS)
        {
        return retval;
        }

    handle->file_names.n_names += handle->frame_names.n_names;
    handle->frame_names.n_names = 0;
    handle->frame_names.data.size = 0;
    gsd_util_zero_memory(handle->frame_names.data.data, handle->frame_names.data.reserved);

    // reserved space must be a multiple of the GSD name size
    if (handle->file_names.data.reserved % GSD_NAME_SIZE != 0)
        {
        return GSD_ERROR_INVALID_ARGUMENT;
        }

    if (handle->file_names.data.reserved > old_reserved)
        {
        // write the new name list to the end of the file
        uint64_t offset = handle->file_size;
        ssize_t bytes_written = gsd_io_pwrite_retry(handle->fd,
                                                    handle->file_names.data.data,
                                                    handle->file_names.data.reserved,
                                                    offset);

        if (bytes_written == -1 || bytes_written != handle->file_names.data.reserved)
            {
            return GSD_ERROR_IO;
            }

        // sync the updated name list
        retval = fsync(handle->fd);
        if (retval != 0)
            {
            return GSD_ERROR_IO;
            }

        handle->file_size += handle->file_names.data.reserved;
        handle->header.namelist_location = offset;
        handle->header.namelist_allocated_entries
            = handle->file_names.data.reserved / GSD_NAME_SIZE;

        // write the new header out
        bytes_written
            = gsd_io_pwrite_retry(handle->fd, &(handle->header), sizeof(struct gsd_header), 0);
        if (bytes_written != sizeof(struct gsd_header))
            {
            return GSD_ERROR_IO;
            }
        }
    else
        {
        // write the new name list to the old index location
        uint64_t offset = handle->header.namelist_location;
        ssize_t bytes_written = gsd_io_pwrite_retry(handle->fd,
                                                    handle->file_names.data.data + old_size,
                                                    handle->file_names.data.reserved - old_size,
                                                    offset + old_size);
        if (bytes_written != (handle->file_names.data.reserved - old_size))
            {
            return GSD_ERROR_IO;
            }
        }

    // sync the updated name list or header
    retval = fsync(handle->fd);
    if (retval != 0)
        {
        return GSD_ERROR_IO;
        }

    return GSD_SUCCESS;
    }

/** @internal
    @brief utility function to append a name to the namelist

    @param id [out] ID of the new name
    @param handle handle to the open gsd file
    @param name string name

    Append a name to the names in the current frame. gsd_end_frame() will add this list to the
    file names.

    @return
      - GSD_SUCCESS (0) on success. Negative value on failure:
      - GSD_ERROR_IO: IO error (check errno).
      - GSD_ERROR_MEMORY_ALLOCATION_FAILED: Unable to allocate memory.
      - GSD_ERROR_FILE_MUST_BE_WRITABLE: File must not be read only.
*/
inline static int gsd_append_name(uint16_t* id, struct gsd_handle* handle, const char* name)
    {
    if (handle->open_flags == GSD_OPEN_READONLY)
        {
        return GSD_ERROR_FILE_MUST_BE_WRITABLE;
        }

    if (handle->file_names.n_names + handle->frame_names.n_names == UINT16_MAX)
        {
        // no more names may be added
        return GSD_ERROR_NAMELIST_FULL;
        }

    // Provide the ID of the new name
    *id = (uint16_t)(handle->file_names.n_names + handle->frame_names.n_names);

    if (handle->header.gsd_version < gsd_make_version(2, 0))
        {
        // v1 files always allocate GSD_NAME_SIZE bytes for each name and put a NULL terminator
        // at address 63
        char name_v1[GSD_NAME_SIZE];
        strncpy(name_v1, name, GSD_NAME_SIZE - 1);
        name_v1[GSD_NAME_SIZE - 1] = 0;
        gsd_byte_buffer_append(&handle->frame_names.data, name_v1, GSD_NAME_SIZE);
        handle->frame_names.n_names++;

        // update the name/id mapping with the truncated name
        int retval = gsd_name_id_map_insert(&handle->name_map, name_v1, *id);
        if (retval != GSD_SUCCESS)
            {
            return retval;
            }
        }
    else
        {
        gsd_byte_buffer_append(&handle->frame_names.data, name, strlen(name) + 1);
        handle->frame_names.n_names++;

        // update the name/id mapping
        int retval = gsd_name_id_map_insert(&handle->name_map, name, *id);
        if (retval != GSD_SUCCESS)
            {
            return retval;
            }
        }

    return GSD_SUCCESS;
    }

/** @internal
    @brief Truncate the file and write a new gsd header.

    @param fd file descriptor to initialize
    @param application Generating application name (truncated to 63 chars)
    @param schema Schema name for data to be written in this GSD file (truncated to 63 chars)
    @param schema_version Version of the scheme data to be written (make with gsd_make_version())
*/
inline static int
gsd_initialize_file(int fd, const char* application, const char* schema, uint32_t schema_version)
    {
    // check if the file was created
    if (fd == -1)
        {
        return GSD_ERROR_IO;
        }

    int retval = ftruncate(fd, 0);
    if (retval != 0)
        {
        return GSD_ERROR_IO;
        }

    // populate header fields
    struct gsd_header header;
    gsd_util_zero_memory(&header, sizeof(header));

    header.magic = GSD_MAGIC_ID;
    header.gsd_version = gsd_make_version(GSD_CURRENT_FILE_VERSION, 0);
    strncpy(header.application, application, sizeof(header.application) - 1);
    header.application[sizeof(header.application) - 1] = 0;
    strncpy(header.schema, schema, sizeof(header.schema) - 1);
    header.schema[sizeof(header.schema) - 1] = 0;
    header.schema_version = schema_version;
    header.index_location = sizeof(header);
    header.index_allocated_entries = GSD_INITIAL_INDEX_SIZE;
    header.namelist_location
        = header.index_location + sizeof(struct gsd_index_entry) * header.index_allocated_entries;
    header.namelist_allocated_entries = GSD_INITIAL_NAME_BUFFER_SIZE / GSD_NAME_SIZE;
    gsd_util_zero_memory(header.reserved, sizeof(header.reserved));

    // write the header out
    ssize_t bytes_written = gsd_io_pwrite_retry(fd, &header, sizeof(header), 0);
    if (bytes_written != sizeof(header))
        {
        return GSD_ERROR_IO;
        }

    // allocate and zero default index memory
    struct gsd_index_entry index[GSD_INITIAL_INDEX_SIZE];
    gsd_util_zero_memory(index, sizeof(index));

    // write the empty index out
    bytes_written = gsd_io_pwrite_retry(fd, index, sizeof(index), sizeof(header));
    if (bytes_written != sizeof(index))
        {
        return GSD_ERROR_IO;
        }

    // allocate and zero the namelist memory
    char names[GSD_INITIAL_NAME_BUFFER_SIZE];
    gsd_util_zero_memory(names, sizeof(char) * GSD_INITIAL_NAME_BUFFER_SIZE);

    // write the namelist out
    bytes_written = gsd_io_pwrite_retry(fd, names, sizeof(names), sizeof(header) + sizeof(index));
    if (bytes_written != sizeof(names))
        {
        return GSD_ERROR_IO;
        }

    // sync file
    retval = fsync(fd);
    if (retval != 0)
        {
        return GSD_ERROR_IO;
        }

    return GSD_SUCCESS;
    }

/** @internal
    @brief Read in the file index and initialize the handle.

    @param handle Handle to read the header

    @pre handle->fd is an open file.
    @pre handle->open_flags is set.
*/
inline static int gsd_initialize_handle(struct gsd_handle* handle)
    {
    // check if the file was created
    if (handle->fd == -1)
        {
        return GSD_ERROR_IO;
        }

    // read the header
    ssize_t bytes_read
        = gsd_io_pread_retry(handle->fd, &handle->header, sizeof(struct gsd_header), 0);
    if (bytes_read == -1)
        {
        return GSD_ERROR_IO;
        }
    if (bytes_read != sizeof(struct gsd_header))
        {
        return GSD_ERROR_NOT_A_GSD_FILE;
        }

    // validate the header
    if (handle->header.magic != GSD_MAGIC_ID)
        {
        return GSD_ERROR_NOT_A_GSD_FILE;
        }

    if (handle->header.gsd_version < gsd_make_version(1, 0)
        && handle->header.gsd_version != gsd_make_version(0, 3))
        {
        return GSD_ERROR_INVALID_GSD_FILE_VERSION;
        }

    if (handle->header.gsd_version >= gsd_make_version(3, 0))
        {
        return GSD_ERROR_INVALID_GSD_FILE_VERSION;
        }

    // determine the file size
    handle->file_size = lseek(handle->fd, 0, SEEK_END);

    // validate that the namelist block exists inside the file
    if (handle->header.namelist_location
            + (GSD_NAME_SIZE * handle->header.namelist_allocated_entries)
        > (uint64_t)handle->file_size)
        {
        return GSD_ERROR_FILE_CORRUPT;
        }

    // allocate the hash map
    int retval = gsd_name_id_map_allocate(&handle->name_map, GSD_NAME_MAP_SIZE);
    if (retval != GSD_SUCCESS)
        {
        return retval;
        }

    // read the namelist block
    size_t namelist_n_bytes = GSD_NAME_SIZE * handle->header.namelist_allocated_entries;
    retval = gsd_byte_buffer_allocate(&handle->file_names.data, namelist_n_bytes);
    if (retval != GSD_SUCCESS)
        {
        return retval;
        }
    bytes_read = gsd_io_pread_retry(handle->fd,
                                    handle->file_names.data.data,
                                    namelist_n_bytes,
                                    handle->header.namelist_location);

    if (bytes_read == -1 || bytes_read != namelist_n_bytes)
        {
        return GSD_ERROR_IO;
        }

    // The name buffer must end in a NULL terminator or else the file is corrupt
    if (handle->file_names.data.data[handle->file_names.data.reserved - 1] != 0)
        {
        return GSD_ERROR_FILE_CORRUPT;
        }

    // Add the names to the hash map. Also determine the number of used bytes in the namelist.
    size_t name_start = 0;
    handle->file_names.n_names = 0;
    while (name_start < handle->file_names.data.reserved)
        {
        char* name = handle->file_names.data.data + name_start;

        // an empty name notes the end of the list
        if (name[0] == 0)
            {
            break;
            }

        retval
            = gsd_name_id_map_insert(&handle->name_map, name, (uint16_t)handle->file_names.n_names);
        if (retval != GSD_SUCCESS)
            {
            return retval;
            }
        handle->file_names.n_names++;

        if (handle->header.gsd_version < gsd_make_version(2, 0))
            {
            // gsd v1 stores names in fixed 64 byte segments
            name_start += GSD_NAME_SIZE;
            }
        else
            {
            size_t len = strnlen(name, handle->file_names.data.reserved - name_start);
            name_start += len + 1;
            }
        }

    handle->file_names.data.size = name_start;

    // read in the file index
    retval = gsd_index_buffer_map(&handle->file_index, handle);
    if (retval != GSD_SUCCESS)
        {
        return retval;
        }

    // determine the current frame counter
    if (handle->file_index.size == 0)
        {
        handle->cur_frame = 0;
        }
    else
        {
        handle->cur_frame = handle->file_index.data[handle->file_index.size - 1].frame + 1;
        }

    // if this is a write mode, allocate the initial frame index and the name buffer
    if (handle->open_flags != GSD_OPEN_READONLY)
        {
        retval = gsd_index_buffer_allocate(&handle->frame_index, GSD_INITIAL_FRAME_INDEX_SIZE);
        if (retval != GSD_SUCCESS)
            {
            return retval;
            }

        retval = gsd_index_buffer_allocate(&handle->buffer_index, GSD_INITIAL_FRAME_INDEX_SIZE);
        if (retval != GSD_SUCCESS)
            {
            return retval;
            }

        retval = gsd_byte_buffer_allocate(&handle->write_buffer, GSD_WRITE_BUFFER_SIZE);
        if (retval != GSD_SUCCESS)
            {
            return retval;
            }

        handle->frame_names.n_names = 0;
        retval = gsd_byte_buffer_allocate(&handle->frame_names.data, GSD_NAME_SIZE);
        if (retval != GSD_SUCCESS)
            {
            return retval;
            }
        }

    return GSD_SUCCESS;
    }

uint32_t gsd_make_version(unsigned int major, unsigned int minor)
    {
    return major << (sizeof(uint32_t) * 4) | minor;
    }

int gsd_create(const char* fname,
               const char* application,
               const char* schema,
               uint32_t schema_version)
    {
    int extra_flags = 0;
#ifdef _WIN32
    extra_flags = _O_BINARY;
#endif

    // create the file
    int fd = open(fname,
                  O_RDWR | O_CREAT | O_TRUNC | extra_flags,
                  S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
    int retval = gsd_initialize_file(fd, application, schema, schema_version);
    close(fd);
    return retval;
    }

int gsd_create_and_open(struct gsd_handle* handle,
                        const char* fname,
                        const char* application,
                        const char* schema,
                        uint32_t schema_version,
                        const enum gsd_open_flag flags,
                        int exclusive_create)
    {
    // zero the handle
    gsd_util_zero_memory(handle, sizeof(struct gsd_handle));

    int extra_flags = 0;
#ifdef _WIN32
    extra_flags = _O_BINARY;
#endif

    // set the open flags in the handle
    if (flags == GSD_OPEN_READWRITE)
        {
        handle->open_flags = GSD_OPEN_READWRITE;
        }
    else if (flags == GSD_OPEN_READONLY)
        {
        return GSD_ERROR_FILE_MUST_BE_WRITABLE;
        }
    else if (flags == GSD_OPEN_APPEND)
        {
        handle->open_flags = GSD_OPEN_APPEND;
        }

    // set the exclusive create bit
    if (exclusive_create)
        {
        extra_flags |= O_EXCL;
        }

    // create the file
    handle->fd = open(fname,
                      O_RDWR | O_CREAT | O_TRUNC | extra_flags,
                      S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
    int retval = gsd_initialize_file(handle->fd, application, schema, schema_version);
    if (retval != 0)
        {
        close(handle->fd);
        return retval;
        }

    retval = gsd_initialize_handle(handle);
    if (retval != 0)
        {
        close(handle->fd);
        }
    return retval;
    }

int gsd_open(struct gsd_handle* handle, const char* fname, const enum gsd_open_flag flags)
    {
    // zero the handle
    gsd_util_zero_memory(handle, sizeof(struct gsd_handle));

    int extra_flags = 0;
#ifdef _WIN32
    extra_flags = _O_BINARY;
#endif

    // open the file
    if (flags == GSD_OPEN_READWRITE)
        {
        handle->fd = open(fname, O_RDWR | extra_flags);
        handle->open_flags = GSD_OPEN_READWRITE;
        }
    else if (flags == GSD_OPEN_READONLY)
        {
        handle->fd = open(fname, O_RDONLY | extra_flags);
        handle->open_flags = GSD_OPEN_READONLY;
        }
    else if (flags == GSD_OPEN_APPEND)
        {
        handle->fd = open(fname, O_RDWR | extra_flags);
        handle->open_flags = GSD_OPEN_APPEND;
        }

    int retval = gsd_initialize_handle(handle);
    if (retval != 0)
        {
        close(handle->fd);
        }
    return retval;
    }

int gsd_truncate(struct gsd_handle* handle)
    {
    if (handle == NULL)
        {
        return GSD_ERROR_INVALID_ARGUMENT;
        }
    if (handle->open_flags == GSD_OPEN_READONLY)
        {
        return GSD_ERROR_FILE_MUST_BE_WRITABLE;
        }

    int retval = 0;

    // deallocate indices
    if (handle->frame_names.data.reserved > 0)
        {
        retval = gsd_byte_buffer_free(&handle->frame_names.data);
        if (retval != GSD_SUCCESS)
            {
            return retval;
            }
        }

    if (handle->file_names.data.reserved > 0)
        {
        retval = gsd_byte_buffer_free(&handle->file_names.data);
        if (retval != GSD_SUCCESS)
            {
            return retval;
            }
        }

    retval = gsd_name_id_map_free(&handle->name_map);
    if (retval != GSD_SUCCESS)
        {
        return retval;
        }

    retval = gsd_index_buffer_free(&handle->file_index);
    if (retval != GSD_SUCCESS)
        {
        return retval;
        }

    if (handle->frame_index.reserved > 0)
        {
        retval = gsd_index_buffer_free(&handle->frame_index);
        if (retval != GSD_SUCCESS)
            {
            return retval;
            }
        }

    if (handle->buffer_index.reserved > 0)
        {
        retval = gsd_index_buffer_free(&handle->buffer_index);
        if (retval != GSD_SUCCESS)
            {
            return retval;
            }
        }

    if (handle->write_buffer.reserved > 0)
        {
        retval = gsd_byte_buffer_free(&handle->write_buffer);
        if (retval != GSD_SUCCESS)
            {
            return retval;
            }
        }

    // keep a copy of the old header
    struct gsd_header old_header = handle->header;
    retval = gsd_initialize_file(handle->fd,
                                 old_header.application,
                                 old_header.schema,
                                 old_header.schema_version);

    if (retval != GSD_SUCCESS)
        {
        return retval;
        }

    return gsd_initialize_handle(handle);
    }

int gsd_close(struct gsd_handle* handle)
    {
    if (handle == NULL)
        {
        return GSD_ERROR_INVALID_ARGUMENT;
        }

    // save the fd so we can use it after freeing the handle
    int fd = handle->fd;

    int retval = gsd_index_buffer_free(&handle->file_index);
    if (retval != GSD_SUCCESS)
        {
        return retval;
        }

    if (handle->frame_index.reserved > 0)
        {
        retval = gsd_index_buffer_free(&handle->frame_index);
        if (retval != GSD_SUCCESS)
            {
            return retval;
            }
        }

    if (handle->buffer_index.reserved > 0)
        {
        retval = gsd_index_buffer_free(&handle->buffer_index);
        if (retval != GSD_SUCCESS)
            {
            return retval;
            }
        }

    if (handle->write_buffer.reserved > 0)
        {
        retval = gsd_byte_buffer_free(&handle->write_buffer);
        if (retval != GSD_SUCCESS)
            {
            return retval;
            }
        }

    retval = gsd_name_id_map_free(&handle->name_map);
    if (retval != GSD_SUCCESS)
        {
        return retval;
        }

    if (handle->frame_names.data.reserved > 0)
        {
        handle->frame_names.n_names = 0;
        retval = gsd_byte_buffer_free(&handle->frame_names.data);
        if (retval != GSD_SUCCESS)
            {
            return retval;
            }
        }

    if (handle->file_names.data.reserved > 0)
        {
        handle->file_names.n_names = 0;
        retval = gsd_byte_buffer_free(&handle->file_names.data);
        if (retval != GSD_SUCCESS)
            {
            return retval;
            }
        }

    // close the file
    retval = close(fd);
    if (retval != 0)
        {
        return GSD_ERROR_IO;
        }

    return GSD_SUCCESS;
    }

int gsd_end_frame(struct gsd_handle* handle)
    {
    if (handle == NULL)
        {
        return GSD_ERROR_INVALID_ARGUMENT;
        }
    if (handle->open_flags == GSD_OPEN_READONLY)
        {
        return GSD_ERROR_FILE_MUST_BE_WRITABLE;
        }

    // increment the frame counter
    handle->cur_frame++;

    // flush the namelist buffer
    int retval = gsd_flush_name_buffer(handle);
    if (retval != GSD_SUCCESS)
        {
        return retval;
        }

    // flush the write buffer
    retval = gsd_flush_write_buffer(handle);
    if (retval != GSD_SUCCESS)
        {
        return retval;
        }

    // write the frame index to the file
    if (handle->frame_index.size > 0)
        {
        // ensure there is enough space in the index
        if ((handle->file_index.size + handle->frame_index.size) > handle->file_index.reserved)
            {
            gsd_expand_file_index(handle, handle->file_index.size + handle->frame_index.size);
            }

        // sort the index before writing
        retval = gsd_index_buffer_sort(&handle->frame_index);
        if (retval != 0)
            {
            return retval;
            }

        // write the frame index entries to the file
        int64_t write_pos = handle->header.index_location
                            + sizeof(struct gsd_index_entry) * handle->file_index.size;

        size_t bytes_to_write = sizeof(struct gsd_index_entry) * handle->frame_index.size;
        ssize_t bytes_written
            = gsd_io_pwrite_retry(handle->fd, handle->frame_index.data, bytes_to_write, write_pos);

        if (bytes_written == -1 || bytes_written != bytes_to_write)
            {
            return GSD_ERROR_IO;
            }

#if !GSD_USE_MMAP
        // add the entries to the file index
        memcpy(handle->file_index.data + handle->file_index.size,
               handle->frame_index.data,
               sizeof(struct gsd_index_entry) * handle->frame_index.size);
#endif

        // update size of file index
        handle->file_index.size += handle->frame_index.size;

        // clear the frame index
        handle->frame_index.size = 0;
        }

    return GSD_SUCCESS;
    }

int gsd_write_chunk(struct gsd_handle* handle,
                    const char* name,
                    enum gsd_type type,
                    uint64_t N,
                    uint32_t M,
                    uint8_t flags,
                    const void* data)
    {
    // validate input
    if (N > 0 && data == NULL)
        {
        return GSD_ERROR_INVALID_ARGUMENT;
        }
    if (M == 0)
        {
        return GSD_ERROR_INVALID_ARGUMENT;
        }
    if (handle->open_flags == GSD_OPEN_READONLY)
        {
        return GSD_ERROR_FILE_MUST_BE_WRITABLE;
        }
    if (flags != 0)
        {
        return GSD_ERROR_INVALID_ARGUMENT;
        }

    uint16_t id = gsd_name_id_map_find(&handle->name_map, name);
    if (id == UINT16_MAX)
        {
        // not found, append to the index
        int retval = gsd_append_name(&id, handle, name);
        if (retval != GSD_SUCCESS)
            {
            return retval;
            }

        if (id == UINT16_MAX)
            {
            // this should never happen
            return GSD_ERROR_NAMELIST_FULL;
            }
        }

    struct gsd_index_entry entry;
    // populate fields in the entry's data
    gsd_util_zero_memory(&entry, sizeof(struct gsd_index_entry));
    entry.frame = handle->cur_frame;
    entry.id = id;
    entry.type = (uint8_t)type;
    entry.N = N;
    entry.M = M;
    size_t size = N * M * gsd_sizeof_type(type);

    // decide whether to write this chunk to the buffer or straight to disk
    if (size < handle->write_buffer.reserved / 2)
        {
        // flush the buffer if this entry won't fit
        if (size > (handle->write_buffer.reserved - handle->write_buffer.size))
            {
            gsd_flush_write_buffer(handle);
            }

        entry.location = handle->write_buffer.size;

        // add an entry to the buffer index
        struct gsd_index_entry* index_entry;

        int retval = gsd_index_buffer_add(&handle->buffer_index, &index_entry);
        if (retval != GSD_SUCCESS)
            {
            return retval;
            }
        *index_entry = entry;

        // add the data to the write buffer
        if (size > 0)
            {
            retval = gsd_byte_buffer_append(&handle->write_buffer, data, size);
            if (retval != GSD_SUCCESS)
                {
                return retval;
                }
            }
        }
    else
        {
        // add an entry to the frame index
        struct gsd_index_entry* index_entry;

        int retval = gsd_index_buffer_add(&handle->frame_index, &index_entry);
        if (retval != GSD_SUCCESS)
            {
            return retval;
            }
        *index_entry = entry;

        // find the location at the end of the file for the chunk
        index_entry->location = handle->file_size;

        // write the data
        ssize_t bytes_written = gsd_io_pwrite_retry(handle->fd, data, size, index_entry->location);
        if (bytes_written == -1 || bytes_written != size)
            {
            return GSD_ERROR_IO;
            }

        // update the file_size in the handle
        handle->file_size += bytes_written;
        }

    return GSD_SUCCESS;
    }

uint64_t gsd_get_nframes(struct gsd_handle* handle)
    {
    if (handle == NULL)
        {
        return 0;
        }
    return handle->cur_frame;
    }

const struct gsd_index_entry*
gsd_find_chunk(struct gsd_handle* handle, uint64_t frame, const char* name)
    {
    if (handle == NULL)
        {
        return NULL;
        }
    if (name == NULL)
        {
        return NULL;
        }
    if (frame >= gsd_get_nframes(handle))
        {
        return NULL;
        }
    if (handle->open_flags == GSD_OPEN_APPEND)
        {
        return NULL;
        }

    // find the id for the given name
    uint16_t match_id = gsd_name_id_map_find(&handle->name_map, name);
    if (match_id == UINT16_MAX)
        {
        return NULL;
        }

    if (handle->header.gsd_version >= gsd_make_version(2, 0))
        {
        // gsd 2.0 files sort the entire index
        // binary search for the index entry
        ssize_t L = 0;
        ssize_t R = handle->file_index.size - 1;
        struct gsd_index_entry T;
        T.frame = frame;
        T.id = match_id;

        while (L <= R)
            {
            size_t m = (L + R) / 2;
            int cmp = gsd_cmp_index_entry(handle->file_index.data + m, &T);
            if (cmp == -1)
                {
                L = m + 1;
                }
            else if (cmp == 1)
                {
                R = m - 1;
                }
            else
                {
                return &(handle->file_index.data[m]);
                }
            }
        }
    else
        {
        // gsd 1.0 file: use binary search to find the frame and linear search to find the entry
        size_t L = 0;
        size_t R = handle->file_index.size;

        // progressively narrow the search window by halves
        do
            {
            size_t m = (L + R) / 2;

            if (frame < handle->file_index.data[m].frame)
                {
                R = m;
                }
            else
                {
                L = m;
                }
            } while ((R - L) > 1);

        // this finds L = the rightmost index with the desired frame
        int64_t cur_index;

        // search all index entries with the matching frame
        for (cur_index = L; (cur_index >= 0) && (handle->file_index.data[cur_index].frame == frame);
             cur_index--)
            {
            // if the frame matches, check the id
            if (match_id == handle->file_index.data[cur_index].id)
                {
                return &(handle->file_index.data[cur_index]);
                }
            }
        }

    // if we got here, we didn't find the specified chunk
    return NULL;
    }

int gsd_read_chunk(struct gsd_handle* handle, void* data, const struct gsd_index_entry* chunk)
    {
    if (handle == NULL)
        {
        return GSD_ERROR_INVALID_ARGUMENT;
        }
    if (data == NULL)
        {
        return GSD_ERROR_INVALID_ARGUMENT;
        }
    if (chunk == NULL)
        {
        return GSD_ERROR_INVALID_ARGUMENT;
        }
    if (handle->open_flags == GSD_OPEN_APPEND)
        {
        return GSD_ERROR_FILE_MUST_BE_READABLE;
        }

    size_t size = chunk->N * chunk->M * gsd_sizeof_type((enum gsd_type)chunk->type);
    if (size == 0)
        {
        return GSD_ERROR_FILE_CORRUPT;
        }
    if (chunk->location == 0)
        {
        return GSD_ERROR_FILE_CORRUPT;
        }

    // validate that we don't read past the end of the file
    if ((chunk->location + size) > (uint64_t)handle->file_size)
        {
        return GSD_ERROR_FILE_CORRUPT;
        }

    ssize_t bytes_read = gsd_io_pread_retry(handle->fd, data, size, chunk->location);
    if (bytes_read == -1 || bytes_read != size)
        {
        return GSD_ERROR_IO;
        }

    return GSD_SUCCESS;
    }

size_t gsd_sizeof_type(enum gsd_type type)
    {
    size_t val = 0;
    if (type == GSD_TYPE_UINT8)
        {
        val = sizeof(uint8_t);
        }
    else if (type == GSD_TYPE_UINT16)
        {
        val = sizeof(uint16_t);
        }
    else if (type == GSD_TYPE_UINT32)
        {
        val = sizeof(uint32_t);
        }
    else if (type == GSD_TYPE_UINT64)
        {
        val = sizeof(uint64_t);
        }
    else if (type == GSD_TYPE_INT8)
        {
        val = sizeof(int8_t);
        }
    else if (type == GSD_TYPE_INT16)
        {
        val = sizeof(int16_t);
        }
    else if (type == GSD_TYPE_INT32)
        {
        val = sizeof(int32_t);
        }
    else if (type == GSD_TYPE_INT64)
        {
        val = sizeof(int64_t);
        }
    else if (type == GSD_TYPE_FLOAT)
        {
        val = sizeof(float);
        }
    else if (type == GSD_TYPE_DOUBLE)
        {
        val = sizeof(double);
        }
    else
        {
        return 0;
        }
    return val;
    }

const char*
gsd_find_matching_chunk_name(struct gsd_handle* handle, const char* match, const char* prev)
    {
    if (handle == NULL)
        {
        return NULL;
        }
    if (match == NULL)
        {
        return NULL;
        }
    if (handle->file_names.n_names == 0)
        {
        return NULL;
        }

    // return nothing found if the name buffer is corrupt
    if (handle->file_names.data.data[handle->file_names.data.reserved - 1] != 0)
        {
        return NULL;
        }

    // determine search start index
    const char* search_str;
    if (prev == NULL)
        {
        search_str = handle->file_names.data.data;
        }
    else
        {
        // return not found if prev is not in range
        if (prev < handle->file_names.data.data)
            {
            return NULL;
            }
        if (prev >= (handle->file_names.data.data + handle->file_names.data.reserved))
            {
            return NULL;
            }

        if (handle->header.gsd_version < gsd_make_version(2, 0))
            {
            search_str = prev + GSD_NAME_SIZE;
            }
        else
            {
            search_str = prev + strlen(prev) + 1;
            }
        }

    size_t match_len = strlen(match);

    while (search_str < (handle->file_names.data.data + handle->file_names.data.reserved))
        {
        if (search_str[0] != 0 && 0 == strncmp(match, search_str, match_len))
            {
            return search_str;
            }

        if (handle->header.gsd_version < gsd_make_version(2, 0))
            {
            search_str += GSD_NAME_SIZE;
            }
        else
            {
            search_str += strlen(search_str) + 1;
            }
        }

    // searched past the end of the list, return NULL
    return NULL;
    }

int gsd_upgrade(struct gsd_handle* handle)
    {
    if (handle == NULL)
        {
        return GSD_ERROR_INVALID_ARGUMENT;
        }
    if (handle->open_flags == GSD_OPEN_READONLY)
        {
        return GSD_ERROR_INVALID_ARGUMENT;
        }
    if (handle->frame_index.size > 0 || handle->frame_names.n_names > 0)
        {
        return GSD_ERROR_INVALID_ARGUMENT;
        }

    if (handle->header.gsd_version < gsd_make_version(2, 0))
        {
        if (handle->file_index.size > 0)
            {
            // make a copy of the file index
            struct gsd_index_buffer buf;
            gsd_util_zero_memory(&buf, sizeof(struct gsd_index_buffer));
            int retval = gsd_index_buffer_allocate(&buf, handle->file_index.size);
            if (retval != GSD_SUCCESS)
                {
                return retval;
                }
            memcpy(buf.data,
                   handle->file_index.data,
                   sizeof(struct gsd_index_entry) * handle->file_index.size);
            buf.size = handle->file_index.size;

            // sort the copy and write it back out to the file
            retval = gsd_index_buffer_sort(&buf);
            if (retval != GSD_SUCCESS)
                {
                gsd_index_buffer_free(&buf);
                return retval;
                }

            ssize_t bytes_written = gsd_io_pwrite_retry(handle->fd,
                                                        buf.data,
                                                        sizeof(struct gsd_index_entry) * buf.size,
                                                        handle->header.index_location);

            if (bytes_written == -1 || bytes_written != sizeof(struct gsd_index_entry) * buf.size)
                {
                gsd_index_buffer_free(&buf);
                return GSD_ERROR_IO;
                }

            retval = gsd_index_buffer_free(&buf);
            if (retval != GSD_SUCCESS)
                {
                return retval;
                }

            // sync the updated index
            retval = fsync(handle->fd);
            if (retval != 0)
                {
                return GSD_ERROR_IO;
                }
            }

        if (handle->file_names.n_names > 0)
            {
            // compact the name list without changing its size or position on the disk
            struct gsd_byte_buffer new_name_buf;
            gsd_util_zero_memory(&new_name_buf, sizeof(struct gsd_byte_buffer));
            int retval = gsd_byte_buffer_allocate(&new_name_buf, handle->file_names.data.reserved);
            if (retval != GSD_SUCCESS)
                {
                return retval;
                }

            const char* name = gsd_find_matching_chunk_name(handle, "", NULL);
            while (name != NULL)
                {
                retval = gsd_byte_buffer_append(&new_name_buf, name, strlen(name) + 1);
                if (retval != GSD_SUCCESS)
                    {
                    gsd_byte_buffer_free(&new_name_buf);
                    return retval;
                    }
                name = gsd_find_matching_chunk_name(handle, "", name);
                }

            if (new_name_buf.reserved != handle->file_names.data.reserved)
                {
                gsd_byte_buffer_free(&new_name_buf);
                return GSD_ERROR_FILE_CORRUPT;
                }

            // write the new names out to disk
            ssize_t bytes_written = gsd_io_pwrite_retry(handle->fd,
                                                        new_name_buf.data,
                                                        new_name_buf.reserved,
                                                        handle->header.namelist_location);

            if (bytes_written == -1 || bytes_written != new_name_buf.reserved)
                {
                gsd_byte_buffer_free(&new_name_buf);
                return GSD_ERROR_IO;
                }

            // swap in the re-organized name buffer
            retval = gsd_byte_buffer_free(&handle->file_names.data);
            if (retval != GSD_SUCCESS)
                {
                gsd_byte_buffer_free(&new_name_buf);
                return retval;
                }
            handle->file_names.data = new_name_buf;

            // sync the updated name list
            retval = fsync(handle->fd);
            if (retval != 0)
                {
                gsd_byte_buffer_free(&new_name_buf);
                return GSD_ERROR_IO;
                }
            }

        // label the file as a v2.0 file
        handle->header.gsd_version = gsd_make_version(GSD_CURRENT_FILE_VERSION, 0);

        // write the new header out
        ssize_t bytes_written
            = gsd_io_pwrite_retry(handle->fd, &(handle->header), sizeof(struct gsd_header), 0);
        if (bytes_written != sizeof(struct gsd_header))
            {
            return GSD_ERROR_IO;
            }

        // sync the updated header
        int retval = fsync(handle->fd);
        if (retval != 0)
            {
            return GSD_ERROR_IO;
            }

        // remap the file index
        retval = gsd_index_buffer_free(&handle->file_index);
        if (retval != 0)
            {
            return retval;
            }

        retval = gsd_index_buffer_map(&handle->file_index, handle);
        if (retval != 0)
            {
            return retval;
            }
        }

    return GSD_SUCCESS;
    }

// undefine windows wrapper macros
#ifdef _WIN32
#undef lseek
#undef write
#undef read
#undef open
#undef ftruncate
#pragma warning(pop)

#endif