Skip to content

Commit

Permalink
Introduce or_item functions to IteratorExt.
Browse files Browse the repository at this point in the history
  • Loading branch information
olson-sean-k committed Jun 20, 2024
1 parent 0dd8c0c commit 4528cff
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,19 @@ let xs = Vec1::from([0i32, 1, 2]);
let ys: Vec1<_> = xs.into_iter1().map(|x| x + 1).collect();
```

Bridging between `Iterator` and `Iterator1`:

```rust
use mitsein::iter1;
use mitsein::prelude::*;
use mitsein::vec1::Vec1;

let xs = iter1::from_head_and_tail(0i32, [1, 2]);
let xs: Vec1<_> = xs.into_iter().skip(3).or_item(3).collect();

assert_eq!(xs.as_slice(), &[3]);
```

## Features and Comparisons

By providing non-empty APIs over both collections **and** views (i.e., slices
Expand Down
26 changes: 26 additions & 0 deletions src/iter1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,15 @@ pub trait IteratorExt: Iterator {
where
Self: Sized,
T: IntoIterator1<Item = Self::Item>;

fn or_item(self, item: Self::Item) -> OrItem<Self>
where
Self: Sized;

fn or_else_item<F>(self, f: F) -> OrElseItem<Self, F>
where
Self: Sized,
F: FnInto<Into = Self::Item>;
}

impl<I> IteratorExt for I
Expand All @@ -41,6 +50,23 @@ where
{
Iterator1::from_iter_unchecked(self.chain(items.into_iter1()))
}

fn or_item(self, item: Self::Item) -> OrItem<Self> {
match Iterator1::try_from_iter(self) {
Ok(items) => items.chain(None),
Err(empty) => Iterator1::from_iter_unchecked(empty.chain(Some(item))),
}
}

fn or_else_item<F>(self, f: F) -> OrElseItem<Self, F>
where
F: FnInto<Into = Self::Item>,
{
match Iterator1::try_from_iter(self) {
Ok(items) => items.chain(AtMostOneWith::none()),
Err(empty) => Iterator1::from_iter_unchecked(empty.chain(AtMostOneWith::some(f))),
}
}
}

pub trait FromIterator1<T> {
Expand Down

0 comments on commit 4528cff

Please sign in to comment.