lib::array.zig (2041B)
1 const std = @import("std"); 2 3 pub fn Array(comptime T: type) type { 4 return struct { 5 const Self = @This(); 6 const Init = 8; 7 8 len: usize, 9 data: []T, 10 allocator: std.mem.Allocator, 11 12 pub const Iterator = struct { 13 cur: ?[*]T = null, 14 end: ?[*]T = null, 15 16 pub fn next(self: *Iterator) ?*const T { 17 if (self.cur) |cur| { 18 self.cur = if (cur == self.end) 19 null 20 else 21 cur + 1; 22 return cur[0]; 23 } 24 return null; 25 } 26 }; 27 28 pub fn init(allocator: std.mem.Allocator) !Self { 29 return Self{ 30 .len = 0, 31 .data = try allocator.alloc(T, Init), 32 .allocator = allocator, 33 }; 34 } 35 36 pub fn iter(self: *Self) Iterator { 37 return if (self.len == 0) Iterator{} else Iterator{ 38 .cur = &self.data[0], 39 .end = &self.data[self.len - 1], 40 }; 41 } 42 43 pub fn add(self: *Self, val: T) !void { 44 if (self.data.len <= self.len) { 45 self.data = try self.allocator.realloc(self.data, 2 * self.data.len); 46 } 47 self.data[self.len] = val; 48 self.len += 1; 49 } 50 51 pub fn slice(self: *const Self) []const T { 52 return self.data[0..self.len]; 53 } 54 55 pub fn get(self: *const Self, idx: usize) ?T { 56 return if (idx >= self.len) null else self.data[idx]; 57 } 58 59 pub fn set(self: *const Self, idx: usize, val: T) !void { 60 if (idx >= self.len) 61 return error.IndexOutOfBounds; 62 self.data[idx] = val; 63 } 64 65 pub fn last(self: *const Self) ?T { 66 return if (self.len == 0) null else self.data[self.len - 1]; 67 } 68 69 pub fn deinit(self: *Self) void { 70 self.allocator.free(self.data); 71 } 72 }; 73 }