#enums #macro #variant #options #convert #newtype #value

no-std as_variant

A simple macro to convert enums with newtype variants to Options

4 stable releases

1.2.0 Aug 9, 2023
1.1.0 Sep 14, 2022
1.0.1 Sep 13, 2022

#123 in No standard library

Download history 1670/week @ 2024-09-17 2215/week @ 2024-09-24 2000/week @ 2024-10-01 1719/week @ 2024-10-08 2068/week @ 2024-10-15 1499/week @ 2024-10-22 1655/week @ 2024-10-29 1777/week @ 2024-11-05 2225/week @ 2024-11-12 2732/week @ 2024-11-19 3045/week @ 2024-11-26 2796/week @ 2024-12-03 2935/week @ 2024-12-10 3007/week @ 2024-12-17 1437/week @ 2024-12-24 1017/week @ 2024-12-31

8,862 downloads per month
Used in 38 crates (10 directly)

MPL-2.0 license

8KB

as_variant

docs.rs

A simple Rust macro to convert enums with newtype variants to Options.

Basic example:

use std::ops::Deref;

use as_variant::as_variant;

enum Value {
    Integer(i64),
    String(String),
    Array(Vec<Value>),
}

impl Value {
    pub fn as_integer(&self) -> Option<i64> {
        as_variant!(self, Self::Integer).copied()
    }

    pub fn as_str(&self) -> Option<&str> {
        as_variant!(self, Self::String).map(Deref::deref)
    }

    pub fn as_array(&self) -> Option<&[Value]> {
        as_variant!(self, Self::Array).map(Deref::deref)
    }

    pub fn into_string(self) -> Option<String> {
        as_variant!(self, Self::String)
    }

    pub fn into_array(self) -> Option<Vec<Value>> {
        as_variant!(self, Self::Array)
    }
}

lib.rs:

Provides a simple macro to convert enums with newtype variants to Options.

No runtime deps