You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
114 lines
2.4 KiB
114 lines
2.4 KiB
//! Message string
|
|
use super::*;
|
|
use std::result::Result;
|
|
|
|
pub enum Message
|
|
{
|
|
Str(&'static str),
|
|
String(String),
|
|
Other(Box<dyn fmt::Display + Send + Sync + 'static>),
|
|
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<Cow<'static, str>>
|
|
{
|
|
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<Cow<'_, str>>
|
|
{
|
|
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<Self, Self::Err>
|
|
{
|
|
Ok(Self::String(string.to_string()))
|
|
}
|
|
}
|
|
|
|
impl<T> From<T> 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, "<opaque type>"),
|
|
_=> write!(f, "<unbound>"),
|
|
}?;
|
|
write!(f,")")
|
|
}
|
|
}
|