simple_bitfield 0.1.8

Create bitfields with the same memory structure as integers using a simple macro.
Documentation
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
#![no_std]


//! Crate to create simple C-style bitfields with the same memory structure
//! as the underlying data type (typically integer). Can be used in `#![no_std]` environments.
//! 
//! Properties of such bitfields:
//!  * they have the exact same memory layout and size as the underlying primitive type;
//!  * their size is checked at compile-time, so it's not possible to add a field that won't fit into the underlying type;
//!  * their fields can be accessed by name (`my_bitfield.some_field`) which aids readability;
//!  * each field has the same set of functions (`get`, `set`, `set_checked` and more);
//!  * each field has its own distinct type;
//!  * it's possible to skip (and not name) any number of bits
//!
//! The [bitfield] macro was inspired by [https://guiand.xyz/blog-posts/bitfields.html](https://guiand.xyz/blog-posts/bitfields.html).
//! 
//! ## Example:
//! ```
//! use simple_bitfield::{bitfield, Field};
//! 
//! bitfield! {
//!     // Bitfield with underlying type `u32`
//!     struct MyBitfield<u32> {
//!         field1: 3, // First field (least significant) of size 3 bits
//!         field2: 9,
//!         _: 6,      // Fields named `_` are skipped (offsets are preserved)
//!         field3: 1  // Last bit (closest to the highest bit of `u32`)
//!     }
//! 
//!     // Multiple bitfields can be defined within one macro invocation
//!    struct AnotherBitfield<u8> {
//!        _: 7,
//!        highest_bit: 1
//!    }
//! }
//!
//! fn main() {
//!    // Create bitfield object
//!    let mut a_bitfield = MyBitfield::new(12345);
//!
//!    // Get the field's value (of underlying type)
//!    let field3: u32 = a_bitfield.field3.get();
//!
//!    println!(
//!        "{:#b} => {:#b}, {:#b}, {:#b}",
//!        u32::from(a_bitfield), // Convert bitfield to underlying type
//!        field3,
//!        a_bitfield.field2.get(),
//!        a_bitfield.field1.get()
//!    );
//!
//!    // Update just that field
//!    a_bitfield.field1.set(0);
//!
//!    println!("{:#b}", u32::from(a_bitfield));
//!
//!    println!("{}\n{:?}", a_bitfield, a_bitfield);
//!    // MyBitfield(12344)
//!    // MyBitfield(field1: 0, field2: 7, field3: 0)
//!
//!    // The type can be inferred, of course
//!    let another_one: AnotherBitfield::AnotherBitfield = AnotherBitfield::new(184);
//!    
//!    // Fields cannot be moved or copied!
//!    // let another_one_highest = another_one.highest_bit;
//!
//!    // Each field has its own type
//!    let another_one_highest: &AnotherBitfield::highest_bit = &another_one.highest_bit;
//!    println!("{:#b}", another_one_highest.get())
//! }
//! ```
//!
//! ## These bitfields are _simple_
//! One bitfield is essentially one integer that has fields whose `get` methods
//! return data of the same integer type. Bitfields that contain more than one integer
//! or any type that doesn't satisfy the [Bitfield] and [Field] traits are not yet possible.
//!
//! Structs that contain multiple bitfields _are_ possible, and their size can be preserved
//! via the `#[repr(packed)]` attribute. Care must be taken of the field access
//! because code like `a_bitfield.field.get()` borrows `a_bitfield`, which can result in
//! unaligned access if the struct with the bitfields is `#[repr(packed)]`.
//!
//! The [TestBitfield] module is only present in the documentation and shows how a bitfield is structured internally.

use core::{
    ops::{ Shl, Shr, BitAnd, BitOrAssign, BitXorAssign },
    fmt::{ Debug, Display }
};

#[doc(hidden)]
pub use static_assertions::const_assert;

