]> git.proxmox.com Git - libgit2.git/blob - tests/str/oom.c
3d59ead019709dff846f69cbbd1400b5a5623b5b
[libgit2.git] / tests / str / oom.c
1 #include "clar_libgit2.h"
2
3 /* Override default allocators with ones that will fail predictably. */
4
5 static git_allocator std_alloc;
6 static git_allocator oom_alloc;
7
8 static void *oom_malloc(size_t n, const char *file, int line)
9 {
10 /* Reject any allocation of more than 100 bytes */
11 return (n > 100) ? NULL : std_alloc.gmalloc(n, file, line);
12 }
13
14 static void *oom_realloc(void *p, size_t n, const char *file, int line)
15 {
16 /* Reject any allocation of more than 100 bytes */
17 return (n > 100) ? NULL : std_alloc.grealloc(p, n, file, line);
18 }
19
20 void test_str_oom__initialize(void)
21 {
22 git_stdalloc_init_allocator(&std_alloc);
23 git_stdalloc_init_allocator(&oom_alloc);
24
25 oom_alloc.gmalloc = oom_malloc;
26 oom_alloc.grealloc = oom_realloc;
27
28 cl_git_pass(git_libgit2_opts(GIT_OPT_SET_ALLOCATOR, &oom_alloc));
29 }
30
31 void test_str_oom__cleanup(void)
32 {
33 cl_git_pass(git_libgit2_opts(GIT_OPT_SET_ALLOCATOR, NULL));
34 }
35
36 void test_str_oom__grow(void)
37 {
38 git_str buf = GIT_STR_INIT;
39
40 cl_git_pass(git_str_grow(&buf, 42));
41 cl_assert(!git_str_oom(&buf));
42
43 cl_assert(git_str_grow(&buf, 101) == -1);
44 cl_assert(git_str_oom(&buf));
45
46 git_str_dispose(&buf);
47 }
48
49 void test_str_oom__grow_by(void)
50 {
51 git_str buf = GIT_STR_INIT;
52
53 cl_git_pass(git_str_grow_by(&buf, 42));
54 cl_assert(!git_str_oom(&buf));
55
56 cl_assert(git_str_grow_by(&buf, 101) == -1);
57 cl_assert(git_str_oom(&buf));
58 }