Skip to content

Commit

Permalink
fix: edge case
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolas-vivot committed Mar 18, 2024
1 parent 7e0c86e commit ac73fc8
Showing 1 changed file with 22 additions and 5 deletions.
27 changes: 22 additions & 5 deletions src/slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,21 +151,24 @@ impl<'a, T> NonEmptyIterator for NEChunks<'a, T> {
tail: &self.tail[0..end],
};

self.index = end;
// 2024-03-18: This is a workaround for edge case of 1 element slice, thus the index
// does not get incremented as end is 0, thus the next iteration will return the same
// slice gain and again.
self.index = end + 1;

Some(slice)
} else if self.index >= self.tail.len() {
} else if self.index >= (self.tail.len() + 1) {
None
} else {
// Ensure we never go out of bounds
let end = min(self.index + self.window.get(), self.tail.len());
let slc: &'a [T] = &self.tail[self.index..end];
let end = min(self.index - 1 + self.window.get(), self.tail.len());
let slc: &'a [T] = &self.tail[self.index - 1..end];

match slc {
[] => None,
[head, tail @ ..] => {
let slice = NESlice { head, tail };
self.index = end;
self.index = end + 1;
Some(slice)
}
}
Expand Down Expand Up @@ -338,4 +341,18 @@ mod tests {
]
);
}

// This test cover an edge case non supported by the `chunks` method
// when the slice has only one element.
#[test]
fn chunks_into_iter_edge_case_single_element() {
let v = nev![1];
let n = NonZeroUsize::new(3).unwrap();
let c: crate::slice::NEChunks<'_, i32> = v.nonempty_chunks(n);

let mut iter = c.into_iter();

assert_eq!(1, iter.next().unwrap().len().get());
assert!(iter.next().is_none());
}
}

0 comments on commit ac73fc8

Please sign in to comment.