pub trait Bitfield {
    //! The trait that's implemented for all bitfields.
    //! Used mainly to access the bitfield's underlying type, [Self::BaseType].

    /// The bitfield's underlying type.
    type BaseType: Copy + Debug + Display;
    
    /// The maximum number of bits that the bitfield can hold.
    /// Used for compile-time checking that no newly added field requires a [Self::BaseType] wider than this.
    const MAX_BITS: u8 = 8 * core::mem::size_of::<Self::BaseType>() as u8;
}

pub trait Field<B: Bitfield>
    where B::BaseType:
        Shl<u8, Output=B::BaseType> +
        Shr<u8, Output=B::BaseType> +
        BitAnd<Output=B::BaseType> +
        BitOrAssign + BitXorAssign + PartialEq
{
    //! The trait that's implemented for all fields of all bitfields.
    //! Allows the nice `my_bitfield.some_field.get()` syntax.

    /// The field's size _in bits_. Specified by the user.
    const SIZE: u8;

    /// The field's offset from the underlying value's least significant bit,
    /// _in bits_.
    ///
    /// The first field's offset is 0, the second field's offset is
    /// `previous_field::SIZE` and so on. Computed automatically.
    const OFFSET: u8;

    /// The field's mask that can be used to extract the last [Self::SIZE] bits from any `B::BaseType`.
    /// Computed automatically.
    ///
    /// Example usage:
    /// ```
    /// use simple_bitfield::{ bitfield, Field };
    ///
    /// bitfield! {
    ///     struct TestBitfield<u32> {
    ///         field1: 4
    ///     }
    /// }
    ///
    /// fn main() {
    ///     let the_bf = TestBitfield::new(123);
    ///
    ///     assert_eq!(TestBitfield::field1::MASK, 0b1111);
    ///     assert_eq!(0b1011_1010 & TestBitfield::field1::MASK, 0b1010);
    /// }
    /// ```
    const MASK: B::BaseType;
    
    /// Returns `true` if the field is not equal to zero.
    fn is_set(&self) -> bool;
    
    /// `true` if the field is within the bitfield's bounds. Used for compile-time checking.
    const VALID: bool = Self::SIZE + Self::OFFSET <= B::MAX_BITS;
    
    /// Returns the size of a field _at runtime_, while [Self::SIZE] is used on the _type_ of the field at compile-time.
    fn size(&self) -> u8 { Self::SIZE }

    /// Returns the offset of a field _at runtime_, while [Self::OFFSET] is used on the _type_ of the field at compile-time.
    fn offset(&self) -> u8 { Self::OFFSET }

    /// Returns the mask of a field _at runtime_, while [Self::MASK] is used on the _type_ of the field at compile-time.
    fn mask(&self) -> B::BaseType { Self::MASK }
    
    /// Returns the current value of the field.
    ///
    /// Example:
    /// ```
    /// use simple_bitfield::{ bitfield, Field };
    ///
    /// bitfield! {
    ///     struct TestBitfield<u32> {
    ///         field1: 4
    ///     }
    /// }
    ///
    /// fn main() {
    ///     let my_bitfield = TestBitfield::new(0b10_1111);
    ///
    ///     assert_eq!(my_bitfield.field1.get(), 0b1111);
    /// }
    /// ```
    fn get(&self) -> B::BaseType {
        let data_ptr: *const B::BaseType = self as *const Self as *const B::BaseType;
        
        (unsafe { *data_ptr } >> Self::OFFSET) & Self::MASK
    }
    
    /// Sets the value of a field. If the value is wider than the field,
    /// the value's lowest [Self::SIZE] bits will be used.
    ///
    /// Example:
    /// ```
    /// use simple_bitfield::{ bitfield, Field };
    ///
    /// bitfield! {
    ///     struct TestBitfield<u32> {
    ///         field1: 4
    ///     }
    /// }
    ///
    /// fn main() {
    ///     let mut my_bitfield = TestBitfield::new(0b10_1111);  // Must be mutable
    ///
    ///     my_bitfield.field1.set(0b1_1100);
    ///     assert_eq!(my_bitfield.field1.get(), 0b1100);
    /// }
    /// ```
    fn set(&mut self, new_value: B::BaseType) {
        let data_ptr: *mut B::BaseType = self as *const Self as *mut B::BaseType;
        
        let old_value: B::BaseType = self.get() << Self::OFFSET;
        
        unsafe {
            *data_ptr ^= old_value;
            *data_ptr |= (new_value & Self::MASK) << Self::OFFSET
        }
    }

    /// Sets the value of a field. If the value is wider than the field,
    /// returns an `Err` result containing the value's lowest [Self::SIZE] bits
    /// and doesn't modify the field.
    ///
    /// Example:
    /// ```
    /// use simple_bitfield::{ bitfield, Field };
    ///
    /// bitfield! {
    ///     struct TestBitfield<u32> {
    ///         field1: 4
    ///     }
    /// }
    ///
    /// fn main() {
    ///     let mut my_bitfield = TestBitfield::new(0b10_1111);  // Must be mutable
    ///
    ///     assert_eq!(
    ///         my_bitfield.field1.set_checked(0b1_1100),
    ///         Err(0b1100)
    ///     );
    ///
    ///     // The field's value didn't change
    ///     assert_eq!(my_bitfield.field1.get(), 0b1111);
    /// }
    /// ```
    fn set_checked(&mut self, new_value: B::BaseType) -> Result<(), B::BaseType> {
        let masked = new_value & Self::MASK;

        if masked != new_value {
            Err(masked)
        } else {
            self.set(masked);

            Ok(())
        }
    }
}

