@@ -3,6 +3,9 @@ const io = std.io;
3
3
const assert = std .debug .assert ;
4
4
const testing = std .testing ;
5
5
6
+ /// Creates a readable stream which buffers data
7
+ /// It also supports 'un-reading' data, so that it can be read again.
8
+ /// This makes look-ahead style parsing much easier.
6
9
pub fn BufferedInStream (comptime buffer_type : std.fifo.LinearFifoBufferType , comptime InStreamType : type ) type {
7
10
return struct {
8
11
unbuffered_in_stream : InStreamType ,
@@ -62,6 +65,14 @@ pub fn BufferedInStream(comptime buffer_type: std.fifo.LinearFifoBufferType, com
62
65
return dest .len ;
63
66
}
64
67
68
+ pub fn putBackByte (self : * Self , byte : u8 ) ! void {
69
+ try self .putBack (&[_ ]u8 {byte });
70
+ }
71
+
72
+ pub fn putBack (self : * Self , bytes : []const u8 ) ! void {
73
+ try self .fifo .unget (bytes );
74
+ }
75
+
65
76
pub fn inStream (self : * Self ) InStream {
66
77
return .{ .context = self };
67
78
}
@@ -111,3 +122,36 @@ test "io.BufferedInStream" {
111
122
defer testing .allocator .free (res );
112
123
testing .expectEqualSlices (u8 , str , res );
113
124
}
125
+
126
+ test "io.BufferedInStream.putBack*" {
127
+ const bytes = [_ ]u8 { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 };
128
+ var fbs = io .fixedBufferStream (& bytes );
129
+ var ps = BufferedInStream (.{ .Static = 2 }, @TypeOf (fbs .inStream ())).init (fbs .inStream ());
130
+
131
+ var dest : [4 ]u8 = undefined ;
132
+
133
+ try ps .putBackByte (9 );
134
+ try ps .putBackByte (10 );
135
+
136
+ var read = try ps .inStream ().read (dest [0.. 4]);
137
+ testing .expectEqual (@as (usize , 4 ), read );
138
+ testing .expectEqual (@as (u8 , 10 ), dest [0 ]);
139
+ testing .expectEqual (@as (u8 , 9 ), dest [1 ]);
140
+ testing .expectEqualSlices (u8 , bytes [0.. 2], dest [2.. 4]);
141
+
142
+ read = try ps .inStream ().read (dest [0.. 4]);
143
+ testing .expectEqual (@as (usize , 4 ), read );
144
+ testing .expectEqualSlices (u8 , bytes [2.. 6], dest [0.. 4]);
145
+
146
+ read = try ps .inStream ().read (dest [0.. 4]);
147
+ testing .expectEqual (@as (usize , 2 ), read );
148
+ testing .expectEqualSlices (u8 , bytes [6.. 8], dest [0.. 2]);
149
+
150
+ try ps .putBackByte (11 );
151
+ try ps .putBackByte (12 );
152
+
153
+ read = try ps .inStream ().read (dest [0.. 4]);
154
+ testing .expectEqual (@as (usize , 2 ), read );
155
+ testing .expectEqual (@as (u8 , 12 ), dest [0 ]);
156
+ testing .expectEqual (@as (u8 , 11 ), dest [1 ]);
157
+ }
0 commit comments