authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2021-01-01 13:23:18-08:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2021-01-01 13:23:18-08:00
log4cc374c639a64c087c9c8aaea59d5bb9a6a637e9
tree67288d41d7425f2896159686bc7d7bde8d46e131
parentdfacac916fabe71ac2a2d1794504ba5b82e25f83
parent03e2c53747a7eeb0d162f7b7fa7763fffdeba2d8
signaturebadge-question-mark Signed by PGP key 4AEE18F83AFDEB23

Merge pull request #7634 from daurnimator/packed-init-all-to

Add PackedIntArray .initAllTo function

1 files changed, 25 insertions(+), 1 deletions(-)

lib/std/packed_int_array.zig+25-1
......@@ -203,6 +203,14 @@ pub fn PackedIntArrayEndian(comptime Int: type, comptime endian: builtin.Endian,
203203 return self;
204204 }
205205
206 ///Initialize all entries of a packed array to the same value
207 pub fn initAllTo(int: Int) Self {
208 // TODO: use `var self = @as(Self, undefined);` https://github.com/ziglang/zig/issues/7635
209 var self = Self{ .bytes = [_]u8{0} ** total_bytes };
210 self.setAll(int);
211 return self;
212 }
213
206214 ///Return the Int stored at index
207215 pub fn get(self: Self, index: usize) Int {
208216 debug.assert(index < int_count);
......@@ -215,6 +223,14 @@ pub fn PackedIntArrayEndian(comptime Int: type, comptime endian: builtin.Endian,
215223 return Io.set(&self.bytes, index, 0, int);
216224 }
217225
226 ///Set all entries of a packed array to the same value
227 pub fn setAll(self: *Self, int: Int) void {
228 var i: usize = 0;
229 while (i < int_count) : (i += 1) {
230 self.set(i, int);
231 }
232 }
233
218234 ///Create a PackedIntSlice of the array from given start to given end
219235 pub fn slice(self: *Self, start: usize, end: usize) PackedIntSliceEndian(Int, endian) {
220236 debug.assert(start < int_count);
......@@ -365,7 +381,15 @@ test "PackedIntArray init" {
365381 const PackedArray = PackedIntArray(u3, 8);
366382 var packed_array = PackedArray.init([_]u3{ 0, 1, 2, 3, 4, 5, 6, 7 });
367383 var i = @as(usize, 0);
368 while (i < packed_array.len()) : (i += 1) testing.expect(packed_array.get(i) == i);
384 while (i < packed_array.len()) : (i += 1) testing.expectEqual(@intCast(u3, i), packed_array.get(i));
385}
386
387test "PackedIntArray initAllTo" {
388 if (we_are_testing_this_with_stage1_which_leaks_comptime_memory) return error.SkipZigTest;
389 const PackedArray = PackedIntArray(u3, 8);
390 var packed_array = PackedArray.initAllTo(5);
391 var i = @as(usize, 0);
392 while (i < packed_array.len()) : (i += 1) testing.expectEqual(@as(u3, 5), packed_array.get(i));
369393}
370394
371395test "PackedIntSlice" {