Merge pull request #45 from dtolnay/chain
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Provide DoubleEndedIterator and ExactSizeIterator for anyhow::Chain
authored by David Tolnay · committed by GitHub · parents 7246344, 9ef3d2d · Browse files · 4 files·+121 added−13 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+121 added−13 removed
- tests:+45 added−0 removed
- other:+76 added−13 removed
Provenance
- Commit
00545d5- Tree
fdc6a1d- Author
David Tolnay <dtolnay@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
7246344- Parent 2
9ef3d2d
4 files changed+121 added−13 removed
added:src/chain.rs+69 added
1+use self::ChainState::{Buffered, Linked};2+use crate::Chain;3+use std::error::Error as StdError;4+use std::vec;5+6+#[derive(Clone)]7+pub(crate) enum ChainState<'a> {8+ Linked {9+ next: Option<&'a (dyn StdError + 'static)>,10+ },11+ Buffered {12+ rest: vec::IntoIter<&'a (dyn StdError + 'static)>,13+ },14+}15+16+impl<'a> Iterator for Chain<'a> {17+ type Item = &'a (dyn StdError + 'static);18+19+ fn next(&mut self) -> Option<Self::Item> {20+ match &mut self.state {21+ Linked { next } => {22+ let error = (*next)?;23+ *next = error.source();24+ Some(error)25+ }26+ Buffered { rest } => rest.next(),27+ }28+ }29+30+ fn size_hint(&self) -> (usize, Option<usize>) {31+ let len = self.len();32+ (len, Some(len))33+ }34+}35+36+impl DoubleEndedIterator for Chain<'_> {37+ fn next_back(&mut self) -> Option<Self::Item> {38+ match &mut self.state {39+ Linked { mut next } => {40+ let mut rest = Vec::new();41+ while let Some(cause) = next {42+ next = cause.source();43+ rest.push(cause);44+ }45+ let mut rest = rest.into_iter();46+ let last = rest.next_back();47+ self.state = Buffered { rest };48+ last49+ }50+ Buffered { rest } => rest.next_back(),51+ }52+ }53+}54+55+impl ExactSizeIterator for Chain<'_> {56+ fn len(&self) -> usize {57+ match &self.state {58+ Linked { mut next } => {59+ let mut len = 0;60+ while let Some(cause) = next {61+ next = cause.source();62+ len += 1;63+ }64+ len65+ }66+ Buffered { rest } => rest.len(),67+ }68+ }69+}modified:src/error.rs+4 added-11 removed
1 use crate::backtrace::Backtrace;2+use crate::chain::ChainState;3 use crate::{Chain, Error};4 use std::any::TypeId;5 use std::error::Error as StdError;6 use std::fmt::{self, Debug, Display};666 unmodified lines673 }674 675 pub(crate) fn chain(&self) -> Chain {676 Chain {677+ state: ChainState::Linked {676- next: Some(self.error()),678+ next: Some(self.error()),679+ },680 }681 }682 }683 44 unmodified lines728 fn from(error: Error) -> Self {729 Box::<dyn StdError + Send + Sync>::from(error)730 }731 }729-730-impl<'a> Iterator for Chain<'a> {731- type Item = &'a (dyn StdError + 'static);732-733- fn next(&mut self) -> Option<Self::Item> {734- let next = self.next?;735- self.next = next.source();736- Some(next)737- }738-}modified:src/lib.rs+3 added-2 removed
167 unmodified lines168 )]169 170 #[macro_use]171 mod backtrace;172+mod chain;173 mod context;174 mod error;175 mod fmt;176 mod kind;1 unmodified line178 179 #[cfg(not(feature = "std"))]180 compile_error!("no_std support is not implemented yet");181 182+use crate::chain::ChainState;183 use crate::error::ErrorImpl;182-use std::error::Error as StdError;184 use std::fmt::Display;185 use std::mem::ManuallyDrop;186 187 pub use anyhow as format_err;114 unmodified lines302 /// }303 /// ```304 #[derive(Clone)]305 pub struct Chain<'a> {305- next: Option<&'a (dyn StdError + 'static)>,306+ state: ChainState<'a>,307 }308 309 /// `Result<T, Error>`310 ///222 unmodified linesadded:tests/test_chain.rs+45 added
1+use anyhow::{anyhow, Error};2+3+fn error() -> Error {4+ anyhow!(0).context(1).context(2).context(3)5+}6+7+#[test]8+fn test_iter() {9+ let e = error();10+ let mut chain = e.chain();11+ assert_eq!("3", chain.next().unwrap().to_string());12+ assert_eq!("2", chain.next().unwrap().to_string());13+ assert_eq!("1", chain.next().unwrap().to_string());14+ assert_eq!("0", chain.next().unwrap().to_string());15+ assert!(chain.next().is_none());16+ assert!(chain.next_back().is_none());17+}18+19+#[test]20+fn test_rev() {21+ let e = error();22+ let mut chain = e.chain().rev();23+ assert_eq!("0", chain.next().unwrap().to_string());24+ assert_eq!("1", chain.next().unwrap().to_string());25+ assert_eq!("2", chain.next().unwrap().to_string());26+ assert_eq!("3", chain.next().unwrap().to_string());27+ assert!(chain.next().is_none());28+ assert!(chain.next_back().is_none());29+}30+31+#[test]32+fn test_len() {33+ let e = error();34+ let mut chain = e.chain();35+ assert_eq!(4, chain.len());36+ assert_eq!("3", chain.next().unwrap().to_string());37+ assert_eq!(3, chain.len());38+ assert_eq!("0", chain.next_back().unwrap().to_string());39+ assert_eq!(2, chain.len());40+ assert_eq!("2", chain.next().unwrap().to_string());41+ assert_eq!(1, chain.len());42+ assert_eq!("1", chain.next_back().unwrap().to_string());43+ assert_eq!(0, chain.len());44+ assert!(chain.next().is_none());45+}