| 1 | fn show_array(name string, a []int) { |
| 2 | eprintln('${name:10} .flags: ${a.flags:34} | .cap: ${a.cap:2} | .len: ${a.len:2} | .data: ${a.data} | ${a}') |
| 3 | } |
| 4 | |
| 5 | fn trace_delete_elements(name string, mut a []int) int { |
| 6 | a.delete_many(5, 3) |
| 7 | show_array(name, a) |
| 8 | a << 55 |
| 9 | show_array(name, a) |
| 10 | a << 66 |
| 11 | show_array(name, a) |
| 12 | a << 77 |
| 13 | res := a.cap |
| 14 | eprintln(' << ${name:10} .cap: ${a.cap} >>') |
| 15 | show_array(name, a) |
| 16 | a << 88 |
| 17 | show_array(name, a) |
| 18 | a << 99 |
| 19 | show_array(name, a) |
| 20 | eprintln('-------------------------------') |
| 21 | return res |
| 22 | } |
| 23 | |
| 24 | fn test_array_cap_shrinkage_after_deletion() { |
| 25 | mut a := [0] |
| 26 | mut middle_cap := 0 |
| 27 | |
| 28 | a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] |
| 29 | middle_cap = trace_delete_elements('normal', mut a) |
| 30 | assert middle_cap == 14 |
| 31 | assert a.len == 12 |
| 32 | assert a.cap == 14 |
| 33 | |
| 34 | a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] |
| 35 | unsafe { a.flags.set(.noslices) } |
| 36 | middle_cap = dump(trace_delete_elements('noslices', mut a)) |
| 37 | assert middle_cap == 14 |
| 38 | assert a.len == 12 |
| 39 | assert a.cap == 14 |
| 40 | |
| 41 | a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] |
| 42 | unsafe { a.flags.set(.noshrink) } |
| 43 | middle_cap = dump(trace_delete_elements('noshrink', mut a)) |
| 44 | assert middle_cap == 14 |
| 45 | assert a.len == 12 |
| 46 | assert a.cap == 14 |
| 47 | |
| 48 | // Note: when *both* flags are set, the memory block for the array |
| 49 | // should NOT shrink on deleting array elements, thus << after the |
| 50 | // deletion, will still have space (till .cap is reached). |
| 51 | a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] |
| 52 | unsafe { a.flags.set(.noslices | .noshrink) } |
| 53 | middle_cap = dump(trace_delete_elements('both', mut a)) |
| 54 | assert middle_cap == 10 |
| 55 | assert a.len == 12 |
| 56 | assert a.cap == 20 |
| 57 | } |
| 58 | |
| 59 | fn fixed_array_on_the_heap(len int, size int) []u8 { |
| 60 | data := vcalloc(size) |
| 61 | println(ptr_str(data)) |
| 62 | return unsafe { |
| 63 | array{ |
| 64 | element_size: 1 |
| 65 | len: len |
| 66 | cap: size |
| 67 | data: data |
| 68 | flags: .noshrink | .nogrow | .nofree |
| 69 | } |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | fn test_array_fixed_growth() { |
| 74 | mut x := fixed_array_on_the_heap(0, 10) |
| 75 | println(ptr_str(x.data)) |
| 76 | x << 5 |
| 77 | x << 10 |
| 78 | x << 15 |
| 79 | x << 20 |
| 80 | dump(x) |
| 81 | dump(x.flags) |
| 82 | assert x[2] == 15 |
| 83 | assert x.flags == .noshrink | .nogrow | .nofree |
| 84 | } |
| 85 | |
| 86 | fn test_array_fixed() { |
| 87 | mut x := fixed_array_on_the_heap(10, 10) |
| 88 | println(ptr_str(x.data)) |
| 89 | x[2] = 5 |
| 90 | dump(x) |
| 91 | dump(x.flags) |
| 92 | assert x[2] == 5 |
| 93 | assert x.flags == .noshrink | .nogrow | .nofree |
| 94 | } |
| 95 | |