mycelium_bitfield/
example.rs1use crate::FromBits;
2#[cfg(trace_macros)]
3trace_macros!(true);
4mod example_bitfield;
5#[cfg(trace_macros)]
6trace_macros!(false);
7pub use self::example_bitfield::ExampleBitfield;
8
9#[repr(u8)]
11#[derive(Debug)]
12pub enum TestEnum {
13 Foo = 0b00,
14 Bar = 0b01,
15 Baz = 0b10,
16 Qux = 0b11,
17}
18
19impl FromBits<u64> for TestEnum {
20 const BITS: u32 = 2;
21 type Error = core::convert::Infallible;
22
23 fn try_from_bits(bits: u64) -> Result<Self, Self::Error> {
24 Ok(match bits as u8 {
25 bits if bits == Self::Foo as u8 => Self::Foo,
26 bits if bits == Self::Bar as u8 => Self::Bar,
27 bits if bits == Self::Baz as u8 => Self::Baz,
28 bits if bits == Self::Qux as u8 => Self::Qux,
29 bits => unreachable!("all patterns are covered: {:#b}", bits),
30 })
31 }
32
33 fn into_bits(self) -> u64 {
34 self as u8 as u64
35 }
36}
37
38#[repr(u8)]
43#[derive(Debug)]
44pub enum AnotherTestEnum {
45 Alice = 0b1000,
46 Bob = 0b1100,
47 Charlie = 0b1110,
48}
49
50impl FromBits<u64> for AnotherTestEnum {
51 const BITS: u32 = 4;
52 type Error = &'static str;
53
54 fn try_from_bits(bits: u64) -> Result<Self, Self::Error> {
55 match bits as u8 {
56 bits if bits == Self::Alice as u8 => Ok(Self::Alice),
57 bits if bits == Self::Bob as u8 => Ok(Self::Bob),
58 bits if bits == Self::Charlie as u8 => Ok(Self::Charlie),
59 _ => Err("invalid bit pattern for `AnotherTestEnum`, expected \
60 one of `0b1000`, `0b1100`, or `0b1110`"),
61 }
62 }
63
64 fn into_bits(self) -> u64 {
65 self as u8 as u64
66 }
67}