module nspkg #include "@ALLOC_HEADER@" fn C.list_alloc_malloc(uint) voidptr fn C.list_alloc_calloc(uint, uint) voidptr fn C.list_alloc_strdup(&u8) &u8 fn C.list_alloc_free(voidptr) fn C.list_alloc_fail_after(i64) fn C.list_alloc_live() int fn alloc_cmp(a voidptr, b voidptr) i32 { return if u64(a) < u64(b) { -1 } else if a == b { 0 } else { 1 } } fn alloc_list(values []int) &List { mut result := &List(unsafe { nil }) for value in values { result = result.add(voidptr(value)) } return result } fn test_allocation_failure_does_not_leak_or_change_the_input() { for operation in 0 .. 4 { values := [1, 2, 2, 3] mut head := &List(unsafe { nil }) for i in 0 .. values.len { head = head.add(unsafe { &values[i] }) } base := C.list_alloc_live() tail := head.prev for budget in 0 .. 10 { C.list_alloc_fail_after(budget) result := match operation { 0 { head.copy() } 1 { head.reverse() } 2 { head.remove_dupes() } else { head.copy_data(sizeof(int)) } } C.list_alloc_fail_after(-1) if operation == 3 { result.free_inner(C.list_alloc_free) } result.free() assert C.list_alloc_live() == base assert head.count() == 4 assert head.prev == tail assert head.nth(0).data == unsafe { &values[0] } assert head.nth(3).data == unsafe { &values[3] } } head.free() assert C.list_alloc_live() == 0 } } fn test_string_allocation_failures() { mut head := &List(unsafe { nil }) for value in ['one', 'two', 'three'] { head = head.add(value.str) } base := C.list_alloc_live() for budget in 0 .. 8 { C.list_alloc_fail_after(budget) result := head.strdup() C.list_alloc_fail_after(-1) result.free_inner(C.list_alloc_free) result.free() assert C.list_alloc_live() == base } head.free() for budget in 0 .. 3 { mut empty := &List(unsafe { nil }) C.list_alloc_fail_after(budget) node := (&empty).append_strdup('new') C.list_alloc_fail_after(-1) if budget < 2 { assert node == unsafe { nil }; assert empty == unsafe { nil } } else { assert node == empty } empty.free_inner(C.list_alloc_free) empty.free() assert C.list_alloc_live() == 0 } } fn test_failed_mutators_and_compare() { head := alloc_list([1, 2]) other := alloc_list([2, 1]) base := C.list_alloc_live() C.list_alloc_fail_after(0) assert head.add(voidptr(3)) == head assert head.add_sorted(voidptr(0), alloc_cmp) == head mut pointer := unsafe { head } assert (&pointer).append(voidptr(3)) == unsafe { nil } assert pointer == head assert head.cmp_unsorted(other, alloc_cmp) == -1 assert head.to_array(1, 1) == none C.list_alloc_fail_after(-1) assert C.list_alloc_live() == base assert head.count() == 2 head.free() other.free() assert C.list_alloc_live() == 0 }