| ... | @@ -40,6 +40,10 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type{ | ... | @@ -40,6 +40,10 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type{ |
| 40 | return l.items[0..l.len]; | 40 | return l.items[0..l.len]; |
| 41 | } | 41 | } |
| 42 | | 42 | |
| | 43 | pub fn at(l: &const Self, n: usize) T { |
| | 44 | return l.toSliceConst()[n]; |
| | 45 | } |
| | 46 | |
| 43 | /// ArrayList takes ownership of the passed in slice. The slice must have been | 47 | /// ArrayList takes ownership of the passed in slice. The slice must have been |
| 44 | /// allocated with `allocator`. | 48 | /// allocated with `allocator`. |
| 45 | /// Deinitialize with `deinit` or use `toOwnedSlice`. | 49 | /// Deinitialize with `deinit` or use `toOwnedSlice`. |
| ... | @@ -59,6 +63,22 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type{ | ... | @@ -59,6 +63,22 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type{ |
| 59 | return result; | 63 | return result; |
| 60 | } | 64 | } |
| 61 | | 65 | |
| | 66 | pub fn insert(l: &Self, n: usize, item: &const T) %void { |
| | 67 | try l.ensureCapacity(l.len + 1); |
| | 68 | l.len += 1; |
| | 69 | |
| | 70 | mem.copy(T, l.items[n+1..l.len], l.items[n..l.len-1]); |
| | 71 | l.items[n] = *item; |
| | 72 | } |
| | 73 | |
| | 74 | pub fn insertSlice(l: &Self, n: usize, items: []align(A) const T) %void { |
| | 75 | try l.ensureCapacity(l.len + items.len); |
| | 76 | l.len += items.len; |
| | 77 | |
| | 78 | mem.copy(T, l.items[n+items.len..l.len], l.items[n..l.len-items.len]); |
| | 79 | mem.copy(T, l.items[n..n+items.len], items); |
| | 80 | } |
| | 81 | |
| 62 | pub fn append(l: &Self, item: &const T) %void { | 82 | pub fn append(l: &Self, item: &const T) %void { |
| 63 | const new_item_ptr = try l.addOne(); | 83 | const new_item_ptr = try l.addOne(); |
| 64 | *new_item_ptr = *item; | 84 | *new_item_ptr = *item; |
| ... | @@ -136,3 +156,22 @@ test "basic ArrayList test" { | ... | @@ -136,3 +156,22 @@ test "basic ArrayList test" { |
| 136 | list.appendSlice([]const i32 {}) catch unreachable; | 156 | list.appendSlice([]const i32 {}) catch unreachable; |
| 137 | assert(list.len == 9); | 157 | assert(list.len == 9); |
| 138 | } | 158 | } |
| | 159 | |
| | 160 | test "insert ArrayList test" { |
| | 161 | var list = ArrayList(i32).init(debug.global_allocator); |
| | 162 | defer list.deinit(); |
| | 163 | |
| | 164 | try list.append(1); |
| | 165 | try list.insert(0, 5); |
| | 166 | assert(list.items[0] == 5); |
| | 167 | assert(list.items[1] == 1); |
| | 168 | |
| | 169 | try list.insertSlice(1, []const i32 { 9, 8 }); |
| | 170 | assert(list.items[0] == 5); |
| | 171 | assert(list.items[1] == 9); |
| | 172 | assert(list.items[2] == 8); |
| | 173 | |
| | 174 | const items = []const i32 { 1 }; |
| | 175 | try list.insertSlice(0, items[0..0]); |
| | 176 | assert(list.items[0] == 5); |
| | 177 | } |