serbzip_core/
succinct.rs

1//! Various types and helpers that reduce boilerplate code.
2
3use std::borrow::Cow;
4use std::error::Error;
5use std::fmt::{Debug, Display, Formatter};
6
7/// [`Errorlike`] is a newtype for conditionally implementing the [`Error`] trait on types that
8/// satisfy [`Debug`] and [`Display`] but do not implement [`Error`] directly.
9///
10/// This is used when you need to return an [`Error`], but don't have one handy.
11///
12/// # Examples
13/// ```
14/// use std::error::Error;
15/// use serbzip_core::succinct::CowStr;
16/// use serbzip_core::succinct::Errorlike;
17///
18/// # fn something_wrong() -> bool {
19/// #     false
20/// # }
21/// #
22/// fn main() -> Result<(), Box<dyn Error>> {
23///     if something_wrong() {
24///         return Err(Errorlike("something awful just happened"))?;
25///     }
26///     Ok(())
27/// }
28/// ```
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct Errorlike<T>(pub T);
31
32impl<'a, C> Errorlike<Cow<'a, C>>
33where
34    C: ?Sized + 'a + ToOwned,
35{
36    /// Convenience for constructing an [`Errorlike`] encapsulating a [`Cow`] that contains
37    /// owned data.
38    pub fn owned(c: <C as ToOwned>::Owned) -> Self {
39        Self(Cow::Owned(c))
40    }
41
42    /// Convenience for constructing an [`Errorlike`] encapsulating a [`Cow`] that contains
43    /// borrowed data.
44    pub fn borrowed(c: &'a C) -> Self {
45        Self(Cow::Borrowed(c))
46    }
47}
48
49impl<T: Display + Debug> Display for Errorlike<T> {
50    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
51        Display::fmt(&self.0, f)
52    }
53}
54
55impl<T: Display + Debug> Error for Errorlike<T> {}
56
57/// An alias for a very common type of [`Cow`], being a lazily constructed [`String`] from
58/// a `'static` string slice.
59pub type CowStr = Cow<'static, str>;
60
61#[cfg(test)]
62mod tests;