Skip to content

Commit 6892865

Browse files
committed
FixedBufferStream: match file semantics more by clamping pos
1 parent 04626c1 commit 6892865

File tree

1 file changed

+8
-8
lines changed

1 file changed

+8
-8
lines changed

lib/std/io/fixed_buffer_stream.zig

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -76,21 +76,22 @@ pub fn FixedBufferStream(comptime Buffer: type) type {
7676
}
7777

7878
pub fn seekTo(self: *Self, pos: u64) SeekError!void {
79-
const usize_pos = std.math.cast(usize, pos) catch std.math.maxInt(usize);
80-
self.pos = usize_pos;
79+
self.pos = if (std.math.cast(usize, pos)) |x| x else |_| self.buffer.len;
8180
}
8281

8382
pub fn seekBy(self: *Self, amt: i64) SeekError!void {
8483
if (amt < 0) {
85-
const abs_amt = std.math.cast(usize, -amt) catch std.math.maxInt(usize);
86-
if (abs_amt > self.pos) {
84+
const abs_amt = std.math.absCast(amt);
85+
const abs_amt_usize = std.math.cast(usize, abs_amt) catch std.math.maxInt(usize);
86+
if (abs_amt_usize > self.pos) {
8787
self.pos = 0;
8888
} else {
89-
self.pos -= abs_amt;
89+
self.pos -= abs_amt_usize;
9090
}
9191
} else {
92-
const usize_amt = std.math.cast(usize, amt) catch std.math.maxInt(usize);
93-
self.pos = std.math.add(usize, self.pos, usize_amt) catch std.math.maxInt(usize);
92+
const amt_usize = std.math.cast(usize, amt) catch std.math.maxInt(usize);
93+
const new_pos = std.math.add(usize, self.pos, amt_usize) catch std.math.maxInt(usize);
94+
self.pos = std.math.min(self.buffer.len, new_pos);
9495
}
9596
}
9697

@@ -102,7 +103,6 @@ pub fn FixedBufferStream(comptime Buffer: type) type {
102103
return self.pos;
103104
}
104105

105-
/// Asserts that the seek pos is within the buffer range.
106106
pub fn getWritten(self: Self) []const u8 {
107107
return self.buffer[0..self.pos];
108108
}

0 commit comments

Comments
 (0)