tsukuyomi/
util.rs

1//! Miscellaneous components used within the framework.
2
3use std::{error::Error as StdError, fmt};
4
5/// A helper type which emulates the standard `never_type` (`!`).
6#[allow(clippy::empty_enum)]
7#[derive(Debug)]
8pub enum Never {}
9
10impl fmt::Display for Never {
11    fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result {
12        match *self {}
13    }
14}
15
16impl StdError for Never {
17    fn description(&self) -> &str {
18        match *self {}
19    }
20
21    fn cause(&self) -> Option<&dyn StdError> {
22        match *self {}
23    }
24}
25
26/// A trait representing the conversion from the arbitrary types.
27///
28/// This trait is an emulation of the standard [`TryFrom`].
29///
30/// [`TryFrom`]: https://doc.rust-lang.org/nightly/std/convert/trait.TryFrom.html
31pub trait TryFrom<T>: Sized {
32    type Error: Into<failure::Error>;
33
34    fn try_from(value: T) -> Result<Self, Self::Error>;
35}
36
37/// A trait representing the conversion into a value of specified type.
38///
39/// This trait is an emulation of the standard [`TryInto`].
40///
41/// [`TryInto`]: https://doc.rust-lang.org/nightly/std/convert/trait.TryInto.html
42pub trait TryInto<T> {
43    type Error: Into<failure::Error>;
44
45    fn try_into(self) -> Result<T, Self::Error>;
46}
47
48impl<T, U> TryInto<U> for T
49where
50    U: TryFrom<T>,
51{
52    type Error = <U as TryFrom<T>>::Error;
53
54    #[inline]
55    fn try_into(self) -> Result<U, Self::Error> {
56        U::try_from(self)
57    }
58}
59
60/// A pair of structs representing arbitrary chain structure.
61#[derive(Debug, Clone)]
62pub struct Chain<L, R> {
63    pub(crate) left: L,
64    pub(crate) right: R,
65}
66
67impl<L, R> Chain<L, R> {
68    pub fn new(left: L, right: R) -> Self {
69        Self { left, right }
70    }
71}
72
73/// A macro for creating a chain of expressions.
74#[macro_export]
75macro_rules! chain {
76    ($e:expr) => ( $e );
77    ($e:expr,) => ( $e );
78    ($h:expr, $($t:expr),+) => ( $crate::util::Chain::new($h, chain!($($t),+)) );
79    ($h:expr, $($t:expr,)+) => ( chain!($h, $($t),+) );
80}
81
82#[derive(Debug, Copy, Clone, PartialEq)]
83pub enum Either<L, R> {
84    Left(L),
85    Right(R),
86}