Skip to content

Commit

Permalink
Make LinearFifo not crash when discarding from empty buffer
Browse files Browse the repository at this point in the history
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
  • Loading branch information
iansimonson authored and andrewrk committed Sep 27, 2020
1 parent ed357f9 commit eab51b7
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 additions & 1 deletion lib/std/fifo.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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();
Expand Down

0 comments on commit eab51b7

Please sign in to comment.