filterable-enum 0.2.0

A library for generating filterable enums (Combining bitflags and discriminated unions)
Documentation
use filterable_enum::{filterable_enum, FilterableEnum};

macro_rules! check_layout {
    ($test:ident, $repr:literal, $integer:ty) => {
        #[test]
        fn $test() {
            #[filterable_enum(repr = $repr)]
            enum Value {
                Unit,
                Tuple(u8, u8),
                Named { number: u64 },
            }

            let values = [
                (Value::Unit, ValueKind::Unit, 1),
                (Value::Tuple(7, 9), ValueKind::Tuple, 2),
                (Value::Named { number: 42 }, ValueKind::Named, 4),
            ];
            for (value, kind, bits) in values {
                // SAFETY: The macro gives Value repr($integer), which places
                // the initialized discriminant at offset zero.
                let tag = unsafe { *(&value as *const Value).cast::<$integer>() };
                assert_eq!(tag, bits);
                assert_eq!(tag, kind as $integer);
                assert_eq!(value.filterable_id(), kind);
                match value.filter_and_take(kind).unwrap() {
                    Value::Unit => {}
                    Value::Tuple(a, b) => assert_eq!((a, b), (7, 9)),
                    Value::Named { number } => assert_eq!(number, 42),
                }
            }
        }
    };
}

check_layout!(test_u8, "u8", u8);
check_layout!(test_u16, "u16", u16);
check_layout!(test_u32, "u32", u32);
check_layout!(test_u64, "u64", u64);
check_layout!(test_u128, "u128", u128);

#[test]
fn test_default_representation() {
    #[filterable_enum]
    enum Value {
        Only,
    }

    assert_eq!(std::mem::size_of::<Value>(), std::mem::size_of::<u32>());
    assert_eq!(std::mem::size_of::<ValueKind>(), std::mem::size_of::<u32>());
    assert_eq!(Value::Only.filterable_id(), ValueKind::Only);
}

#[test]
fn test_full_u8_capacity_without_extra_tag() {
    #[filterable_enum(repr = "u8")]
    enum Small {
        A(u8),
        B(u8),
        C(u8),
        D(u8),
        E(u8),
        F(u8),
        G(u8),
        H(u8),
    }

    // A one-byte tag plus a one-byte payload, with no wrapper tag.
    assert_eq!(std::mem::size_of::<Small>(), 2);
    for (index, value) in [
        Small::A(0),
        Small::B(1),
        Small::C(2),
        Small::D(3),
        Small::E(4),
        Small::F(5),
        Small::G(6),
        Small::H(7),
    ]
    .into_iter()
    .enumerate()
    {
        assert_eq!(value.filterable_id() as u8, 1 << index);
        let payload = match value {
            Small::A(n)
            | Small::B(n)
            | Small::C(n)
            | Small::D(n)
            | Small::E(n)
            | Small::F(n)
            | Small::G(n)
            | Small::H(n) => n,
        };
        assert_eq!(payload as usize, index);
    }
}