bstringify

Crates.iobstringify
lib.rsbstringify
version0.1.2
sourcesrc
created_at2020-07-25 22:49:13.886555
updated_at2020-07-25 23:19:18.397205
descriptionstringify! that yields byte string literals instead
homepagehttps://crates.io/crates/bstringify
repositoryhttps://github.com/danielhenrymantilla/rust-bstringify
max_upload_size
id269588
size20,681
Daniel Henry-Mantilla (danielhenrymantilla)

documentation

https://docs.rs/bstringify

README

bstringify!

Like stringify!, but yielding byte string literals instead.

Repository Latest version Documentation License CI

Since .as_bytes() on strings is a const fn, this macro should only be useful to create a byte string literal to match against:

use ::bstringify::bstringify;

/// like FromStr but with [u8] instead
trait FromBytes : Sized {
    fn from_bytes (input: &'_ [u8])
      -> Option<Self>
    ;
}

macro_rules! derive_FromBytes {(
    $(#[$attr:meta])*
    $pub:vis
    enum $EnumName:ident {
        $(
            $Variant:ident
        ),* $(,)?
    }
) => (
    $(#[$attr])*
    $pub
    enum $EnumName {
        $(
            $Variant,
        )*
    }
    
    impl $crate::FromBytes
        for $EnumName
    {
        fn from_bytes (input: &'_ [u8])
          -> Option<Self>
        {
            match input {
            $(
                | bstringify!($Variant) => Some(Self::$Variant),
            )*
                | _ => None,
            }
        }
    }
)}

derive_FromBytes! {
    enum Example {
        Foo,
        Bar,
    }
}

fn main ()
{
    assert!(matches!(
        Example::from_bytes(b"Foo"), Some(Example::Foo)
    ));
    assert!(matches!(
        Example::from_bytes(b"Bar"), Some(Example::Bar)
    ));
    assert!(matches!(
        Example::from_bytes(b"Bad"), None
    ));
}
Commit count: 7

cargo fmt