Implement DoubleEndedIterator for Chain
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Tolnay · committed by David Tolnay · parent a8c199b · Browse files · 3 files·+45 added−6 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+45 added−6 removed
- other:+45 added−6 removed
Provenance
- Commit
a2caba0- Tree
93ba15a- Author
David Tolnay <dtolnay@gmail.com>- Committer
David Tolnay <dtolnay@gmail.com>- Parent
a8c199b
3 files changed+45 added−6 removed
modified:src/chain.rs+39 added-3 removed
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> {8- let next = self.next?;9- self.next = next.source();10- Some(next)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+31+impl DoubleEndedIterator for Chain<'_> {32+ fn next_back(&mut self) -> Option<Self::Item> {33+ match &mut self.state {34+ Linked { mut next } => {35+ let mut rest = Vec::new();36+ while let Some(cause) = next {37+ next = cause.source();38+ rest.push(cause);39+ }40+ let mut rest = rest.into_iter();41+ let last = rest.next_back();42+ self.state = Buffered { rest };43+ last44+ }45+ Buffered { rest } => rest.next_back(),46+ }47+ }48+}modified:src/error.rs+4 added-1 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 48 unmodified linesmodified:src/lib.rs+2 added-2 removed
177 unmodified lines178 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;183-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> {306- next: Option<&'a (dyn StdError + 'static)>,306+ state: ChainState<'a>,307 }308 309 /// `Result<T, Error>`310 ///222 unmodified lines