Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add QueryIter::peek #282

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
# Unreleased

### Added
- `QueryIter::peek` to access the next result without advancing the iterator

# 0.9

### Changed
Expand Down
20 changes: 17 additions & 3 deletions src/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<<Q::Fetch as Fetch<'_>>::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) }
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why strip the entity ID here if it is returned by the Iterator impl? Isn't that something the caller could need and if not ignore?

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, that should definitely be included.

}
}

unsafe impl<'q, Q: Query> Send for QueryIter<'q, Q> where <Q::Fetch as Fetch<'q>>::Item: Send {}
Expand Down Expand Up @@ -871,15 +878,22 @@ impl<Q: Query> ChunkIter<Q> {
}
}

/// Safety: `'a` must be appropriate
#[inline]
unsafe fn next<'a>(&mut self) -> Option<(u32, <Q::Fetch as Fetch<'a>>::Item)> {
let result = self.peek()?;
self.position += 1;
Some(result)
}

/// Safety: `'a` must be appropriate
#[inline]
unsafe fn peek<'a>(&mut self) -> Option<(u32, <Q::Fetch as Fetch<'a>>::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 {
Expand Down