Skip to content

Commit 1baaf9a

Browse files
frmdstryrandrewrk
authored andcommitted
Increase io.BufferedInStream readByte speed by ~75%
1 parent 8829b53 commit 1baaf9a

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

lib/std/io.zig

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,13 @@ pub fn BufferedInStreamCustom(comptime buffer_size: usize, comptime Error: type)
107107
fn readFn(in_stream: *Stream, dest: []u8) !usize {
108108
const self = @fieldParentPtr(Self, "stream", in_stream);
109109

110+
// Hot path for one byte reads
111+
if (dest.len == 1 and self.end_index > self.start_index) {
112+
dest[0] = self.buffer[self.start_index];
113+
self.start_index += 1;
114+
return 1;
115+
}
116+
110117
var dest_index: usize = 0;
111118
while (true) {
112119
const dest_space = dest.len - dest_index;
@@ -126,6 +133,13 @@ pub fn BufferedInStreamCustom(comptime buffer_size: usize, comptime Error: type)
126133
if (dest_space < buffer_size) {
127134
self.start_index = 0;
128135
self.end_index = try self.unbuffered_in_stream.read(self.buffer[0..]);
136+
137+
// Shortcut
138+
if (self.end_index >= dest_space) {
139+
mem.copy(u8, dest[dest_index..], self.buffer[0..dest_space]);
140+
self.start_index = dest_space;
141+
return dest.len;
142+
}
129143
} else {
130144
// asking for so much data that buffering is actually less efficient.
131145
// forward the request directly to the unbuffered stream

lib/std/io/in_stream.zig

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,8 @@ pub fn InStream(comptime ReadError: type) type {
174174
/// Reads 1 byte from the stream or returns `error.EndOfStream`.
175175
pub fn readByte(self: *Self) !u8 {
176176
var result: [1]u8 = undefined;
177-
try self.readNoEof(result[0..]);
177+
const amt_read = try self.read(result[0..]);
178+
if (amt_read < 1) return error.EndOfStream;
178179
return result[0];
179180
}
180181

0 commit comments

Comments
 (0)