-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathembedDB.c
More file actions
8029 lines (7021 loc) · 317 KB
/
Copy pathembedDB.c
File metadata and controls
8029 lines (7021 loc) · 317 KB
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
#include "./embedDB.h"
/******************************************************************************/
/**
* @file EmbedDB-Amalgamation
* @author EmbedDB Team (See Authors.md)
* @brief Source code amalgamated into one file for easy distribution
* @copyright Copyright 2024
* EmbedDB Team
* @par Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* @par 1.Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* @par 2.Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* @par 3.Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* @par THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/******************************************************************************/
/************************************************************spline.c************************************************************/
/******************************************************************************/
/**
* @file spline.c
* @author EmbedDB Team (See Authors.md)
* @brief Implementation of spline.
* @copyright Copyright 2024
* EmbedDB Team
* @par Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* @par 1.Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* @par 2.Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* @par 3.Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* @par THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/******************************************************************************/
#if defined(ARDUINO)
#endif
/**
* @brief Initialize a spline structure with given maximum size and error.
* @param spl Spline structure
* @param size Maximum size of spline
* @param maxError Maximum error allowed in spline
* @param keySize Size of key in bytes
*/
void splineInit(spline *spl, id_t size, size_t maxError, uint8_t keySize) {
uint8_t pointSize = sizeof(uint32_t) + keySize;
spl->count = 0;
spl->pointsStartIndex = 0;
spl->eraseSize = 1;
spl->size = size;
spl->maxError = maxError;
spl->points = (void *)malloc(pointSize * size);
spl->tempLastPoint = 0;
spl->keySize = keySize;
spl->lastKey = malloc(keySize);
spl->lower = malloc(pointSize);
spl->upper = malloc(pointSize);
spl->firstSplinePoint = malloc(pointSize);
spl->numAddCalls = 0;
}
/**
* @brief Check if first line is to the left (counter-clockwise) of the second.
*/
static inline int8_t splineIsLeft(uint64_t x1, int64_t y1, uint64_t x2, int64_t y2) {
return y1 * x2 > y2 * x1;
}
/**
* @brief Check if first line is to the right (clockwise) of the second.
*/
static inline int8_t splineIsRight(uint64_t x1, int64_t y1, uint64_t x2, int64_t y2) {
return y1 * x2 < y2 * x1;
}
/**
* @brief Adds point to spline structure
* @param spl Spline structure
* @param key Data key to be added (must be incrementing)
* @param page Page number for spline point to add
*/
void splineAdd(spline *spl, void *key, uint32_t page) {
spl->numAddCalls++;
/* Check if no spline points are currently empty */
if (spl->numAddCalls == 1) {
/* Add first point in data set to spline. */
void *firstPoint = splinePointLocation(spl, 0);
memcpy(firstPoint, key, spl->keySize);
memcpy(((int8_t *)firstPoint + spl->keySize), &page, sizeof(uint32_t));
/* Log first point for wrap around purposes */
memcpy(spl->firstSplinePoint, key, spl->keySize);
memcpy(((int8_t *)spl->firstSplinePoint + spl->keySize), &page, sizeof(uint32_t));
spl->count++;
memcpy(spl->lastKey, key, spl->keySize);
return;
}
/* Check if there is only one spline point (need to initialize upper and lower limits using 2nd point) */
if (spl->numAddCalls == 2) {
/* Initialize upper and lower limits using second (unique) data point */
memcpy(spl->lower, key, spl->keySize);
uint32_t lowerPage = page < spl->maxError ? 0 : page - spl->maxError;
memcpy(((int8_t *)spl->lower + spl->keySize), &lowerPage, sizeof(uint32_t));
memcpy(spl->upper, key, spl->keySize);
uint32_t upperPage = page + spl->maxError;
memcpy(((int8_t *)spl->upper + spl->keySize), &upperPage, sizeof(uint32_t));
memcpy(spl->lastKey, key, spl->keySize);
spl->lastLoc = page;
}
/* Skip duplicates */
uint64_t keyVal = 0, lastKeyVal = 0;
memcpy(&keyVal, key, spl->keySize);
memcpy(&lastKeyVal, spl->lastKey, spl->keySize);
if (keyVal <= lastKeyVal && spl->numAddCalls != 2)
return;
/* Last point added to spline, check if previous point is temporary - overwrite previous point if temporary */
if (spl->tempLastPoint != 0) {
spl->count--;
}
uint32_t lastPage = 0;
uint64_t lastPointKey = 0, upperKey = 0, lowerKey = 0;
void *lastPointLocation = splinePointLocation(spl, spl->count - 1);
memcpy(&lastPointKey, lastPointLocation, spl->keySize);
memcpy(&upperKey, spl->upper, spl->keySize);
memcpy(&lowerKey, spl->lower, spl->keySize);
memcpy(&lastPage, (int8_t *)lastPointLocation + spl->keySize, sizeof(uint32_t));
uint64_t xdiff, upperXDiff, lowerXDiff = 0;
uint32_t ydiff, upperYDiff = 0;
int64_t lowerYDiff = 0; /* This may be negative */
xdiff = keyVal - lastPointKey;
ydiff = page - lastPage;
upperXDiff = upperKey - lastPointKey;
memcpy(&upperYDiff, (int8_t *)spl->upper + spl->keySize, sizeof(uint32_t));
upperYDiff -= lastPage;
lowerXDiff = lowerKey - lastPointKey;
memcpy(&lowerYDiff, (int8_t *)spl->lower + spl->keySize, sizeof(uint32_t));
lowerYDiff -= lastPage;
if (spl->count >= spl->size) {
int8_t eraseResult = splineErase(spl, spl->eraseSize);
}
/* Check if next point still in error corridor */
if (splineIsLeft(xdiff, ydiff, upperXDiff, upperYDiff) == 1 ||
splineIsRight(xdiff, ydiff, lowerXDiff, lowerYDiff) == 1) {
/* Point is not in error corridor. Add previous point to spline. */
void *nextSplinePoint = splinePointLocation(spl, spl->count);
memcpy(nextSplinePoint, spl->lastKey, spl->keySize);
memcpy((int8_t *)nextSplinePoint + spl->keySize, &spl->lastLoc, sizeof(uint32_t));
spl->count++;
spl->tempLastPoint = 0;
/* Update upper and lower limits. */
memcpy(spl->lower, key, spl->keySize);
uint32_t lowerPage = page < spl->maxError ? 0 : page - spl->maxError;
memcpy((int8_t *)spl->lower + spl->keySize, &lowerPage, sizeof(uint32_t));
memcpy(spl->upper, key, spl->keySize);
uint32_t upperPage = page + spl->maxError;
memcpy((int8_t *)spl->upper + spl->keySize, &upperPage, sizeof(uint32_t));
/* If we add a point, we might need to erase again */
if (spl->count >= spl->size) {
int8_t eraseResult = splineErase(spl, spl->eraseSize);
}
} else {
/* Check if must update upper or lower limits */
/* Upper limit */
if (splineIsLeft(upperXDiff, upperYDiff, xdiff, page + spl->maxError - lastPage) == 1) {
memcpy(spl->upper, key, spl->keySize);
uint32_t upperPage = page + spl->maxError;
memcpy((int8_t *)spl->upper + spl->keySize, &upperPage, sizeof(uint32_t));
}
/* Lower limit */
if (splineIsRight(lowerXDiff, lowerYDiff, xdiff, (page < spl->maxError ? 0 : page - spl->maxError) - lastPage) == 1) {
memcpy(spl->lower, key, spl->keySize);
uint32_t lowerPage = page < spl->maxError ? 0 : page - spl->maxError;
memcpy((int8_t *)spl->lower + spl->keySize, &lowerPage, sizeof(uint32_t));
}
}
spl->lastLoc = page;
/* Add last key on spline if not already there. */
/* This will get overwritten the next time a new spline point is added */
memcpy(spl->lastKey, key, spl->keySize);
void *tempSplinePoint = splinePointLocation(spl, spl->count);
memcpy(tempSplinePoint, spl->lastKey, spl->keySize);
memcpy((int8_t *)tempSplinePoint + spl->keySize, &spl->lastLoc, sizeof(uint32_t));
spl->count++;
spl->tempLastPoint = 1;
}
/**
* @brief Removes points from the spline
* @param spl The spline structure to search
* @param numPoints The number of points to remove from the spline
* @return Returns zero if successful and one if not
*/
int splineErase(spline *spl, uint32_t numPoints) {
/* If the user tries to delete more points than they allocated or deleting would only leave one spline point */
if (numPoints > spl->count || spl->count - numPoints == 1)
return 1;
if (numPoints == 0)
return 0;
spl->count -= numPoints;
spl->pointsStartIndex = (spl->pointsStartIndex + numPoints) % spl->size;
if (spl->count == 0)
spl->numAddCalls = 0;
return 0;
}
/**
* @brief Builds a spline structure given a sorted data set. GreedySplineCorridor
* implementation from "Smooth interpolating histograms with error guarantees"
* (BNCOD'08) by T. Neumann and S. Michel.
* @param spl Spline structure
* @param data Array of sorted data
* @param size Number of values in array
* @param maxError Maximum error for each spline
*/
void splineBuild(spline *spl, void **data, id_t size, size_t maxError) {
spl->maxError = maxError;
for (id_t i = 0; i < size; i++) {
void *key;
memcpy(&key, data + i, sizeof(void *));
splineAdd(spl, key, i);
}
}
/**
* @brief Print a spline structure.
* @param spl Spline structure
*/
void splinePrint(spline *spl) {
if (spl == NULL) {
printf("No spline to print.\n");
return;
}
printf("Spline max error (%u):\n", spl->maxError);
printf("Spline points (%lu):\n", spl->count);
uint64_t keyVal = 0;
uint32_t page = 0;
for (id_t i = 0; i < spl->count; i++) {
void *point = splinePointLocation(spl, i);
memcpy(&keyVal, point, spl->keySize);
memcpy(&page, (int8_t *)point + spl->keySize, sizeof(uint32_t));
printf("[%u]: (%lu, %d)\n", i, keyVal, page);
}
printf("\n");
}
/**
* @brief Return spline structure size in bytes.
* @param spl Spline structure
* @return size of the spline in bytes
*/
uint32_t splineSize(spline *spl) {
return sizeof(spline) + (spl->size * (spl->keySize + sizeof(uint32_t)));
}
/**
* @brief Performs a recursive binary search on the spine points for a key
* @param arr Array of spline points to search through
* @param low Lower search bound (Index of spline point)
* @param high Higher search bound (Index of spline point)
* @param key Key to search for
* @param compareKey Function to compare keys
* @return Index of spline point that is the upper end of the spline segment that contains the key
*/
size_t pointsBinarySearch(spline *spl, int low, int high, void *key, int8_t compareKey(void *, void *)) {
int32_t mid;
if (high >= low) {
mid = low + (high - low) / 2;
// If mid is zero, then low = 0 and high = 1. Therefore there is only one spline segment and we return 1, the upper bound.
if (mid == 0) {
return 1;
}
void *midSplinePoint = splinePointLocation(spl, mid);
void *midSplineMinusOnePoint = splinePointLocation(spl, mid - 1);
if (compareKey(midSplinePoint, key) >= 0 && compareKey(midSplineMinusOnePoint, key) <= 0)
return mid;
if (compareKey(midSplinePoint, key) > 0)
return pointsBinarySearch(spl, low, mid - 1, key, compareKey);
return pointsBinarySearch(spl, mid + 1, high, key, compareKey);
}
mid = low + (high - low) / 2;
if (mid >= high) {
return high;
} else {
return low;
}
}
/**
* @brief Estimate the page number of a given key
* @param spl The spline structure to search
* @param key The key to search for
* @param compareKey Function to compare keys
* @param loc A return value for the best estimate of which page the key is on
* @param low A return value for the smallest page that it could be on
* @param high A return value for the largest page it could be on
*/
void splineFind(spline *spl, void *key, int8_t compareKey(void *, void *), id_t *loc, id_t *low, id_t *high) {
size_t pointIdx;
uint64_t keyVal = 0, smallestKeyVal = 0, largestKeyVal = 0;
void *smallestSplinePoint = splinePointLocation(spl, 0);
void *largestSplinePoint = splinePointLocation(spl, spl->count - 1);
memcpy(&keyVal, key, spl->keySize);
memcpy(&smallestKeyVal, smallestSplinePoint, spl->keySize);
memcpy(&largestKeyVal, largestSplinePoint, spl->keySize);
if (compareKey(key, splinePointLocation(spl, 0)) < 0 || spl->count <= 1) {
// Key is smaller than any we have on record
uint32_t lowEstimate, highEstimate, locEstimate = 0;
memcpy(&lowEstimate, (int8_t *)spl->firstSplinePoint + spl->keySize, sizeof(uint32_t));
memcpy(&highEstimate, (int8_t *)smallestSplinePoint + spl->keySize, sizeof(uint32_t));
locEstimate = (lowEstimate + highEstimate) / 2;
memcpy(loc, &locEstimate, sizeof(uint32_t));
memcpy(low, &lowEstimate, sizeof(uint32_t));
memcpy(high, &highEstimate, sizeof(uint32_t));
return;
} else if (compareKey(key, splinePointLocation(spl, spl->count - 1)) > 0) {
memcpy(loc, (int8_t *)largestSplinePoint + spl->keySize, sizeof(uint32_t));
memcpy(low, (int8_t *)largestSplinePoint + spl->keySize, sizeof(uint32_t));
memcpy(high, (int8_t *)largestSplinePoint + spl->keySize, sizeof(uint32_t));
return;
} else {
// Perform a binary seach to find the spline point above the key we're looking for
pointIdx = pointsBinarySearch(spl, 0, spl->count - 1, key, compareKey);
}
// Interpolate between two spline points
void *downKey = splinePointLocation(spl, pointIdx - 1);
uint32_t downPage = 0;
memcpy(&downPage, (int8_t *)downKey + spl->keySize, sizeof(uint32_t));
void *upKey = splinePointLocation(spl, pointIdx);
uint32_t upPage = 0;
memcpy(&upPage, (int8_t *)upKey + spl->keySize, sizeof(uint32_t));
uint64_t downKeyVal = 0, upKeyVal = 0;
memcpy(&downKeyVal, downKey, spl->keySize);
memcpy(&upKeyVal, upKey, spl->keySize);
// Estimate location as page number
// Keydiff * slope + y
id_t locationEstimate = (id_t)((keyVal - downKeyVal) * (upPage - downPage) / (long double)(upKeyVal - downKeyVal)) + downPage;
memcpy(loc, &locationEstimate, sizeof(id_t));
// Set error bounds based on maxError from spline construction
id_t lowEstiamte = (spl->maxError > locationEstimate) ? 0 : locationEstimate - spl->maxError;
memcpy(low, &lowEstiamte, sizeof(id_t));
void *lastSplinePoint = splinePointLocation(spl, spl->count - 1);
uint32_t lastSplinePointPage = 0;
memcpy(&lastSplinePointPage, (int8_t *)lastSplinePoint + spl->keySize, sizeof(uint32_t));
id_t highEstimate = (locationEstimate + spl->maxError > lastSplinePointPage) ? lastSplinePointPage : locationEstimate + spl->maxError;
memcpy(high, &highEstimate, sizeof(id_t));
}
/**
* @brief Free memory allocated for spline structure.
* @param spl Spline structure
*/
void splineClose(spline *spl) {
free(spl->points);
free(spl->lastKey);
free(spl->lower);
free(spl->upper);
free(spl->firstSplinePoint);
}
/**
* @brief Returns a pointer to the location of the specified spline point in memory. Note that this method does not check if there is a point there, so it may be garbage data.
* @param spl The spline structure that contains the points
* @param pointIndex The index of the point to return a pointer to
*/
void *splinePointLocation(spline *spl, size_t pointIndex) {
return (int8_t *)spl->points + (((pointIndex + spl->pointsStartIndex) % spl->size) * (spl->keySize + sizeof(uint32_t)));
}
/************************************************************embedDB.c************************************************************/
/******************************************************************************/
/**
* @file embedDB.c
* @author EmbedDB Team (See Authors.md)
* @brief Source code for EmbedDB.
* @copyright Copyright 2024
* EmbedDB Team
* @par Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* @par 1.Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* @par 2.Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* @par 3.Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* @par THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/******************************************************************************/
#if defined(ARDUINO)
#endif
/* Helper Functions */
int8_t embedDBInitData(embedDBState *state);
int8_t embedDBInitDataFromFile(embedDBState *state);
int8_t embedDBInitDataFromFileWithRecordLevelConsistency(embedDBState *state);
int8_t embedDBInitIndex(embedDBState *state);
int8_t embedDBInitIndexFromFile(embedDBState *state);
int8_t embedDBInitVarData(embedDBState *state);
int8_t embedDBInitVarDataFromFile(embedDBState *state);
int8_t shiftRecordLevelConsistencyBlocks(embedDBState *state);
void embedDBInitSplineFromFile(embedDBState *state);
int32_t getMaxError(embedDBState *state, void *buffer);
void updateMaximumError(embedDBState *state, void *buffer);
int8_t embedDBSetupVarDataStream(embedDBState *state, void *key, embedDBVarDataStream **varData, id_t recordNumber);
uint32_t cleanSpline(embedDBState *state, uint32_t minPageNumber);
void readToWriteBuf(embedDBState *state);
void readToWriteBufVar(embedDBState *state);
void printBitmap(char *bm) {
for (int8_t i = 0; i <= 7; i++) {
printf(" " BYTE_TO_BINARY_PATTERN "", BYTE_TO_BINARY(*(bm + i)));
}
printf("\n");
}
/**
* @brief Determine if two bitmaps have any overlapping bits
* @return 1 if there is any overlap, else 0
*/
int8_t bitmapOverlap(uint8_t *bm1, uint8_t *bm2, int8_t size) {
for (int8_t i = 0; i < size; i++)
if ((*((uint8_t *)(bm1 + i)) & *((uint8_t *)(bm2 + i))) >= 1)
return 1;
return 0;
}
void initBufferPage(embedDBState *state, int pageNum) {
/* Initialize page */
uint16_t i = 0;
void *buf = (char *)state->buffer + pageNum * state->pageSize;
for (i = 0; i < state->pageSize; i++) {
((int8_t *)buf)[i] = 0;
}
if (pageNum != EMBEDDB_VAR_WRITE_BUFFER(state->parameters)) {
/* Initialize header key min. Max and sum is already set to zero by the
* for-loop above */
void *min = EMBEDDB_GET_MIN_KEY(buf);
/* Initialize min to all 1s */
for (i = 0; i < state->keySize; i++) {
((int8_t *)min)[i] = 1;
}
/* Initialize data min. */
min = EMBEDDB_GET_MIN_DATA(buf, state);
/* Initialize min to all 1s */
for (i = 0; i < state->dataSize; i++) {
((int8_t *)min)[i] = 1;
}
}
}
/**
* @brief Return the smallest key in the node
* @param state embedDB algorithm state structure
* @param buffer In memory page buffer with node data
*/
void *embedDBGetMinKey(embedDBState *state, void *buffer) {
return (void *)((int8_t *)buffer + state->headerSize);
}
/**
* @brief Return the largest key in the node
* @param state embedDB algorithm state structure
* @param buffer In memory page buffer with node data
*/
void *embedDBGetMaxKey(embedDBState *state, void *buffer) {
int16_t count = EMBEDDB_GET_COUNT(buffer);
return (void *)((int8_t *)buffer + state->headerSize + (count - 1) * state->recordSize);
}
/**
* @brief Initialize embedDB structure.
* @param state embedDB algorithm state structure
* @param indexMaxError max error of indexing structure (spline)
* @return Return 0 if success. Non-zero value if error.
*/
int8_t embedDBInit(embedDBState *state, size_t indexMaxError) {
if (state->keySize > 8) {
#ifdef PRINT_ERRORS
printf("ERROR: Key size is too large. Max key size is 8 bytes.\n");
#endif
return -1;
}
/* check the number of allocated pages is a multiple of the erase size */
if (state->numDataPages % state->eraseSizeInPages != 0) {
#ifdef PRINT_ERRORS
printf("ERROR: The number of allocated data pages must be divisible by the erase size in pages.\n");
#endif
return -1;
}
if (state->numDataPages < (EMBEDDB_USING_RECORD_LEVEL_CONSISTENCY(state->parameters) ? 4 : 2) * state->eraseSizeInPages) {
#ifdef PRINT_ERRORS
printf("ERROR: The minimum number of data pages is twice the eraseSizeInPages or 4 times the eraseSizeInPages if using record-level consistency.\n");
#endif
return -1;
}
state->recordSize = state->keySize + state->dataSize;
if (EMBEDDB_USING_VDATA(state->parameters)) {
if (state->numVarPages % state->eraseSizeInPages != 0) {
#ifdef PRINT_ERRORS
printf("ERROR: The number of allocated variable data pages must be divisible by the erase size in pages.\n");
#endif
return -1;
}
state->recordSize += 4;
}
state->indexMaxError = indexMaxError;
/* Calculate block header size */
/* Header size depends on bitmap size: 6 + X bytes: 4 byte id, 2 for record count, X for bitmap. */
state->headerSize = 6;
if (EMBEDDB_USING_INDEX(state->parameters)) {
if (state->numIndexPages % state->eraseSizeInPages != 0) {
#ifdef PRINT_ERRORS
printf("ERROR: The number of allocated index pages must be divisible by the erase size in pages.\n");
#endif
return -1;
}
state->headerSize += state->bitmapSize;
}
if (EMBEDDB_USING_MAX_MIN(state->parameters))
state->headerSize += state->keySize * 2 + state->dataSize * 2;
/* Flags to show that these values have not been initalized with actual data yet */
state->bufferedPageId = -1;
state->bufferedIndexPageId = -1;
state->bufferedVarPage = -1;
/* Calculate number of records per page */
state->maxRecordsPerPage = (state->pageSize - state->headerSize) / state->recordSize;
/* Initialize max error to maximum records per page */
state->maxError = state->maxRecordsPerPage;
/* Allocate first page of buffer as output page */
initBufferPage(state, 0);
if (state->numDataPages < (EMBEDDB_USING_INDEX(state->parameters) * 2 + 2) * state->eraseSizeInPages) {
#ifdef PRINT_ERRORS
printf("ERROR: Number of pages allocated must be at least twice erase block size for embedDB and four times when using indexing. Memory pages: %d\n", state->numDataPages);
#endif
return -1;
}
/* Initialize the spline structure if being used */
if (!EMBEDDB_USING_BINARY_SEARCH(state->parameters)) {
if (state->numSplinePoints < 4) {
#ifdef PRINT_ERRORS
printf("ERROR: Unable to setup spline with less than 4 points.");
#endif
return -1;
}
state->spl = malloc(sizeof(spline));
splineInit(state->spl, state->numSplinePoints, indexMaxError, state->keySize);
}
/* Allocate file for data*/
int8_t dataInitResult = 0;
dataInitResult = embedDBInitData(state);
if (dataInitResult != 0) {
return dataInitResult;
}
/* Allocate file and buffer for index */
int8_t indexInitResult = 0;
if (EMBEDDB_USING_INDEX(state->parameters)) {
if (state->bufferSizeInBlocks < 4) {
#ifdef PRINT_ERRORS
printf("ERROR: embedDB using index requires at least 4 page buffers.\n");
#endif
return -1;
} else {
indexInitResult = embedDBInitIndex(state);
}
} else {
state->indexFile = NULL;
state->numIndexPages = 0;
}
if (indexInitResult != 0) {
return indexInitResult;
}
/* Allocate file and buffer for variable data */
int8_t varDataInitResult = 0;
if (EMBEDDB_USING_VDATA(state->parameters)) {
if (state->bufferSizeInBlocks < 4 + (EMBEDDB_USING_INDEX(state->parameters) ? 2 : 0)) {
#ifdef PRINT_ERRORS
printf("ERROR: embedDB using variable records requires at least 4 page buffers if there is no index and 6 if there is.\n");
#endif
return -1;
} else {
varDataInitResult = embedDBInitVarData(state);
}
return varDataInitResult;
} else {
state->varFile = NULL;
state->numVarPages = 0;
}
embedDBResetStats(state);
return 0;
}
int8_t embedDBInitData(embedDBState *state) {
state->nextDataPageId = 0;
state->nextDataPageId = 0;
state->numAvailDataPages = state->numDataPages;
state->minDataPageId = 0;
if (state->dataFile == NULL) {
#ifdef PRINT_ERRORS
printf("ERROR: No data file provided!\n");
#endif
return -1;
}
if (EMBEDDB_USING_RECORD_LEVEL_CONSISTENCY(state->parameters)) {
state->numAvailDataPages -= (state->eraseSizeInPages * 2);
state->nextRLCPhysicalPageLocation = state->eraseSizeInPages;
state->rlcPhysicalStartingPage = state->eraseSizeInPages;
}
/* Setup data file. */
int8_t openStatus = 0;
if (!EMBEDDB_RESETING_DATA(state->parameters)) {
openStatus = state->fileInterface->open(state->dataFile, EMBEDDB_FILE_MODE_R_PLUS_B);
if (openStatus) {
if (EMBEDDB_USING_RECORD_LEVEL_CONSISTENCY(state->parameters)) {
return embedDBInitDataFromFileWithRecordLevelConsistency(state);
} else {
return embedDBInitDataFromFile(state);
}
}
} else {
openStatus = state->fileInterface->open(state->dataFile, EMBEDDB_FILE_MODE_W_PLUS_B);
}
if (!openStatus) {
#ifdef PRINT_ERRORS
printf("Error: Can't open data file!\n");
#endif
return -1;
}
return 0;
}
int8_t embedDBInitDataFromFile(embedDBState *state) {
id_t logicalPageId = 0;
id_t maxLogicalPageId = 0;
id_t physicalPageId = 0;
uint32_t count = 0;
count_t blockSize = state->eraseSizeInPages;
bool validData = false;
bool hasData = false;
void *buffer = (int8_t *)state->buffer + state->pageSize * EMBEDDB_DATA_READ_BUFFER;
/* This will become zero if there is no more to read */
int8_t moreToRead = !(readPage(state, physicalPageId));
/* this handles the case where the first page may have been erased, so has junk data and we actually need to start from the second page */
uint32_t i = 0;
int8_t numRecords = 0;
while (moreToRead && i < 2) {
memcpy(&logicalPageId, buffer, sizeof(id_t));
validData = logicalPageId % state->numDataPages == count;
numRecords = EMBEDDB_GET_COUNT(buffer);
if (validData && numRecords > 0 && numRecords < state->maxRecordsPerPage + 1) {
hasData = true;
maxLogicalPageId = logicalPageId;
physicalPageId++;
updateMaximumError(state, buffer);
count++;
i = 2;
} else {
physicalPageId += blockSize;
count += blockSize;
}
moreToRead = !(readPage(state, physicalPageId));
i++;
}
/* if we have no valid data, we just have an empty file can can start from the scratch */
if (!hasData)
return 0;
while (moreToRead && count < state->numDataPages) {
memcpy(&logicalPageId, buffer, sizeof(id_t));
validData = logicalPageId % state->numDataPages == count;
if (validData && logicalPageId == maxLogicalPageId + 1) {
maxLogicalPageId = logicalPageId;
physicalPageId++;
updateMaximumError(state, buffer);
moreToRead = !(readPage(state, physicalPageId));
count++;
} else {
break;
}
}
/*
* Now we need to find where the page with the smallest key that is still valid.
* The default case is we have not wrapped and the page number for the physical page with the smallest key is 0.
*/
id_t physicalPageIDOfSmallestData = 0;
/* check if data exists at this location */
if (moreToRead && count < state->numDataPages) {
/* find where the next block boundary is */
id_t pagesToBlockBoundary = blockSize - (count % blockSize);
/* go to the next block boundary */
physicalPageId = (physicalPageId + pagesToBlockBoundary) % state->numDataPages;
moreToRead = !(readPage(state, physicalPageId));
/* there should have been more to read because the file should not be empty at this point if it was not empty at the previous block */
if (!moreToRead) {
return -1;
}
/* check if data is valid or if it is junk */
memcpy(&logicalPageId, buffer, sizeof(id_t));
validData = logicalPageId % state->numDataPages == physicalPageId;
/* this means we have wrapped and our start is actually here */
if (validData) {
physicalPageIDOfSmallestData = physicalPageId;
}
}
state->nextDataPageId = maxLogicalPageId + 1;
readPage(state, physicalPageIDOfSmallestData);
memcpy(&(state->minDataPageId), buffer, sizeof(id_t));
state->numAvailDataPages = state->numDataPages + state->minDataPageId - maxLogicalPageId - 1;
/* Put largest key back into the buffer */
readPage(state, (state->nextDataPageId - 1) % state->numDataPages);
if (!EMBEDDB_USING_BINARY_SEARCH(state->parameters)) {
embedDBInitSplineFromFile(state);
}
return 0;
}
int8_t embedDBInitDataFromFileWithRecordLevelConsistency(embedDBState *state) {
id_t logicalPageId = 0;
id_t maxLogicalPageId = 0;
id_t physicalPageId = 0;
uint32_t count = 0;
count_t blockSize = state->eraseSizeInPages;
bool validData = false;
bool hasPermanentData = false;
void *buffer = (int8_t *)state->buffer + state->pageSize * EMBEDDB_DATA_READ_BUFFER;
/* This will become zero if there is no more to read */
int8_t moreToRead = !(readPage(state, physicalPageId));
/* This handles the case that the first three pages may not have valid data in them.
* They may be either an erased page or pages for record-level consistency.
*/
uint32_t i = 0;
int8_t numRecords = 0;
while (moreToRead && i < 4) {
memcpy(&logicalPageId, buffer, sizeof(id_t));
validData = logicalPageId % state->numDataPages == count;
numRecords = EMBEDDB_GET_COUNT(buffer);
if (validData && numRecords > 0 && numRecords < state->maxRecordsPerPage + 1) {
/* Setup for next loop so it does not have to worry about setting the initial values */
hasPermanentData = true;
maxLogicalPageId = logicalPageId;
physicalPageId++;
updateMaximumError(state, buffer);
count++;
i = 4;
} else {
physicalPageId += blockSize;
count += blockSize;
}
moreToRead = !(readPage(state, physicalPageId));
i++;
}
if (hasPermanentData) {
while (moreToRead && count < state->numDataPages) {
memcpy(&logicalPageId, buffer, sizeof(id_t));
validData = logicalPageId % state->numDataPages == count;
if (validData && logicalPageId == maxLogicalPageId + 1) {
maxLogicalPageId = logicalPageId;
physicalPageId++;
updateMaximumError(state, buffer);
moreToRead = !(readPage(state, physicalPageId));
count++;
} else {
break;
}
}
} else {
/* Case where the there is no permanent pages written, but we may still have record-level consistency records in block 2 */
count = 0;
physicalPageId = 0;
}
/* find where the next block boundary is */
id_t pagesToBlockBoundary = blockSize - (count % blockSize);
/* if we are on a block-boundary, we erase the next page in case the erase failed and then skip to the start of the next block */
if (pagesToBlockBoundary == blockSize) {
int8_t eraseSuccess = state->fileInterface->erase(count, count + blockSize, state->pageSize, state->dataFile);
if (!eraseSuccess) {
#ifdef PRINT_ERRORS
printf("Error: Unable to erase data page during recovery!\n");
#endif
return -1;
}
}
/* go to the next block boundary */
physicalPageId = (physicalPageId + pagesToBlockBoundary) % state->numDataPages;
state->rlcPhysicalStartingPage = physicalPageId;
state->nextRLCPhysicalPageLocation = physicalPageId;
/* record-level consistency recovery algorithm */
uint32_t numPagesRead = 0;
uint32_t numPagesToRead = blockSize * 2;
uint32_t rlcMaxLogicalPageNumber = UINT32_MAX;
uint32_t rlcMaxRecordCount = UINT32_MAX;
uint32_t rlcMaxPage = UINT32_MAX;
moreToRead = !(readPage(state, physicalPageId));
while (moreToRead && numPagesRead < numPagesToRead) {
memcpy(&logicalPageId, buffer, sizeof(id_t));
/* If the next logical page number is not the one after the max data page, we can just skip to the next page.
* We also need to read the page if there are no permanent records but the logicalPageId is zero, as this indicates we have record-level consistency records
*/
if (logicalPageId == maxLogicalPageId + 1 || (logicalPageId == 0 && !hasPermanentData)) {
uint32_t numRecords = EMBEDDB_GET_COUNT(buffer);
if (rlcMaxRecordCount == UINT32_MAX || numRecords > rlcMaxRecordCount) {
rlcMaxRecordCount = numRecords;
rlcMaxLogicalPageNumber = logicalPageId;
rlcMaxPage = numPagesRead;
}
}
physicalPageId = (physicalPageId + 1) % state->numDataPages;
moreToRead = !(readPage(state, physicalPageId));
numPagesRead++;
}
/* need to find large record-level consistency page to place back into the buffer and either one or both of the record-level consistency pages */
uint32_t eraseStartingPage = 0;
uint32_t eraseEndingPage = 0;
uint32_t numBlocksToErase = 0;
if (rlcMaxLogicalPageNumber == UINT32_MAX) {
eraseStartingPage = state->rlcPhysicalStartingPage % state->numDataPages;
numBlocksToErase = 2;
} else {
state->nextRLCPhysicalPageLocation = (state->rlcPhysicalStartingPage + rlcMaxPage + 1) % state->numDataPages;
/* need to read the max page into read buffer again so we can copy into the write buffer */
int8_t readSuccess = readPage(state, (state->rlcPhysicalStartingPage + rlcMaxPage) % state->numDataPages);
if (readSuccess != 0) {
#ifdef PRINT_ERRORS
printf("Error: Can't read page in data file that was previously read!\n");
#endif
return -1;
}
memcpy(state->buffer, buffer, state->pageSize);
eraseStartingPage = (state->rlcPhysicalStartingPage + (rlcMaxPage < blockSize ? blockSize : 0)) % state->numDataPages;
numBlocksToErase = 1;
}
for (uint32_t i = 0; i < numBlocksToErase; i++) {
eraseEndingPage = eraseStartingPage + blockSize;
int8_t eraseSuccess = state->fileInterface->erase(eraseStartingPage, eraseEndingPage, state->pageSize, state->dataFile);
if (!eraseSuccess) {
#ifdef PRINT_ERRORS
printf("Error: Unable to erase pages in data file!\n");
#endif
return -1;
}
eraseStartingPage = eraseEndingPage % state->numDataPages;
}
/* if we don't have any permanent data, we can just return now that the record-level consistency records have been handled */
if (!hasPermanentData) {
return 0;
}
/* Now check if we have wrapped after the record level consistency.
* The default case is we start at beginning of data file.
*/
id_t physicalPageIDOfSmallestData = 0;
physicalPageId = (state->rlcPhysicalStartingPage + 2 * blockSize) % state->numDataPages;
int8_t readSuccess = readPage(state, physicalPageId);
if (readSuccess == 0) {
memcpy(&logicalPageId, buffer, sizeof(id_t));
validData = logicalPageId % state->numDataPages == physicalPageId;
/* this means we have wrapped and our start is actually here */
if (validData) {
physicalPageIDOfSmallestData = physicalPageId;
}
}
state->nextDataPageId = maxLogicalPageId + 1;
readPage(state, physicalPageIDOfSmallestData);
memcpy(&(state->minDataPageId), buffer, sizeof(id_t));
state->numAvailDataPages = state->numDataPages + state->minDataPageId - maxLogicalPageId - 1 - (2 * blockSize);