From 6370f6b5f7a8dfdc3857f2e80e0ae8791dd549d6 Mon Sep 17 00:00:00 2001 From: Sergio Benitez Date: Tue, 9 Apr 2024 18:12:06 -0700 Subject: [PATCH] Export 'Error::chain()'. Impl 'Error: From<&str>'. --- src/error.rs | 52 ++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 44 insertions(+), 8 deletions(-) diff --git a/src/error.rs b/src/error.rs index b5c9311..1f08041 100644 --- a/src/error.rs +++ b/src/error.rs @@ -23,15 +23,17 @@ pub type Result = std::result::Result; /// /// Broadly, there are two ways to construct an `Error`: /// -/// * Via an error message, since `Error` impls `From`: +/// * With an error message, as `Error` impls `From` and `From<&str>`: /// /// ``` /// use figment::Error; /// -/// Error::from("whoops, something went wrong!".to_string()); +/// Error::from(format!("{} is invalid", 1)); +/// +/// Error::from("whoops, something went wrong!"); /// ``` /// -/// * Via a [`Kind`], since `Error` impls `From`: +/// * With a [`Kind`], as `Error` impls `From`: /// /// ``` /// use figment::{error::{Error, Kind}, value::Value}; @@ -144,11 +146,6 @@ impl Error { self } - pub(crate) fn chain(self, mut error: Error) -> Self { - error.prev = Some(Box::new(self)); - error - } - pub(crate) fn retagged(mut self, tag: Tag) -> Self { if self.tag.is_default() { self.tag = tag; @@ -201,6 +198,39 @@ impl Error { self } + /// Prepends `self` to `error` and returns `error`. + /// + /// ```rust + /// use figment::error::Error; + /// + /// let e1 = Error::from("1"); + /// let e2 = Error::from("2"); + /// let e3 = Error::from("3"); + /// + /// let error = e1.chain(e2).chain(e3); + /// assert_eq!(error.count(), 3); + /// + /// let unchained = error.into_iter() + /// .map(|e| e.to_string()) + /// .collect::>(); + /// assert_eq!(unchained, vec!["3", "2", "1"]); + /// + /// let e1 = Error::from("1"); + /// let e2 = Error::from("2"); + /// let e3 = Error::from("3"); + /// let error = e3.chain(e2).chain(e1); + /// assert_eq!(error.count(), 3); + /// + /// let unchained = error.into_iter() + /// .map(|e| e.to_string()) + /// .collect::>(); + /// assert_eq!(unchained, vec!["1", "2", "3"]); + /// ``` + pub fn chain(self, mut error: Error) -> Self { + error.prev = Some(Box::new(self)); + error + } + /// Returns the number of errors represented by `self`. /// /// # Example @@ -386,6 +416,12 @@ impl From for Error { } } +impl From<&str> for Error { + fn from(string: &str) -> Error { + Kind::Message(string.into()).into() + } +} + impl From for Error { fn from(string: String) -> Error { Kind::Message(string).into()