Skip to content

Commit

Permalink
Improve ExactlyOneError
Browse files Browse the repository at this point in the history
  • Loading branch information
Xaeroxe committed Dec 3, 2018
1 parent 44d50da commit 094b416
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 14 deletions.
24 changes: 14 additions & 10 deletions src/exactly_one_err.rs
@@ -1,3 +1,5 @@
use std::iter::ExactSizeIterator;

use size_hint;

/// Iterator returned for the error case of `IterTools::exactly_one()`
Expand All @@ -9,31 +11,31 @@ use size_hint;
/// This is very similar to PutBackN except this iterator only supports 0-2 elements and does not
/// use a `Vec`.
#[derive(Debug, Clone)]
pub struct ExactlyOneErr<T, I>
pub struct ExactlyOneError<I>
where
I: Iterator<Item = T>,
I: Iterator,
{
first_two: (Option<T>, Option<T>),
first_two: (Option<I::Item>, Option<I::Item>),
inner: I,
}

impl<T, I> ExactlyOneErr<T, I>
impl<I> ExactlyOneError<I>
where
I: Iterator<Item = T>,
I: Iterator,
{
/// Creates a new `ExactlyOneErr` iterator.
pub fn new(first_two: (Option<T>, Option<T>), inner: I) -> Self {
pub fn new(first_two: (Option<I::Item>, Option<I::Item>), inner: I) -> Self {
Self { first_two, inner }
}
}

impl<T, I> Iterator for ExactlyOneErr<T, I>
impl<I> Iterator for ExactlyOneError<I>
where
I: Iterator<Item = T>,
I: Iterator,
{
type Item = T;
type Item = I::Item;

fn next(&mut self) -> Option<T> {
fn next(&mut self) -> Option<Self::Item> {
self.first_two
.0
.take()
Expand All @@ -52,3 +54,5 @@ where
size_hint::add_scalar(self.inner.size_hint(), additional_len)
}
}

impl<I> ExactSizeIterator for ExactlyOneError<I> where I: ExactSizeIterator {}
8 changes: 4 additions & 4 deletions src/lib.rs
Expand Up @@ -74,7 +74,7 @@ pub mod structs {
#[cfg(feature = "use_std")]
pub use combinations::Combinations;
pub use cons_tuples_impl::ConsTuples;
pub use exactly_one_err::ExactlyOneErr;
pub use exactly_one_err::ExactlyOneError;
pub use format::{Format, FormatWith};
#[cfg(feature = "use_std")]
pub use groupbylazy::{IntoChunks, Chunk, Chunks, GroupBy, Group, Groups};
Expand Down Expand Up @@ -2003,22 +2003,22 @@ pub trait Itertools : Iterator {
/// assert!((0..10).filter(|&x| x > 1 && x < 5).exactly_one().unwrap_err().eq(2..5));
/// assert!((0..10).filter(|&x| false).exactly_one().unwrap_err().eq(0..0));
/// ```
fn exactly_one(mut self) -> Result<Self::Item, ExactlyOneErr<Self::Item, Self>>
fn exactly_one(mut self) -> Result<Self::Item, ExactlyOneError<Self>>
where
Self: Sized,
{
match self.next() {
Some(first) => {
match self.next() {
Some(second) => {
Err(ExactlyOneErr::new((Some(first), Some(second)), self))
Err(ExactlyOneError::new((Some(first), Some(second)), self))
}
None => {
Ok(first)
}
}
}
None => Err(ExactlyOneErr::new((None, None), self)),
None => Err(ExactlyOneError::new((None, None), self)),
}
}
}
Expand Down

0 comments on commit 094b416

Please sign in to comment.