From 103e79d26a60ef87df304799e8032c6b54698973 Mon Sep 17 00:00:00 2001 From: Nathaniel Theis Date: Tue, 26 May 2015 16:39:18 -0700 Subject: Implement RFC 771: std::iter::once --- src/libcore/iter.rs | 94 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) (limited to 'src/libcore') diff --git a/src/libcore/iter.rs b/src/libcore/iter.rs index 74f3eccab68..9337c501a3a 100644 --- a/src/libcore/iter.rs +++ b/src/libcore/iter.rs @@ -3030,6 +3030,100 @@ pub fn repeat(elt: T) -> Repeat { Repeat{element: elt} } +/// An iterator that yields nothing. +#[unstable(feature="iter_empty", reason = "new addition")] +pub struct Empty(marker::PhantomData); + +#[unstable(feature="iter_empty", reason = "new addition")] +impl Iterator for Empty { + type Item = T; + + fn next(&mut self) -> Option { + None + } + + fn size_hint(&self) -> (usize, Option){ + (0, Some(0)) + } +} + +#[unstable(feature="iter_empty", reason = "new addition")] +impl DoubleEndedIterator for Empty { + fn next_back(&mut self) -> Option { + None + } +} + +#[unstable(feature="iter_empty", reason = "new addition")] +impl ExactSizeIterator for Empty { + fn len(&self) -> usize { + 0 + } +} + +// not #[derive] because that adds a Clone bound on T, +// which isn't necessary. +#[unstable(feature="iter_empty", reason = "new addition")] +impl Clone for Empty { + fn clone(&self) -> Empty { + Empty(marker::PhantomData) + } +} + +// not #[derive] because that adds a Default bound on T, +// which isn't necessary. +#[unstable(feature="iter_empty", reason = "new addition")] +impl Default for Empty { + fn default() -> Empty { + Empty(marker::PhantomData) + } +} + +/// Creates an iterator that yields nothing. +#[unstable(feature="iter_empty", reason = "new addition")] +pub fn empty() -> Empty { + Empty(marker::PhantomData) +} + +/// An iterator that yields an element exactly once. +#[unstable(feature="iter_once", reason = "new addition")] +pub struct Once { + inner: ::option::IntoIter +} + +#[unstable(feature="iter_once", reason = "new addition")] +impl Iterator for Once { + type Item = T; + + fn next(&mut self) -> Option { + self.inner.next() + } + + fn size_hint(&self) -> (usize, Option) { + self.inner.size_hint() + } +} + +#[unstable(feature="iter_once", reason = "new addition")] +impl DoubleEndedIterator for Once { + fn next_back(&mut self) -> Option { + self.inner.next_back() + } +} + +#[unstable(feature="iter_once", reason = "new addition")] +impl ExactSizeIterator for Once { + fn len(&self) -> usize { + self.inner.len() + } +} + +/// Creates an iterator that yields an element exactly once. +#[unstable(feature="iter_once", reason = "new addition")] +pub fn once(value: T) -> Once { + Once { inner: Some(value).into_iter() } +} + /// Functions for lexicographical ordering of sequences. /// /// Lexicographical ordering through `<`, `<=`, `>=`, `>` requires -- cgit 1.4.1-3-g733a5