aboutsummaryrefslogtreecommitdiff
path: root/std/array_list.zig
diff options
context:
space:
mode:
authorAndrew Kelley <superjoe30@gmail.com>2018-05-04 13:39:27 -0400
committerAndrew Kelley <superjoe30@gmail.com>2018-05-04 13:39:27 -0400
commit7e37d268c86ccc823c4a381a42029722d36c3975 (patch)
tree1600a184f03fedd91131bcbaea2c5ee85dfa06a3 /std/array_list.zig
parent6309121f70ff88cf64267f2bf1d9e452090ca277 (diff)
parentef3111be236fc389a696562d31bccd3a9b6d1c56 (diff)
downloadzig-7e37d268c86ccc823c4a381a42029722d36c3975.tar.gz
zig-7e37d268c86ccc823c4a381a42029722d36c3975.zip
Merge remote-tracking branch 'origin/master' into llvm7
Diffstat (limited to 'std/array_list.zig')
-rw-r--r--std/array_list.zig56
1 files changed, 55 insertions, 1 deletions
diff --git a/std/array_list.zig b/std/array_list.zig
index 2a44b66518..bd7e8ea7ed 100644
--- a/std/array_list.zig
+++ b/std/array_list.zig
@@ -44,6 +44,10 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type{
return l.toSliceConst()[n];
}
+ pub fn count(self: &const Self) usize {
+ return self.len;
+ }
+
/// ArrayList takes ownership of the passed in slice. The slice must have been
/// allocated with `allocator`.
/// Deinitialize with `deinit` or use `toOwnedSlice`.
@@ -128,6 +132,27 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type{
return null;
return self.pop();
}
+
+ pub const Iterator = struct {
+ list: &const Self,
+ // how many items have we returned
+ count: usize,
+
+ pub fn next(it: &Iterator) ?T {
+ if (it.count >= it.list.len) return null;
+ const val = it.list.at(it.count);
+ it.count += 1;
+ return val;
+ }
+
+ pub fn reset(it: &Iterator) void {
+ it.count = 0;
+ }
+ };
+
+ pub fn iterator(self: &Self) Iterator {
+ return Iterator { .list = self, .count = 0 };
+ }
};
}
@@ -157,6 +182,35 @@ test "basic ArrayList test" {
assert(list.len == 9);
}
+test "iterator ArrayList test" {
+ var list = ArrayList(i32).init(debug.global_allocator);
+ defer list.deinit();
+
+ try list.append(1);
+ try list.append(2);
+ try list.append(3);
+
+ var count : i32 = 0;
+ var it = list.iterator();
+ while (it.next()) |next| {
+ assert(next == count + 1);
+ count += 1;
+ }
+
+ assert(count == 3);
+ assert(it.next() == null);
+ it.reset();
+ count = 0;
+ while (it.next()) |next| {
+ assert(next == count + 1);
+ count += 1;
+ if (count == 2) break;
+ }
+
+ it.reset();
+ assert(?? it.next() == 1);
+}
+
test "insert ArrayList test" {
var list = ArrayList(i32).init(debug.global_allocator);
defer list.deinit();
@@ -174,4 +228,4 @@ test "insert ArrayList test" {
const items = []const i32 { 1 };
try list.insertSlice(0, items[0..0]);
assert(list.items[0] == 5);
-}
+} \ No newline at end of file