Crate uncon_derive [] [src]

Support for deriving traits found in uncon.

Usage

This crate is available on crates.io and can be used by adding the following to your project's Cargo.toml:

[dependencies]
uncon_derive = "1.1.1"
uncon = "1.1.0"

and this to your crate root:

#[macro_use]
extern crate uncon_derive;
extern crate uncon;

Examples

The FromUnchecked trait can be derived for:

  • Structs with a single field
  • C-like enums with #[repr] attribute
#[derive(FromUnchecked)]
struct U4 {
    bits: u8
}

#[derive(FromUnchecked, PartialEq, Debug)]
#[uncon(impl_from, other(u16, u32, u64, usize))]
#[repr(u8)]
enum Flag {
    A, B, C, D
}

// `usize` and `isize` also supported:
#[derive(FromUnchecked)]
#[repr(usize)]
enum Value {
    X, Y, Z
}

unsafe {
    let b = 0b1010;
    let x = U4::from_unchecked(b);
    assert_eq!(x.bits, b);

    let n = 2u8;
    let f = Flag::from_unchecked(n);
    assert_eq!(f, Flag::C);

    // Done via `#[uncon(other(u32, ...))]`
    assert_eq!(Flag::from_unchecked(n as u32), f);

    // Done via `#[uncon(impl_from)]`
    assert_eq!(Flag::from(5usize), Flag::B);
}

Options

  • Derive FromUnchecked for other types:

    • Done via #[uncon(other(...))].
    • Derives FromUnchecked with each type listed via an as cast to the inner or representative type.
  • Derive From:

    • Done via #[uncon(from_impl)].
    • Only for C-like enums such that no variant is assigned a discriminant.