aboutsummaryrefslogtreecommitdiff
path: root/lib/std
diff options
context:
space:
mode:
authorIan Simonson <ian.simonson@protonmail.com>2020-09-27 15:07:50 +1000
committerAndrew Kelley <andrew@ziglang.org>2020-09-27 05:46:39 -0400
commiteab51b7785ce0989f90a5cdde4b1110f40875ddb (patch)
treedf0772f5d0911f497ccd14fb980a4c225f99b0d8 /lib/std
parented357f9897a6c96a1744307b1bc75a370dd85461 (diff)
downloadzig-eab51b7785ce0989f90a5cdde4b1110f40875ddb.tar.gz
zig-eab51b7785ce0989f90a5cdde4b1110f40875ddb.zip
Make LinearFifo not crash when discarding from empty buffer
Previously if a LinearFifo was empty and discard was called an unsigned overflow would occur. However it is safe to perform this overflow as a bitwise & operation with 0xFFFFFFFFFFFFFF is a noop
Diffstat (limited to 'lib/std')
-rw-r--r--lib/std/fifo.zig12
1 files changed, 11 insertions, 1 deletions
diff --git a/lib/std/fifo.zig b/lib/std/fifo.zig
index c92da615f9..91d4c0330b 100644
--- a/lib/std/fifo.zig
+++ b/lib/std/fifo.zig
@@ -186,7 +186,9 @@ pub fn LinearFifo(
} else {
var head = self.head + count;
if (powers_of_two) {
- head &= self.buf.len - 1;
+ // Note it is safe to do a wrapping subtract as
+ // bitwise & with all 1s is a noop
+ head &= self.buf.len -% 1;
} else {
head %= self.buf.len;
}
@@ -376,6 +378,14 @@ pub fn LinearFifo(
};
}
+test "LinearFifo(u8, .Dynamic) discard(0) from empty buffer should not error on overflow" {
+ var fifo = LinearFifo(u8, .Dynamic).init(testing.allocator);
+ defer fifo.deinit();
+
+ // If overflow is not explicitly allowed this will crash in debug / safe mode
+ fifo.discard(0);
+}
+
test "LinearFifo(u8, .Dynamic)" {
var fifo = LinearFifo(u8, .Dynamic).init(testing.allocator);
defer fifo.deinit();