mirror of
https://github.com/ziglang/zig.git
synced 2026-02-15 05:48:31 +00:00
Add ArrayList functions (#755)
at - Get the item at the n-th index. insert - Insert and item into the middle of the list, resizing and copying existing elements if needed. insertSlice - Insert a slice into the middle of the list, resizing and copying existing elements if needed.
This commit is contained in:
parent
dd20f558f0
commit
1c236b0766
@ -40,6 +40,10 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type{
|
||||
return l.items[0..l.len];
|
||||
}
|
||||
|
||||
pub fn at(l: &const Self, n: usize) T {
|
||||
return l.toSliceConst()[n];
|
||||
}
|
||||
|
||||
/// ArrayList takes ownership of the passed in slice. The slice must have been
|
||||
/// allocated with `allocator`.
|
||||
/// Deinitialize with `deinit` or use `toOwnedSlice`.
|
||||
@ -59,6 +63,22 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type{
|
||||
return result;
|
||||
}
|
||||
|
||||
pub fn insert(l: &Self, n: usize, item: &const T) %void {
|
||||
try l.ensureCapacity(l.len + 1);
|
||||
l.len += 1;
|
||||
|
||||
mem.copy(T, l.items[n+1..l.len], l.items[n..l.len-1]);
|
||||
l.items[n] = *item;
|
||||
}
|
||||
|
||||
pub fn insertSlice(l: &Self, n: usize, items: []align(A) const T) %void {
|
||||
try l.ensureCapacity(l.len + items.len);
|
||||
l.len += items.len;
|
||||
|
||||
mem.copy(T, l.items[n+items.len..l.len], l.items[n..l.len-items.len]);
|
||||
mem.copy(T, l.items[n..n+items.len], items);
|
||||
}
|
||||
|
||||
pub fn append(l: &Self, item: &const T) %void {
|
||||
const new_item_ptr = try l.addOne();
|
||||
*new_item_ptr = *item;
|
||||
@ -136,3 +156,22 @@ test "basic ArrayList test" {
|
||||
list.appendSlice([]const i32 {}) catch unreachable;
|
||||
assert(list.len == 9);
|
||||
}
|
||||
|
||||
test "insert ArrayList test" {
|
||||
var list = ArrayList(i32).init(debug.global_allocator);
|
||||
defer list.deinit();
|
||||
|
||||
try list.append(1);
|
||||
try list.insert(0, 5);
|
||||
assert(list.items[0] == 5);
|
||||
assert(list.items[1] == 1);
|
||||
|
||||
try list.insertSlice(1, []const i32 { 9, 8 });
|
||||
assert(list.items[0] == 5);
|
||||
assert(list.items[1] == 9);
|
||||
assert(list.items[2] == 8);
|
||||
|
||||
const items = []const i32 { 1 };
|
||||
try list.insertSlice(0, items[0..0]);
|
||||
assert(list.items[0] == 5);
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user