1 #ifndef TEST_ALLOCATOR_H_
2 #define TEST_ALLOCATOR_H_
3 
4 #include "assertions.h"
5 #include "cbor.h"
6 
7 // Harness for mocking `malloc` and `realloc`
8 
9 typedef enum call_expectation {
10   MALLOC,
11   MALLOC_FAIL,
12   REALLOC,
13   REALLOC_FAIL
14 } call_expectation;
15 
16 void set_mock_malloc(int calls, ...);
17 
18 void finalize_mock_malloc(void);
19 
20 void *instrumented_malloc(size_t size);
21 
22 void *instrumented_realloc(void *ptr, size_t size);
23 
24 #define WITH_MOCK_MALLOC(block, malloc_calls, ...)                    \
25   do {                                                                \
26     cbor_set_allocs(instrumented_malloc, instrumented_realloc, free); \
27     set_mock_malloc(malloc_calls, __VA_ARGS__);                       \
28     block;                                                            \
29     finalize_mock_malloc();                                           \
30     cbor_set_allocs(malloc, realloc, free);                           \
31   } while (0)
32 
33 #define WITH_FAILING_MALLOC(block) WITH_MOCK_MALLOC(block, 1, MALLOC_FAIL)
34 
35 #endif  // TEST_ALLOCATOR_H_
36