authorgravatar for ian.simonson@protonmail.comIan Simonson <ian.simonson@protonmail.com> 2020-09-27 15:07:50+10:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2020-09-27 05:46:39-04:00
logeab51b7785ce0989f90a5cdde4b1110f40875ddb
treedf0772f5d0911f497ccd14fb980a4c225f99b0d8
parented357f9897a6c96a1744307b1bc75a370dd85461

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

1 files changed, 11 insertions(+), 1 deletions(-)

lib/std/fifo.zig+11-1
...@@ -186,7 +186,9 @@ pub fn LinearFifo(...@@ -186,7 +186,9 @@ pub fn LinearFifo(
186 } else {186 } else {
187 var head = self.head + count;187 var head = self.head + count;
188 if (powers_of_two) {188 if (powers_of_two) {
189 head &= self.buf.len - 1;189 // Note it is safe to do a wrapping subtract as
190 // bitwise & with all 1s is a noop
191 head &= self.buf.len -% 1;
190 } else {192 } else {
191 head %= self.buf.len;193 head %= self.buf.len;
192 }194 }
...@@ -376,6 +378,14 @@ pub fn LinearFifo(...@@ -376,6 +378,14 @@ pub fn LinearFifo(
376 };378 };
377}379}
378380
381test "LinearFifo(u8, .Dynamic) discard(0) from empty buffer should not error on overflow" {
382 var fifo = LinearFifo(u8, .Dynamic).init(testing.allocator);
383 defer fifo.deinit();
384
385 // If overflow is not explicitly allowed this will crash in debug / safe mode
386 fifo.discard(0);
387}
388
379test "LinearFifo(u8, .Dynamic)" {389test "LinearFifo(u8, .Dynamic)" {
380 var fifo = LinearFifo(u8, .Dynamic).init(testing.allocator);390 var fifo = LinearFifo(u8, .Dynamic).init(testing.allocator);
381 defer fifo.deinit();391 defer fifo.deinit();