//! Message string use super::*; use std::result::Result; pub enum Message { Str(&'static str), String(String), Other(Box), None, } impl cmp::PartialEq for Message { fn eq(&self, other: &Self) -> bool { self.as_str() == other.as_str() } } impl Message { /// Into the internal string pub fn into_string(self) -> Option> { Some(match self { Self::Str(string) => Cow::Borrowed(string), Self::String(string) => Cow::Owned(string), Self::Other(other) => Cow::Owned(other.to_string()), _ => return None, }) } /// Returns message as a string, either created from `format!`, or referenced from inner pub fn as_str(&self) -> Option> { Some(match self { Self::Str(string) => Cow::Borrowed(string), Self::String(string) => Cow::Borrowed(&string), Self::Other(other) => Cow::Owned(other.to_string()), _ => return None, }) } pub const fn from_str(string: &'static str) -> Self { Self::Str(string) } pub const fn from_string(string: String) -> Self { Self::String(string) } pub fn from_other(other: impl fmt::Display + Send + Sync + 'static) -> Self { Self::Other(Box::new(other)) } pub const fn none() -> Self { Self::None } pub fn fmt(&self) -> impl fmt::Display + '_ { struct Format<'a>(&'a Message); impl<'a> fmt::Display for Format<'a> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.0 { Message::Str(string) => write!(f, "{}", string), Message::String(string) => write!(f, "{}", string), Message::Other(other) => write!(f, "{}", other), _ => Ok(()) } } } Format(&self) } } impl FromStr for Message { type Err = !; fn from_str(string: &str) -> Result { Ok(Self::String(string.to_string())) } } impl From for Message where T: fmt::Display + 'static + Send + Sync { fn from(from: T) -> Self { Self::from_other(from) } } impl fmt::Debug for Message { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "error::Message (")?; match self { Self::Str(string) => write!(f, "{:?}", string), Self::String(string) => write!(f, "{:?}", string), Self::Other(_) => write!(f, ""), _=> write!(f, ""), }?; write!(f,")") } }