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

Implement SourceIterator and InPlaceIterable for ResultShunt #81619

Merged
merged 4 commits into from
Apr 4, 2021
Merged
Show file tree
Hide file tree
Changes from 2 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
23 changes: 23 additions & 0 deletions library/core/src/iter/adapters/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,3 +191,26 @@ where
self.try_fold(init, ok(fold)).unwrap()
}
}

#[unstable(issue = "none", feature = "inplace_iteration")]
unsafe impl<S: Iterator, I, E> SourceIter for ResultShunt<'_, I, E>
where
I: SourceIter<Source = S>,
{
type Source = S;

#[inline]
unsafe fn as_inner(&mut self) -> &mut S {
// SAFETY: unsafe function forwarding to unsafe function with the same requirements
unsafe { SourceIter::as_inner(&mut self.iter) }
}
}

// SAFETY: ResultShunt::next calls I::find, which has to advance `iter` in order to
// return `Some(_)`. Since `iter` has type `I: InPlaceIterable` it's guaranteed that
// at least one item will be moved out from the underlying source.
#[unstable(issue = "none", feature = "inplace_iteration")]
unsafe impl<I, T, E> InPlaceIterable for ResultShunt<'_, I, E> where
I: Iterator<Item = Result<T, E>> + InPlaceIterable
{
}
26 changes: 26 additions & 0 deletions library/core/tests/iter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,3 +100,29 @@ pub fn extend_for_unit() {
}
assert_eq!(x, 5);
}

#[test]
pub fn inplace_result_collect() {
let src = vec![0usize; 256];
let srcptr = src.as_ptr();
let sink = src.into_iter().map(|i| Ok(i)).collect::<Result<Vec<_>, ()>>().unwrap();
let sinkptr = sink.as_ptr();
assert_eq!(srcptr, sinkptr);

let src: Vec<usize> = vec![0usize; 256];
let srcptr = src.as_ptr();
let iter = src
.into_iter()
.enumerate()
.map(|i| i.0 + i.1)
.zip(std::iter::repeat(1usize))
.map(|(a, b)| a + b)
.map_while(Option::Some)
.peekable()
.skip(1)
.map(|e| std::num::NonZeroUsize::new(e))
.map(|z| z.map(|u| u.get()).ok_or(()));
let sink = iter.collect::<Result<Vec<_>, _>>().unwrap();
let sinkptr = sink.as_ptr();
assert_eq!(srcptr, sinkptr as *const usize);
SkiFire13 marked this conversation as resolved.
Show resolved Hide resolved
}