summaryrefslogtreecommitdiffstats
path: root/libimagutil
diff options
context:
space:
mode:
authorJohn Sirois <john.sirois@gmail.com>2016-07-14 07:28:50 -0600
committerJohn Sirois <john.sirois@gmail.com>2016-07-14 07:28:54 -0600
commit7f57e5e23400e83102f7fbc830080e53793e959f (patch)
tree0dd9e7fd697fa296d6f3faa7f99ee67178338a14 /libimagutil
parent2c40b8734eece9f1a265dc4ede9d244788a79bc4 (diff)
Move from a helper function to a typeclass.
This introduces the `FoldResut` trait to move from `func(receiver, ...)` style to `receiver.func(...)` style. Also add a means to pass the default result explicitly.
Diffstat (limited to 'libimagutil')
-rw-r--r--libimagutil/src/iter.rs36
1 files changed, 29 insertions, 7 deletions
diff --git a/libimagutil/src/iter.rs b/libimagutil/src/iter.rs
index 0f682bff..52d723bf 100644
--- a/libimagutil/src/iter.rs
+++ b/libimagutil/src/iter.rs
@@ -1,8 +1,30 @@
-/// Processes `iter` returning the last successful result or the first error.
-pub fn fold_ok<X, I, R, E, F>(iter: I, mut func: F) -> Result<R, E>
- where I: Iterator<Item = X>,
- R: Default,
- F: FnMut(X) -> Result<R, E>
-{
- iter.fold(Ok(R::default()), |acc, item| acc.and_then(|_| func(item)))
+/// Folds its contents to a result.
+pub trait FoldResult: Sized {
+ type Item;
+
+ /// Processes all contained items returning the last successful result or the first error.
+ /// If there are no items, returns `Ok(R::default())`.
+ fn fold_defresult<R, E, F>(self, func: F) -> Result<R, E>
+ where R: Default,
+ F: FnMut(Self::Item)
+ -> Result<R, E>
+ {
+ self.fold_result(R::default(), func)
+ }
+
+ /// Processes all contained items returning the last successful result or the first error.
+ /// If there are no items, returns `Ok(default)`.
+ fn fold_result<R, E, F>(self, default: R, mut func: F) -> Result<R, E>
+ where F: FnMut(Self::Item) -> Result<R, E>;
}
+
+impl<X, I: Iterator<Item = X>> FoldResult for I {
+ type Item = X;
+
+ fn fold_result<R, E, F>(self, default: R, mut func: F) -> Result<R, E>
+ where F: FnMut(Self::Item) -> Result<R, E>
+ {
+ self.fold(Ok(default), |acc, item| acc.and_then(|_| func(item)))
+ }
+}
+