| ... | ... | @@ -0,0 +1,66 @@ |
| 1 | pub struct List#(T: type) { |
| 2 | items: ?&T, |
| 3 | length: usize, |
| 4 | capacity: usize, |
| 5 | |
| 6 | pub fn (l: &List) deinit() { |
| 7 | free(l.items); |
| 8 | l.items = None; |
| 9 | } |
| 10 | |
| 11 | pub fn append(l: &List, item: T) -> error { |
| 12 | const err = l.ensure_capacity(l.length + 1); |
| 13 | if err != Error.None { |
| 14 | return err; |
| 15 | } |
| 16 | const raw_items = l.items ?? unreachable; |
| 17 | l.raw_items[l.length] = item; |
| 18 | l.length += 1; |
| 19 | return 0; |
| 20 | } |
| 21 | |
| 22 | pub fn at(l: List, index: usize) -> T { |
| 23 | assert(index < l.length); |
| 24 | const raw_items = l.items ?? unreachable; |
| 25 | return raw_items[index]; |
| 26 | } |
| 27 | |
| 28 | pub fn ptr_at(l: &List, index: usize) -> &T { |
| 29 | assert(index < l.length); |
| 30 | const raw_items = l.items ?? unreachable; |
| 31 | return &raw_items[index]; |
| 32 | } |
| 33 | |
| 34 | pub fn clear(l: &List) { |
| 35 | l.length = 0; |
| 36 | } |
| 37 | |
| 38 | pub fn pop(l: &List) -> T { |
| 39 | assert(l.length >= 1); |
| 40 | l.length -= 1; |
| 41 | return l.items[l.length]; |
| 42 | } |
| 43 | |
| 44 | fn ensure_capacity(l: &List, new_capacity: usize) -> error { |
| 45 | var better_capacity = max(l.capacity, 16); |
| 46 | while better_capacity < new_capacity { |
| 47 | better_capacity *= 2; |
| 48 | } |
| 49 | if better_capacity != l.capacity { |
| 50 | const new_items = realloc(l.items, better_capacity) ?? { return Error.NoMem }; |
| 51 | l.items = new_items; |
| 52 | l.capacity = better_capacity; |
| 53 | } |
| 54 | Error.None |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | pub fn malloc#(T: type)(count: usize) -> ?&T { realloc(None, count) } |
| 59 | |
| 60 | pub fn realloc#(T: type)(ptr: ?&T, new_count: usize) -> ?&T { |
| 61 | |
| 62 | } |
| 63 | |
| 64 | pub fn free#(T: type)(ptr: ?&T) { |
| 65 | |
| 66 | } |