Skip to content

Commit

Permalink
Introduce ZERO constant
Browse files Browse the repository at this point in the history
This is a shortcut for `A::new_with_raw_value(0)`.
  • Loading branch information
danlehmann committed Jul 23, 2024
1 parent 056a50b commit 3d9df9c
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
12 changes: 12 additions & 0 deletions bitbybit-tests/src/bitfield_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,18 @@ fn test_construction() {
assert_eq!(45, t.raw_value);
}

#[test]
fn test_zero() {
#[bitfield(u32)]
struct TestA {}

#[bitfield(u32, default = 0x123)]
struct TestB {}

assert_eq!(0, TestA::ZERO.raw_value());
assert_eq!(0, TestB::ZERO.raw_value());
}

#[test]
fn test_getter_and_setter() {
#[bitfield(u128, default = 0)]
Expand Down
8 changes: 8 additions & 0 deletions bitbybit/src/bitfield/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,12 @@ pub fn bitfield(args: TokenStream, input: TokenStream) -> TokenStream {
quote! { #base_data_type::#extract(self.raw_value, 0) }
};

let zero = if base_data_size.exposed == base_data_size.internal {
quote! { 0 }
} else {
quote! { #base_data_type::new(0) }
};

let expanded = quote! {
#[derive(Copy, Clone)]
#[repr(C)]
Expand All @@ -260,6 +266,8 @@ pub fn bitfield(args: TokenStream, input: TokenStream) -> TokenStream {
}

impl #struct_name {
pub const ZERO: Self = Self::new_with_raw_value(#zero);

#default_constructor
/// Returns the underlying raw value of this bitfield
#[inline]
Expand Down

0 comments on commit 3d9df9c

Please sign in to comment.