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
|
// bin.c - Example usage of bin.h flat file block storage
#include <assert.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
typedef int32_t bin_key_t;
#define BIN_IMPLEMENTATION
#include "../include/bin.h"
#define TEST_LENGTH 10
#define TEST_START -2
struct sample_t {
bin_key_t time;
double data;
};
int main(void) {
char const *path = "./test.bin";
FILE *bin = bin_init(path, sizeof(struct sample_t));
if (!bin) {
fprintf(stderr, "Failed to initialize binary file\n");
return 1;
}
bin_key_t half = (bin_key_t)((TEST_START + TEST_LENGTH) / 2.0);
// Insert half of the values using bin_insert()
for (bin_key_t i = half - 1; i >= TEST_START; i--) {
struct sample_t sample = {.time = i, .data = 2.0 * i};
bin_insert(bin, 0, &sample, 1);
}
// Append half of the values to the end
for (bin_key_t i = half; i < TEST_START + TEST_LENGTH; i++) {
struct sample_t sample = {.time = i, .data = 2.0 * i};
bin_append(bin, &sample, 1);
}
uint64_t l = bin_length(bin);
(void)bin_block_size(bin);
assert(l < 1000000);
struct sample_t *x = calloc(l, sizeof(struct sample_t));
if (!x) {
fprintf(stderr, "Failed to allocate memory\n");
bin_close(bin);
return 1;
}
bin_read(bin, 0, x, l);
// Test that all values are correct
for (uint32_t i = 0; i < TEST_LENGTH; i++) {
bin_key_t key = TEST_START + (int32_t)i;
assert(x[i].time == key);
assert(fabs(x[i].data - 2.0 * key) < 1e-9);
}
free(x);
bin_close(bin);
remove(path);
return 0;
}
|