diff --git a/bitbybit-tests/src/bitfield_tests.rs b/bitbybit-tests/src/bitfield_tests.rs index bd5e266..c0175a5 100644 --- a/bitbybit-tests/src/bitfield_tests.rs +++ b/bitbybit-tests/src/bitfield_tests.rs @@ -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)] diff --git a/bitbybit/src/bitfield/mod.rs b/bitbybit/src/bitfield/mod.rs index df156fd..ec8a3e1 100644 --- a/bitbybit/src/bitfield/mod.rs +++ b/bitbybit/src/bitfield/mod.rs @@ -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)] @@ -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]