authorgravatar for hello@nektro.netMeghan Denny <hello@nektro.net> 2023-02-10 08:12:26 -08:00
committergravatar for hello@nektro.netMeghan Denny <hello@nektro.net> 2023-02-10 08:12:26 -08:00
log3fe700ebc8ff66966abe145166bfdf546b3a8422
treed4a5abdadef4be7d4837270b92f64d1e19e1181c
parent7dbc8810f8bc628f51fb77f11ff425a6023d236d

allow indexBufferT and BufIndexer to be backed by arbitrary sources

so long as the index being accessed is within the known maximum this allows a large maximum being set (essentially making this unchecked) for cases where accesses are otherwise known to be good

1 files changed, 3 insertions(+), 4 deletions(-)

src/lib.zig+3-4
...@@ -377,9 +377,9 @@ pub fn readType(reader: anytype, comptime T: type, endian: std.builtin.Endian) !...@@ -377,9 +377,9 @@ pub fn readType(reader: anytype, comptime T: type, endian: std.builtin.Endian) !
377 };377 };
378}378}
379379
380pub fn indexBufferT(bytes: []const u8, comptime T: type, endian: std.builtin.Endian, idx: usize, max_len: usize) T {380pub fn indexBufferT(bytes: [*]const u8, comptime T: type, endian: std.builtin.Endian, idx: usize, max_len: usize) T {
381 std.debug.assert(idx < max_len);381 std.debug.assert(idx < max_len);
382 var fbs = std.io.fixedBufferStream(bytes[idx * @sizeOf(T) ..]);382 var fbs = std.io.fixedBufferStream((bytes + (idx * @sizeOf(T)))[0..@sizeOf(T)]);
383 return readType(fbs.reader(), T, endian) catch |err| switch (err) {383 return readType(fbs.reader(), T, endian) catch |err| switch (err) {
384 error.EndOfStream => unreachable, // assert above has been violated384 error.EndOfStream => unreachable, // assert above has been violated
385 };385 };
...@@ -393,7 +393,6 @@ pub fn BufIndexer(comptime T: type, comptime endian: std.builtin.Endian) type {...@@ -393,7 +393,6 @@ pub fn BufIndexer(comptime T: type, comptime endian: std.builtin.Endian) type {
393 const Self = @This();393 const Self = @This();
394394
395 pub fn init(bytes: []const u8, max_len: usize) Self {395 pub fn init(bytes: []const u8, max_len: usize) Self {
396 std.debug.assert(bytes.len >= @sizeOf(T) * max_len);
397 return .{396 return .{
398 .bytes = bytes.ptr,397 .bytes = bytes.ptr,
399 .max_len = max_len,398 .max_len = max_len,
...@@ -401,7 +400,7 @@ pub fn BufIndexer(comptime T: type, comptime endian: std.builtin.Endian) type {...@@ -401,7 +400,7 @@ pub fn BufIndexer(comptime T: type, comptime endian: std.builtin.Endian) type {
401 }400 }
402401
403 pub fn at(self: *const Self, idx: usize) T {402 pub fn at(self: *const Self, idx: usize) T {
404 return indexBufferT(self.bytes[0 .. @sizeOf(T) * self.max_len], T, endian, idx, self.max_len);403 return indexBufferT(self.bytes, T, endian, idx, self.max_len);
405 }404 }
406 };405 };
407}406}