authorgravatar for frmdstryr@protonmail.comfrmdstryr <frmdstryr@protonmail.com> 2019-12-04 13:23:18-05:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2019-12-05 10:16:50-05:00
log1baaf9a503bd399f4da4a9d3e80695b1739ea966
tree8034e4b1c47ef064db09dc0722f36a4945d3b6d0
parent8829b5316b1ff1dab9d3d985191e40f481d05441

Increase io.BufferedInStream readByte speed by ~75%


2 files changed, 16 insertions(+), 1 deletions(-)

lib/std/io.zig+14
...@@ -107,6 +107,13 @@ pub fn BufferedInStreamCustom(comptime buffer_size: usize, comptime Error: type)...@@ -107,6 +107,13 @@ pub fn BufferedInStreamCustom(comptime buffer_size: usize, comptime Error: type)
107 fn readFn(in_stream: *Stream, dest: []u8) !usize {107 fn readFn(in_stream: *Stream, dest: []u8) !usize {
108 const self = @fieldParentPtr(Self, "stream", in_stream);108 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
110 var dest_index: usize = 0;117 var dest_index: usize = 0;
111 while (true) {118 while (true) {
112 const dest_space = dest.len - dest_index;119 const dest_space = dest.len - dest_index;
...@@ -126,6 +133,13 @@ pub fn BufferedInStreamCustom(comptime buffer_size: usize, comptime Error: type)...@@ -126,6 +133,13 @@ pub fn BufferedInStreamCustom(comptime buffer_size: usize, comptime Error: type)
126 if (dest_space < buffer_size) {133 if (dest_space < buffer_size) {
127 self.start_index = 0;134 self.start_index = 0;
128 self.end_index = try self.unbuffered_in_stream.read(self.buffer[0..]);135 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 }
129 } else {143 } else {
130 // asking for so much data that buffering is actually less efficient.144 // asking for so much data that buffering is actually less efficient.
131 // forward the request directly to the unbuffered stream145 // forward the request directly to the unbuffered stream
lib/std/io/in_stream.zig+2-1
...@@ -174,7 +174,8 @@ pub fn InStream(comptime ReadError: type) type {...@@ -174,7 +174,8 @@ pub fn InStream(comptime ReadError: type) type {
174 /// Reads 1 byte from the stream or returns `error.EndOfStream`.174 /// Reads 1 byte from the stream or returns `error.EndOfStream`.
175 pub fn readByte(self: *Self) !u8 {175 pub fn readByte(self: *Self) !u8 {
176 var result: [1]u8 = undefined;176 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;
178 return result[0];179 return result[0];
179 }180 }
180181