/// Generates the format args for all fields of a bitfield.
///
/// The result looks like this: `field_low: value, field: value, field_high: value`. Used internally.
#[macro_export]
#[doc(hidden)]
macro_rules! gen_format_debug {
    ($self:ident) => { format_args!("{}", "") };
    ($self:ident | $first_field:ident) => {
        format_args!(
            "{}: {:?}",
            // Can't just refer to `self` because it's a keyword?!
            // So have to pass it from call site
            stringify!($first_field), $self.$first_field.get()
        )
    };
    ($self:ident | $first_field:ident | $second_field:ident $(| $other_field:ident)*) => {
        format_args!(
            "{}: {:?}, {}",
            stringify!($first_field), $self.$first_field.get(),
            $crate::gen_format_debug!($self | $second_field $(| $other_field)*)
        )
    };
}


/// Creates bitfield types.
///
/// Adapted from [https://guiand.xyz/blog-posts/bitfields.html](https://guiand.xyz/blog-posts/bitfields.html)
///
/// Example:
/// ```
/// use core::mem::{size_of, size_of_val};
/// use simple_bitfield::{
///     bitfield, Field // For field access
/// };
///
/// bitfield!{
///     struct BitfieldName<u8> {
///         first_two_bits: 2,
///         three_more_bits: 3
///     }
///
///     struct AnotherBitfield<u32> {
///         _: 31, // Skip first 31 bits
///         last_bit: 1
///     }
/// }
///
/// # pub fn main() {
/// let value: u8 = 0b111_011_10;
/// let my_bitfield: BitfieldName::BitfieldName = BitfieldName::new(value);
/// let another_bitfield = AnotherBitfield::new(value.into());
///
/// assert_eq!(
///     size_of_val(&my_bitfield),
///     size_of::<u8>()
/// );
/// assert_eq!(
///     size_of_val(&my_bitfield),
///     size_of::<u8>()
/// );
///
/// assert_eq!(my_bitfield.first_two_bits.size(), 2);
/// assert_eq!(my_bitfield.three_more_bits.size(), 3);
///
/// assert_eq!(my_bitfield.first_two_bits.get(), value & 0b11);
/// assert_eq!(
///     my_bitfield.three_more_bits.get(),
///     (value >> my_bitfield.first_two_bits.size()) & 0b111
/// );
///
/// assert_eq!(another_bitfield.last_bit.get(), 0);
/// # }
/// ```
///
/// The bitfield `BitfieldName` is actually a module. The type that holds the data is `BitfieldName::BitfieldName`,
/// which is unique for each bitfield. Each field is a zero-size struct that cannot be instantiated separately from the bitfield.
/// The memory representation of the bitfield is exactly the same as that of the underlying type.
#[macro_export]
macro_rules! bitfield {
    ($($(#[$attr:meta])* $visibility:vis struct $bitfield_name:ident < $big_type:ty > { $($field:tt : $size:literal),* })*) => {$(
        // Construct the whole module
        #[allow(non_snake_case)]
        #[allow(dead_code)]
        $visibility mod $bitfield_name {
            //! This module represents a single bitfield.

            /// Struct with the actual data.
            #[repr(transparent)]
            #[derive(Copy, Clone)]
            $(#[$attr])*
            pub struct $bitfield_name($big_type);
            impl $crate::Bitfield for $bitfield_name {
                type BaseType = $big_type;
            }

            impl From<$big_type> for $bitfield_name
            {
                fn from(val: $big_type) -> Self {
                    Self(val)
                }
            }

            impl From<$bitfield_name> for $big_type {
                fn from(val: $bitfield_name) -> Self {
                    val.0
                }
            }

            /// Creates a new bitfield
            pub const fn new(val: $big_type) -> $bitfield_name {
                // Can't use `val.into()` because `into` is not `const`.
                $bitfield_name(val)
            }

            /* Generate a zero-sized (!!) `struct` for each `$field`
             * and a zero-sized (!!) `struct Field` whose elements are objects of these structs.
             */
            $crate::bitfield!{
                impl
                $($field : $size),* end_marker // List of fields to process
    
                Fields, // Name of the struct that will hold the resulting fields
                $bitfield_name, // Name of the underlying bitfield struct that holds the actual data
                0, // Offset of the current bitfield
                processed // Empty (!) list of processed field names
            }

            $crate::const_assert!(Fields::VALID);

            /// Implement this so that accesses to fields of `$bitfield_name`
            /// actually access the zero-sized struct `Fields`
            impl core::ops::Deref for $bitfield_name {
                type Target = Fields;

                fn deref(&self) -> &Self::Target {
                    // We go through Deref here because Fields MUST NOT be moveable.
                    unsafe { &*(self as *const Self as *const Fields) } 
                }
            }

            impl core::ops::DerefMut for $bitfield_name {
                fn deref_mut(&mut self) -> &mut Self::Target {
                    // We go through Deref here because Fields MUST NOT be moveable.
                    unsafe { &mut *(self as *mut Self as *mut Fields) } 
                }
            }
        }
    )*};

    (impl end_marker $struct_name:ident, $bitfield_type:ty, $curr_offset:expr, processed $(| $field_processed:ident)*) => {
        /// Struct whose fields' names' are those of the bitfield's fields.
        ///
        /// When accessing a field of a bitfield like `some_bitfield.a_field`, a reference to `some_bitfield` is created
        /// and `unsafe`ly treated as a reference to _this struct_.
        /// However, this should actually be OK because this struct can't be constructed since none of its fields can be constructed.
        ///
        /// This struct's size is zero:
        /// ```
        /// use simple_bitfield::bitfield;
        ///
        /// bitfield!{
        ///     struct BitfieldName<u8> {
        ///         first_two_bits: 2,
        ///         three_more_bits: 3
        ///     }
        /// }
        ///
        /// # fn main() {
        /// assert_eq!(core::mem::size_of::<BitfieldName::Fields>(), 0);
        /// # }
        /// ```
        #[repr(C)]
        pub struct $struct_name {
            $(pub $field_processed: $field_processed),*
        }

        impl $struct_name {
            /// `true` if ALL fields are valid, `false` otherwise
            const VALID: bool = $(<$field_processed as $crate::Field<$bitfield_type>>::VALID &)* true;
        }

        impl core::fmt::Display for $bitfield_type {
            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::result::Result<(), core::fmt::Error> {
                write!(f, "{}({})", stringify!($bitfield_type), self.0)
            }
        }

        impl core::fmt::Debug for $bitfield_type {
            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::result::Result<(), core::fmt::Error> {
                use $crate::Field; // because `gen_format` accesses fields

                write!(f, "{}", format_args!(
                    "{}({})", stringify!($bitfield_type),
                    $crate::gen_format_debug!(self $(| $field_processed)*)
                ))
            }
        }
    };

    (impl _ : $size:literal $(, $other_field:tt : $other_size:literal)* end_marker $struct_name:ident, $bitfield_type:ty, $curr_offset:expr, processed $(| $field_processed:ident)*) => {
        // Skip field that's equal to `_`
        $crate::bitfield!{
            impl
            $($other_field : $other_size),* end_marker
            $struct_name, $bitfield_type,
            $curr_offset + $size,
            processed $(| $field_processed)*
        }
    };

    (impl $field:ident : $size:literal $(, $other_field:tt : $other_size:literal)* end_marker $struct_name:ident, $bitfield_type:ty, $curr_offset:expr, processed $(| $field_processed:ident)*) => {
        // Create one field

        /// The bitfield's field. Can't be constructed outside of a bitfield.
        ///
        /// It's actually a struct of size ZERO and implements `Field<UnderlyingBitfieldType>`, so that its value can be obtained with `get()` and changed with `set()`.
        ///
        /// This struct cannot be constructed explicitly:
        /// ```compile_fail
        /// use simple_bitfield::bitfield;
        ///
        /// bitfield!{
        ///     struct BitfieldName<u8> {
        ///         first_two_bits: 2,
        ///         three_more_bits: 3
        ///     }
        /// }
        ///
        /// # fn main() {
        /// let tried_to_construct_field = BitfieldName::first_two_bits(());
        /// # }
        /// ```
        #[allow(non_camel_case_types)]
        pub struct $field(());
        /*
         * `struct thing(())` is a "unit-valued tuple struct",
         * basically the same as `struct thing(<any type>)`,
         * which can be constucted like `thing(<value of type>)`,
         * but the constructor is invisible outside the module.
         *
         * https://stackoverflow.com/questions/50162597/what-are-the-differences-between-the-multiple-ways-to-create-zero-sized-structs
        */

        #[allow(dead_code)]
        impl $crate::Field<$bitfield_type> for $field {
            const SIZE: u8 = $size;
            const OFFSET: u8 = $curr_offset;
            const MASK: <$bitfield_type as $crate::Bitfield>::BaseType = (1 << Self::SIZE) - 1;

            #[inline]
            fn is_set(&self) -> bool {
                self.get() != 0
            }
        }

        $crate::const_assert!(<$field as $crate::Field<$bitfield_type>>::VALID);

        // Process the next fields
        $crate::bitfield!{
            impl
            $($other_field : $other_size),* end_marker // Schedule the next fields
            $struct_name, $bitfield_type, // Pass along
            $curr_offset + $size, // INCREMENT the current offset!!
            processed $(| $field_processed)* | $field // Add the field name to processed fields
            /* The trick with field names being separated by pipes (`|`) like `| $field`
             * is needed because `$(| $field_processed)*` may be empty, but we apparently need SOME separator,
             * so the separator must be in front of the field name
             */
        }
    }
}


#[cfg(doc)]
bitfield! {
    pub struct TestBitfield<u32> {
        field_1: 2,
        _: 3,
        field_2: 5
    }
}


// Should be AFTER the macro definition
#[cfg(test)]
mod tests;