iter.rs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. //
  2. // imag - the personal information management suite for the commandline
  3. // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
  4. //
  5. // This library is free software; you can redistribute it and/or
  6. // modify it under the terms of the GNU Lesser General Public
  7. // License as published by the Free Software Foundation; version
  8. // 2.1 of the License.
  9. //
  10. // This library is distributed in the hope that it will be useful,
  11. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. // Lesser General Public License for more details.
  14. //
  15. // You should have received a copy of the GNU Lesser General Public
  16. // License along with this library; if not, write to the Free Software
  17. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  18. //
  19. /// Folds its contents to a result.
  20. pub trait FoldResult: Sized {
  21. type Item;
  22. /// Processes all contained items returning the last successful result or the first error.
  23. /// If there are no items, returns `Ok(R::default())`.
  24. fn fold_defresult<R, E, F>(self, func: F) -> Result<R, E>
  25. where R: Default,
  26. F: FnMut(Self::Item)
  27. -> Result<R, E>
  28. {
  29. self.fold_result(R::default(), func)
  30. }
  31. /// Processes all contained items returning the last successful result or the first error.
  32. /// If there are no items, returns `Ok(default)`.
  33. fn fold_result<R, E, F>(self, default: R, mut func: F) -> Result<R, E>
  34. where F: FnMut(Self::Item) -> Result<R, E>;
  35. }
  36. impl<X, I: Iterator<Item = X>> FoldResult for I {
  37. type Item = X;
  38. fn fold_result<R, E, F>(self, default: R, mut func: F) -> Result<R, E>
  39. where F: FnMut(Self::Item) -> Result<R, E>
  40. {
  41. self.fold(Ok(default), |acc, item| acc.and_then(|_| func(item)))
  42. }
  43. }