std: add in_stream.isBytes

master
daurnimator 2020-04-25 20:42:13 +10:00
parent b531c0e676
commit 1d6e53756b
No known key found for this signature in database
GPG Key ID: 45B429A8F9D9D22A
1 changed files with 18 additions and 0 deletions

View File

@ -234,6 +234,18 @@ pub fn InStream(
}
}
/// Reads `slice.len` bytes from the stream and returns if they are the same as the passed slice
pub fn isBytes(self: Self, slice: []const u8) !bool {
var i: usize = 0;
var matches = true;
while (i < slice.len) : (i += 1) {
if (slice[i] != try self.readByte()) {
matches = false;
}
}
return matches;
}
pub fn readStruct(self: Self, comptime T: type) !T {
// Only extern and packed structs have defined in-memory layout.
comptime assert(@typeInfo(T).Struct.layout != builtin.TypeInfo.ContainerLayout.Auto);
@ -276,3 +288,9 @@ test "InStream" {
}, undefined)) == .c);
testing.expectError(error.EndOfStream, in_stream.readByte());
}
test "InStream.isBytes" {
const in_stream = std.io.fixedBufferStream("foobar").inStream();
testing.expectEqual(true, try in_stream.isBytes("foo"));
testing.expectEqual(false, try in_stream.isBytes("qux"));
}