-
Notifications
You must be signed in to change notification settings - Fork 0
/
survival_demo.c
91 lines (77 loc) · 2.08 KB
/
survival_demo.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
#include <survival.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include "slice.h"
static ALIGNED(16) int ARRAY_0[10] = {};
// Demo of ASSUME for optimization.
static void
add_vec(int* data, size_t data_len, int x)
{
ASSUME(data_len >= 16);
ASSUME((data_len % 16) == 0);
for (size_t k = 0; k < data_len; k++) {
data[k] += x;
}
}
void
demo_count_of()
{
static double local_array[3] = { 1.0 };
assert(COUNT_OF(ARRAY_0) == 10);
assert(COUNT_OF(local_array) == 3);
}
// Instanciate a trivial cleanup function for FILE* types.
DEFINE_TRIVIAL_CLEANUP_FUNC(
file_cleanup, /* Name for the wrapper generated. */
FILE*, /* Type passed to the destructor. */
fclose /* Destructor invoked. */
);
// Attribute to declare scoped variables.
#define scoped_slice SURVIVAL_CLEANUP(slice_release)
#define scoped_file SURVIVAL_CLEANUP(file_cleanup)
void
demo_scoped_slice()
{
// Because tmp is declared with the "scoped_slice" attribute, it will be
// automatically released by calling "slice_release" when this function
// returns (the necessary calls are generated by the compiler).
scoped_slice slice_t tmp;
if (slice_init(&tmp, 129) < 0) {
EPRINTF("slice_init failed\n");
}
add_vec(tmp.ptr, tmp.size, 10);
DPRINTF("leaving scope, slice will be released\n");
}
void
demo_scoped_file()
{
// f will be automatically closed.
scoped_file FILE* f = fopen("slice.h", "r");
if (f == NULL) {
EPRINTF("unable to open file.\n");
}
DPRINTF("file handle: %p\n", f);
}
int
main(int argc, char** argv)
{
DPRINTF("checking MAX macro\n");
assert(MAX(10, 3) == 10);
assert(MAX(3, 12) == 12);
DPRINTF("checking MIN macro\n");
assert(MIN(10, 3) == 3);
assert(MIN(1, 12) == 1);
DPRINTF("checking LIKELY, UNLIKELY\n");
int rnd = rand();
if (LIKELY(rnd > 0)) {
DPRINTF("rand() is > 0, (%d)\n", rnd);
}
if (UNLIKELY(rand() == 0)) {
EPRINTF("rand() is == 0");
}
demo_scoped_file();
demo_scoped_slice();
DPRINTF("All tests passed :)\n");
return 0;
}