Skip to main content

impl_enum_from

Macro impl_enum_from 

Source
macro_rules! impl_enum_from {
    (<$($generic:ident),+> in $($rest:tt)+) => { ... };
    (<const $($rest:tt)+) => { ... };
    (<$generic:ident, $($rest:tt)+) => { ... };
    (@impl [$($generic:tt)+] $from:ty => $($target:tt)+) => { ... };
    ($from:ty => $($target:tt)+) => { ... };
    (@parse [$($generic:tt)*] [$from:ty] [$($enum:tt)+]
        :: $variant:ident $(,)?) => { ... };
    (@parse [$($generic:tt)*] [$from:ty] [$($enum:tt)+]
        :: $variant:ident { $field:ident $(,)? } $(,)?) => { ... };
    (@parse [$($generic:tt)*] [$from:ty] [$($path:tt)*]
        $next:tt $($rest:tt)+) => { ... };
}
Expand description

Implement From for an enum variant with one named or unnamed field.

The destination is the enum path followed by the variant name. Each source type can have only one conversion into a given enum. Generic conversions must not overlap with other conversions for any choice of type arguments.

Declare type and const parameters before in.

ยงExamples

With an error enum:

enum Error {
    Io(std::io::Error),
}

impl_more::impl_enum_from!(std::io::Error => Error::Io);

fn read() -> Result<String, Error> {
    Ok(std::fs::read_to_string("config.txt")?)
}

With a named field:

enum Error {
    Io { source: std::io::Error },
}

impl_more::impl_enum_from!(std::io::Error => Error::Io { source });

let error = Error::from(std::io::Error::from(std::io::ErrorKind::NotFound));
assert!(matches!(error, Error::Io { source } if source.kind() == std::io::ErrorKind::NotFound));

With a generic enum and a module path:

mod errors {
    pub enum Error<T> {
        Io(std::io::Error),
        Other(Vec<T>),
    }
}

impl_more::impl_enum_from!(<T> in std::io::Error => errors::Error<T>::Io);
impl_more::impl_enum_from!(<T> in Vec<T> => errors::Error<T>::Other);

let error = errors::Error::from(vec![42_u32]);
assert!(matches!(error, errors::Error::Other(values) if values == [42]));

With type and const parameters:

enum Value<T, const N: usize> {
    Items([T; N]),
}

impl_more::impl_enum_from!(<T, const N: usize> in [T; N] => Value<T, N>::Items);

let value = Value::from([1, 2, 3]);
assert!(matches!(value, Value::Items([1, 2, 3])));