nspkg / tests / list_alloc_test.v.in
94 lines · 88 sloc · 2.66 KB · c01b0795d1db56c7bce2539b2c46b110637fdc1a
Raw
1module nspkg
2
3#include "@ALLOC_HEADER@"
4fn C.list_alloc_malloc(uint) voidptr
5fn C.list_alloc_calloc(uint, uint) voidptr
6fn C.list_alloc_strdup(&u8) &u8
7fn C.list_alloc_free(voidptr)
8fn C.list_alloc_fail_after(i64)
9fn C.list_alloc_live() int
10
11fn alloc_cmp(a voidptr, b voidptr) i32 {
12 return if u64(a) < u64(b) { -1 } else if a == b { 0 } else { 1 }
13}
14
15fn alloc_list(values []int) &List {
16 mut result := &List(unsafe { nil })
17 for value in values { result = result.add(voidptr(value)) }
18 return result
19}
20
21fn test_allocation_failure_does_not_leak_or_change_the_input() {
22 for operation in 0 .. 4 {
23 values := [1, 2, 2, 3]
24 mut head := &List(unsafe { nil })
25 for i in 0 .. values.len { head = head.add(unsafe { &values[i] }) }
26 base := C.list_alloc_live()
27 tail := head.prev
28 for budget in 0 .. 10 {
29 C.list_alloc_fail_after(budget)
30 result := match operation {
31 0 { head.copy() }
32 1 { head.reverse() }
33 2 { head.remove_dupes() }
34 else { head.copy_data(sizeof(int)) }
35 }
36 C.list_alloc_fail_after(-1)
37 if operation == 3 { result.free_inner(C.list_alloc_free) }
38 result.free()
39 assert C.list_alloc_live() == base
40 assert head.count() == 4
41 assert head.prev == tail
42 assert head.nth(0).data == unsafe { &values[0] }
43 assert head.nth(3).data == unsafe { &values[3] }
44 }
45 head.free()
46 assert C.list_alloc_live() == 0
47 }
48}
49
50fn test_string_allocation_failures() {
51 mut head := &List(unsafe { nil })
52 for value in ['one', 'two', 'three'] { head = head.add(value.str) }
53 base := C.list_alloc_live()
54 for budget in 0 .. 8 {
55 C.list_alloc_fail_after(budget)
56 result := head.strdup()
57 C.list_alloc_fail_after(-1)
58 result.free_inner(C.list_alloc_free)
59 result.free()
60 assert C.list_alloc_live() == base
61 }
62 head.free()
63 for budget in 0 .. 3 {
64 mut empty := &List(unsafe { nil })
65 C.list_alloc_fail_after(budget)
66 node := (&empty).append_strdup('new')
67 C.list_alloc_fail_after(-1)
68 if budget < 2 { assert node == unsafe { nil }; assert empty == unsafe { nil } }
69 else { assert node == empty }
70 empty.free_inner(C.list_alloc_free)
71 empty.free()
72 assert C.list_alloc_live() == 0
73 }
74}
75
76fn test_failed_mutators_and_compare() {
77 head := alloc_list([1, 2])
78 other := alloc_list([2, 1])
79 base := C.list_alloc_live()
80 C.list_alloc_fail_after(0)
81 assert head.add(voidptr(3)) == head
82 assert head.add_sorted(voidptr(0), alloc_cmp) == head
83 mut pointer := unsafe { head }
84 assert (&pointer).append(voidptr(3)) == unsafe { nil }
85 assert pointer == head
86 assert head.cmp_unsorted(other, alloc_cmp) == -1
87 assert head.to_array(1, 1) == none
88 C.list_alloc_fail_after(-1)
89 assert C.list_alloc_live() == base
90 assert head.count() == 2
91 head.free()
92 other.free()
93 assert C.list_alloc_live() == 0
94}
95