-
Notifications
You must be signed in to change notification settings - Fork 2
/
gsd.c
2468 lines (2084 loc) · 67.6 KB
/
gsd.c
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
// Copyright (c) 2016-2021 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;
}