45: Fix incorrect length calculation for RingBuffer when head > tail r=japaric a=ReeceStevens

When the head index becomes greater than the tail, the `len()` function returns the incorrect length. This causes iterations over ring buffers to stop early as well, since they use the same calculation.

This PR adds two (very minimal) tests that demonstrate the error.

Co-authored-by: Reece Stevens <reecestevens24@gmail.com>
This commit is contained in:
bors[bot] 2018-07-13 04:56:38 +00:00
commit d2beff0cef
2 changed files with 37 additions and 2 deletions

View File

@ -207,7 +207,7 @@ where
let tail = self.tail.load_relaxed().into();
if head > tail {
head - tail
self.capacity().into() + 1 - head + tail
} else {
tail - head
}
@ -335,7 +335,7 @@ macro_rules! impl_ {
let tail = self.tail.load_relaxed();
if head > tail {
head - tail
self.capacity() + 1 - head + tail
} else {
tail - head
}

View File

@ -155,3 +155,38 @@ fn unchecked() {
assert_eq!(rb.len(), N::to_usize() / 2);
}
#[test]
fn len_properly_wraps() {
type N = U3;
let mut rb: RingBuffer<u8, N> = RingBuffer::new();
rb.enqueue(1).unwrap();
assert_eq!(rb.len(), 1);
rb.dequeue();
assert_eq!(rb.len(), 0);
rb.enqueue(2).unwrap();
assert_eq!(rb.len(), 1);
rb.enqueue(3).unwrap();
assert_eq!(rb.len(), 2);
rb.enqueue(4).unwrap();
assert_eq!(rb.len(), 3);
}
#[test]
fn iterator_properly_wraps() {
type N = U3;
let mut rb: RingBuffer<u8, N> = RingBuffer::new();
rb.enqueue(1).unwrap();
rb.dequeue();
rb.enqueue(2).unwrap();
rb.enqueue(3).unwrap();
rb.enqueue(4).unwrap();
let expected = [2, 3, 4];
let mut actual = [0, 0, 0];
for (idx, el) in rb.iter().enumerate() {
actual[idx] = *el;
}
assert_eq!(expected, actual)
}