1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
#![doc = include_str!("../README.md")]
#![warn(missing_docs, rustdoc::broken_intra_doc_links)]
#![cfg_attr(not(test), no_std)]
#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg, doc_cfg_hide))]
#![cfg_attr(docsrs, doc(cfg_hide(docsrs)))]
#![cfg_attr(trace_macros, feature(trace_macros))]
use core::{convert::Infallible, fmt};

pub mod pack;
pub use self::pack::*;
mod bitfield;

/// An example of the code generated by the [`bitfield!`] macro.
///
/// > **Warning**: This module is included for DEMONSTRATION PURPOSES ONLY.
/// > This module is *not* part of the public API of this crate; it is provided
/// > as documentation only, and may change in non-breaking releases.
///
/// The [`ExampleBitfield`] type in this module was generated by the
/// following [`bitfield!`] invocation:
///
/// ```
#[doc = include_str!("example/example_bitfield.rs")]
/// ```
///
/// This module also contains two example types implementing the
/// [`FromBits`] trait, as a demonstration of how typed enums can
/// be used with the [`bitfield!`] macro.
///
///
/// [`ExampleBitfield`]: example::ExampleBitfield
#[cfg(any(test, docsrs, trace_macros))]
#[allow(missing_docs)]
pub mod example;

/// Trait implemented by values which can be converted to and from raw bits.
pub trait FromBits<B>: Sized {
    /// The error type returned by [`Self::try_from_bits`] when an invalid bit
    /// pattern is encountered.
    ///
    /// If all bit patterns possible in [`Self::BITS`] bits are valid bit
    /// patterns for a `Self`-typed value, this should generally be
    /// [`core::convert::Infallible`].
    type Error: fmt::Display;

    /// The number of bits required to represent a value of this type.
    const BITS: u32;

    /// Attempt to convert `bits` into a value of this type.
    ///
    /// # Returns
    ///
    /// - `Ok(Self)` if `bits` contained a valid bit pattern for a value of this
    ///   type.
    /// - `Err(Self::Error)` if `bits` is an invalid bit pattern for a value of
    ///   this type.
    fn try_from_bits(bits: B) -> Result<Self, Self::Error>;

    /// Convert `self` into a raw bit representation.
    ///
    /// In general, this will be a low-cost conversion (e.g., for `enum`s, this
    /// is generally an `as` cast).
    fn into_bits(self) -> B;
}

macro_rules! impl_frombits_for_ty {
   ($(impl FromBits<$($F:ty),+> for $T:ty {})+) => {
        $(

            $(
                impl FromBits<$F> for $T {
                    const BITS: u32 = <$T>::BITS;
                    type Error = Infallible;

                    fn try_from_bits(f: $F) -> Result<Self, Self::Error> {
                        Ok(f as $T)
                    }

                    fn into_bits(self) -> $F {
                        self as $F
                    }
                }
            )*
        )+
    }
}

macro_rules! impl_frombits_for_bool {
    (impl FromBits<$($F:ty),+> for bool {}) => {
        $(
            impl FromBits<$F> for bool {
                const BITS: u32 = 1;
                type Error = Infallible;

                fn try_from_bits(f: $F) -> Result<Self, Self::Error> {
                    Ok(if f == 0 { false } else { true })
                }

                fn into_bits(self) -> $F {
                    if self {
                        1
                    } else {
                        0
                    }
                }
            }
        )+
    }
}

impl_frombits_for_bool! {
    impl FromBits<u8, u16, u32, u64, usize> for bool {}
}

impl_frombits_for_ty! {
    impl FromBits<u8, u16, u32, u64> for u8 {}
    impl FromBits<u16, u32, u64> for u16 {}
    impl FromBits<u32, u64> for u32 {}
    impl FromBits<u64> for u64 {}

    impl FromBits<u8, u16, u32, u64> for i8 {}
    impl FromBits<u16, u32, u64> for i16 {}
    impl FromBits<u32, u64> for i32 {}
    impl FromBits<u64> for i64 {}

    // Rust doesn't support 8 bit targets, so {u,i}size are always at least 16 bit wide,
    // source: https://doc.rust-lang.org/1.45.2/src/core/convert/num.rs.html#134-139
    //
    // This allows the following impls to be supported on all platforms.
    // Impls for {u,i}32 and {u,i}64 however need to be restricted (see below).
    impl FromBits<usize> for u8 {}
    impl FromBits<usize> for i8 {}
    impl FromBits<usize> for u16 {}
    impl FromBits<usize> for i16 {}

    impl FromBits<usize> for usize {}
    impl FromBits<usize> for isize {}
}

#[cfg(target_pointer_width = "16")]
impl_frombits_for_ty! {
    impl FromBits<u16, u32, u64> for usize {}
    impl FromBits<u16, u32, u64> for isize {}
}

#[cfg(target_pointer_width = "32")]
impl_frombits_for_ty! {
    impl FromBits<u32, u64> for usize {}
    impl FromBits<u32, u64> for isize {}

    impl FromBits<usize> for u32 {}
    impl FromBits<usize> for i32 {}
}

#[cfg(target_pointer_width = "64")]
impl_frombits_for_ty! {
    impl FromBits<u64> for usize {}
    impl FromBits<u64> for isize {}

    impl FromBits<usize> for u32 {}
    impl FromBits<usize> for i32 {}
    impl FromBits<usize> for u64 {}
    impl FromBits<usize> for i64 {}
}