Commit 31ba9d569b

daurnimator <quae@daurnimator.com>
2021-01-01 14:52:47
Add PackedIntArray .initAllTo function
1 parent 93bb1d9
Changed files (1)
lib/std/packed_int_array.zig
@@ -203,6 +203,13 @@ pub fn PackedIntArrayEndian(comptime Int: type, comptime endian: builtin.Endian,
             return self;
         }
 
+        ///Initialize all entries of a packed array to the same value
+        pub fn initAllTo(int: Int) Self {
+            var self = @as(Self, undefined);
+            self.setAll(int);
+            return self;
+        }
+
         ///Return the Int stored at index
         pub fn get(self: Self, index: usize) Int {
             debug.assert(index < int_count);
@@ -215,6 +222,14 @@ pub fn PackedIntArrayEndian(comptime Int: type, comptime endian: builtin.Endian,
             return Io.set(&self.bytes, index, 0, int);
         }
 
+        ///Set all entries of a packed array to the same value
+        pub fn setAll(self: *Self, int: Int) void {
+            var i: usize = 0;
+            while (i < int_count) : (i += 1) {
+                self.set(i, int);
+            }
+        }
+
         ///Create a PackedIntSlice of the array from given start to given end
         pub fn slice(self: *Self, start: usize, end: usize) PackedIntSliceEndian(Int, endian) {
             debug.assert(start < int_count);
@@ -365,7 +380,15 @@ test "PackedIntArray init" {
     const PackedArray = PackedIntArray(u3, 8);
     var packed_array = PackedArray.init([_]u3{ 0, 1, 2, 3, 4, 5, 6, 7 });
     var i = @as(usize, 0);
-    while (i < packed_array.len()) : (i += 1) testing.expect(packed_array.get(i) == i);
+    while (i < packed_array.len()) : (i += 1) testing.expectEqual(@intCast(u3, i), packed_array.get(i));
+}
+
+test "PackedIntArray initAllTo" {
+    if (we_are_testing_this_with_stage1_which_leaks_comptime_memory) return error.SkipZigTest;
+    const PackedArray = PackedIntArray(u3, 8);
+    var packed_array = PackedArray.initAllTo(5);
+    var i = @as(usize, 0);
+    while (i < packed_array.len()) : (i += 1) testing.expectEqual(@as(u3, 5), packed_array.get(i));
 }
 
 test "PackedIntSlice" {