use alloc::{borrow::Cow, boxed::Box, string::ToString};
#[derive(Debug, thiserror::Error)]
#[error("{msg}")]
pub struct ValueError<T> {
msg: Cow<'static, str>,
value: Box<T>,
}
impl<T> ValueError<T> {
pub fn new(value: T, msg: impl core::fmt::Display) -> Self {
Self { msg: Cow::Owned(msg.to_string()), value: Box::new(value) }
}
pub fn new_static(value: T, msg: &'static str) -> Self {
Self { msg: Cow::Borrowed(msg), value: Box::new(value) }
}
pub fn convert<U>(self) -> ValueError<U>
where
U: From<T>,
{
self.map(U::from)
}
pub fn map<U>(self, f: impl FnOnce(T) -> U) -> ValueError<U> {
ValueError { msg: self.msg, value: Box::new(f(*self.value)) }
}
pub fn into_value(self) -> T {
*self.value
}
pub const fn value(&self) -> &T {
&self.value
}
}