Skip to content

Commit eab51b7

Browse files
iansimonsonandrewrk
authored andcommitted
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 parent ed357f9 commit eab51b7

File tree

1 file changed

+11
-1
lines changed

1 file changed

+11
-1
lines changed

lib/std/fifo.zig

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,9 @@ pub fn LinearFifo(
186186
} else {
187187
var head = self.head + count;
188188
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;
190192
} else {
191193
head %= self.buf.len;
192194
}
@@ -376,6 +378,14 @@ pub fn LinearFifo(
376378
};
377379
}
378380

381+
test "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+
379389
test "LinearFifo(u8, .Dynamic)" {
380390
var fifo = LinearFifo(u8, .Dynamic).init(testing.allocator);
381391
defer fifo.deinit();

0 commit comments

Comments
 (0)