diff --git a/CHANGELOG.md b/CHANGELOG.md index 5407aa87..198aef99 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,8 @@ +# Unreleased + +### Added +- `QueryIter::peek` to access the next result without advancing the iterator + # 0.9 ### Changed diff --git a/src/query.rs b/src/query.rs index 9e7ba4ec..0f0490c4 100644 --- a/src/query.rs +++ b/src/query.rs @@ -731,6 +731,13 @@ impl<'q, Q: Query> QueryIter<'q, Q> { iter: ChunkIter::empty(), } } + + /// Access the next result without advancing the iterator + pub fn peek(&mut self) -> Option<>::Item> { + // Safety: returned lifetime borrows `self`, ensuring it can't overlap with a future call to + // `peek` or `next` + unsafe { self.iter.peek().map(|x| x.1) } + } } unsafe impl<'q, Q: Query> Send for QueryIter<'q, Q> where >::Item: Send {} @@ -871,15 +878,22 @@ impl ChunkIter { } } + /// Safety: `'a` must be appropriate #[inline] unsafe fn next<'a>(&mut self) -> Option<(u32, >::Item)> { + let result = self.peek()?; + self.position += 1; + Some(result) + } + + /// Safety: `'a` must be appropriate + #[inline] + unsafe fn peek<'a>(&mut self) -> Option<(u32, >::Item)> { if self.position == self.len { return None; } let entity = self.entities.as_ptr().add(self.position); - let item = self.fetch.get(self.position); - self.position += 1; - Some((*entity, item)) + Some((*entity, self.fetch.get(self.position))) } fn remaining(&self) -> usize {