Skip to content

Commit

Permalink
added sanity tests, more details in readme
Browse files Browse the repository at this point in the history
  • Loading branch information
carlsverre committed Nov 8, 2024
1 parent c82cc6a commit 2de5c26
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,13 @@ Utility functions for Iterators of Results. This crate is heavily inspired by [T

This crate exports a trait called `TryIteratorExt` which provides utility methods on top of any Iterator which returns a `Result`. `TryIteratorExt` is automatically implemented on top of compatible Iterators via a generic `impl` so all you have to do is import the trait and start calling methods on your iterators.

The methods provide two fundamental simplifications over regular Iterator methods:

1. They operate directly on `Ok` or `Err` values, passing through the other values transparently.
2. They take in fallible closures which can return `Err`.

See [tests/sanity.rs](./tests/sanity.rs) for a quick overview of using this crate.

## Release Stability

This crate is still pre-1.0 and will be until someone wants to use it in production. If you want to use it before that point please pin a specific version number and be prepared for breaking changes.
54 changes: 54 additions & 0 deletions tests/sanity.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
use tryiter::TryIteratorExt;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct MyErr;

fn example_next(vals: Vec<Result<i32, MyErr>>) -> Result<(), MyErr> {
for result in vals {
let result = result?;
println!("{}", result);
}
Ok(())
}

fn example_try_next(vals: Vec<Result<i32, MyErr>>) -> Result<(), MyErr> {
let mut iter = vals.into_iter();
while let Some(result) = iter.try_next()? {
println!("{}", result);
}
Ok(())
}

#[test]
fn test_sanity() {
let vals = vec![Ok(1), Ok(2), Ok(3), Err(MyErr), Ok(4)];

example_next(vals.clone()).expect_err("error");
example_try_next(vals.clone()).expect_err("error");

// TryIteratorExt also provides helpful Result friendly methods:
let vals: Vec<Result<i32, MyErr>> = vec![Ok(1), Ok(2), Ok(3), Ok(4)];

// assert that all elements are less than 5
assert_eq!(vals.iter().cloned().try_all(|x| Ok(x < 5)), Ok(true));

// is any element equal to 3?
assert_eq!(vals.iter().cloned().try_any(|x| Ok(x == 3)), Ok(true));

// do a series of fallible operations
let mut iter = vals
.iter()
.cloned()
.map_ok(|x| Ok(x * 2))
.try_filter(|x| Ok(*x < 4));
while let Some(val) = iter.try_next().expect("error") {
println!("{}", val);
}

// raise an error during processing
vals.iter()
.cloned()
.map_ok(|_| Err::<i32, _>(MyErr))
.try_next()
.expect_err("error");
}

0 comments on commit 2de5c26

Please sign in to comment.