authorgravatar for quae@daurnimator.comdaurnimator <quae@daurnimator.com> 2019-11-16 22:34:27+11:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2020-02-18 16:47:03-05:00
logdd75cc214d087e0d3a68a76ced3a707aa456d887
tree4721f5597a4fc5f595e0c9a51e05f1a14c091d7e
parent38ad7daebb42d562946c092a59cfbbf94e75870a
signature Commit is signed but in an unrecognized format.

std: let PeekStream have static/dynamic variants

This completes a TODO in the existing implementation

2 files changed, 32 insertions(+), 12 deletions(-)

lib/std/io.zig+31-11
......@@ -196,7 +196,7 @@ test "io.BufferedInStream" {
196196
197197/// Creates a stream which supports 'un-reading' data, so that it can be read again.
198198/// This makes look-ahead style parsing much easier.
199pub fn PeekStream(comptime buffer_type: usize, comptime InStreamError: type) type {
199pub fn PeekStream(comptime buffer_type: std.fifo.LinearFifoBufferType, comptime InStreamError: type) type {
200200 return struct {
201201 const Self = @This();
202202 pub const Error = InStreamError;
......@@ -205,18 +205,38 @@ pub fn PeekStream(comptime buffer_type: usize, comptime InStreamError: type) typ
205205 stream: Stream,
206206 base: *Stream,
207207
208 // Right now the look-ahead space is statically allocated, but a version with dynamic allocation
209 // is not too difficult to derive from this.
210 const FifoType = std.fifo.LinearFifo(u8, .{ .Static = buffer_size });
208 const FifoType = std.fifo.LinearFifo(u8, buffer_type);
211209 fifo: FifoType,
212210
213 pub fn init(base: *Stream) Self {
214 return .{
215 .base = base,
216 .fifo = FifoType.init(),
217 .stream = Stream{ .readFn = readFn },
218 };
219 }
211 pub usingnamespace switch (buffer_type) {
212 .Static => struct {
213 pub fn init(base: *Stream) Self {
214 return .{
215 .base = base,
216 .fifo = FifoType.init(),
217 .stream = Stream{ .readFn = readFn },
218 };
219 }
220 },
221 .Slice => struct {
222 pub fn init(base: *Stream, buf: []u8) Self {
223 return .{
224 .base = base,
225 .fifo = FifoType.init(buf),
226 .stream = Stream{ .readFn = readFn },
227 };
228 }
229 },
230 .Dynamic => struct {
231 pub fn init(base: *Stream, allocator: *mem.Allocator) Self {
232 return .{
233 .base = base,
234 .fifo = FifoType.init(allocator),
235 .stream = Stream{ .readFn = readFn },
236 };
237 }
238 },
239 };
220240
221241 pub fn putBackByte(self: *Self, byte: u8) !void {
222242 try self.putBack(@ptrCast([*]const u8, &byte)[0..1]);
lib/std/io/test.zig+1-1
......@@ -93,7 +93,7 @@ test "SliceInStream" {
9393test "PeekStream" {
9494 const bytes = [_]u8{ 1, 2, 3, 4, 5, 6, 7, 8 };
9595 var ss = io.SliceInStream.init(&bytes);
96 var ps = io.PeekStream(2, io.SliceInStream.Error).init(&ss.stream);
96 var ps = io.PeekStream(.{ .Static = 2 }, io.SliceInStream.Error).init(&ss.stream);
9797
9898 var dest: [4]u8 = undefined;
9999