bitfield-0.17.0/.cargo_vcs_info.json0000644000000001360000000000100127030ustar { "git": { "sha1": "1386eb34c2e73b5c38b984ae8a405901e141de64" }, "path_in_vcs": "" }bitfield-0.17.0/.gitignore000064400000000000000000000000271046102023000134620ustar 00000000000000target Cargo.lock *.bk bitfield-0.17.0/CHANGELOG.md000064400000000000000000000037271046102023000133150ustar 00000000000000# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] ## [0.17.0] - 2024-09-08 ### Breaking Changes - Changes published as 0.16.2 (version now yanked) was breaking ## [0.16.2] - 2024-09-07 ### Added - Allow creating bitfield structs with arbitrary visibilities, thanks to @ADSteele916 ## [0.16.1] - 2024-07-25 ### Added - Implement bitwise operations for all array-Like inner types, using `AsRef`/`AsMut`, thanks to @PokeJofeJr4th - Allow to derive constructors, thanks to @PokeJofeJr4th ## [0.16.0] - 2024-07-22 ### Added - Easily Derive Bitwise Operations, thanks to @PokeJofeJr4th ### Breaking Changes - The minimum rustc version is now 1.79.0 ## [0.15.0] - 2024-04-09 ### Added - Allow to generate mask for a field ### Breaking Changes - The minimum rustc version is now 1.46.0 ## [0.14.0] - 2022-07-11 ### Added - Getters work with immutable Data ### Breaking Changes - The minimum rustc version is now 1.31.0 - The setters of the `BitRange` and `Bit` has been separated in the `BitRangeMut` and `BitMut` traits. ## [0.13.2] - 2019-05-28 ### Added - `from into` can be used in place of `from` to change the input type of the setter. Thanks to @roblabla [Unreleased]: https://github.com/dzamlo/rust-bitfield/compare/v0.17.0...HEAD [0.17.0]: https://github.com/dzamlo/rust-bitfield/compare/v0.16.2...v0.17.0 [0.16.2]: https://github.com/dzamlo/rust-bitfield/compare/v0.16.0...v0.16.2 [0.16.1]: https://github.com/dzamlo/rust-bitfield/compare/v0.16.0...v0.16.1 [0.16.0]: https://github.com/dzamlo/rust-bitfield/compare/v0.15.0...v0.16.0 [0.15.0]: https://github.com/dzamlo/rust-bitfield/compare/v0.14.0...v0.15.0 [0.14.0]: https://github.com/dzamlo/rust-bitfield/compare/v0.13.2...v0.14.0 [0.13.2]: https://github.com/dzamlo/rust-bitfield/compare/v0.13.1...v0.13.2 bitfield-0.17.0/Cargo.lock0000644000000002310000000000100106520ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "bitfield" version = "0.17.0" bitfield-0.17.0/Cargo.toml0000644000000021270000000000100107030ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] name = "bitfield" version = "0.17.0" authors = ["Loïc Damien "] build = false autobins = false autoexamples = false autotests = false autobenches = false description = "This crate provides macros to generate bitfield-like struct." documentation = "https://docs.rs/bitfield" readme = "README.md" license = "MIT OR Apache-2.0" repository = "https://github.com/dzamlo/rust-bitfield" [lib] name = "bitfield" path = "src/lib.rs" [[example]] name = "bits_position" path = "examples/bits_position.rs" [[example]] name = "ipv4" path = "examples/ipv4.rs" [[test]] name = "lib" path = "tests/lib.rs" [dependencies] bitfield-0.17.0/Cargo.toml.orig000064400000000000000000000004771046102023000143720ustar 00000000000000[package] name = "bitfield" version = "0.17.0" authors = ["Loïc Damien "] license = "MIT OR Apache-2.0" description = "This crate provides macros to generate bitfield-like struct." repository = "https://github.com/dzamlo/rust-bitfield" documentation = "https://docs.rs/bitfield" [dependencies] bitfield-0.17.0/LICENSE-APACHE000064400000000000000000000261361046102023000134270ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. bitfield-0.17.0/LICENSE-MIT000064400000000000000000000020401046102023000131230ustar 00000000000000Copyright (c) 2017 Loïc Damien Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. bitfield-0.17.0/README.md000064400000000000000000000032651046102023000127600ustar 00000000000000rust-bitfield ============= This crate provides macros to generate bitfield-like struct. This a complete rewrite of the `bitfield` crate. You can find the previous version in the [rust-bitfield-legacy](https://github.com/dzamlo/rust-bitfield-legacy) repository. This version works on the stable version of rustc and use a different syntax with different possibility. ## Example An IPv4 header could be described like that: ```rust bitfield!{ struct IpV4Header(MSB0 [u8]); u32; get_version, _: 3, 0; get_ihl, _: 7, 4; get_dscp, _: 13, 8; get_ecn, _: 15, 14; get_total_length, _: 31, 16; get_identification, _: 47, 32; get_df, _: 49; get_mf, _: 50; get_fragment_offset, _: 63, 51; get_time_to_live, _: 71, 64; get_protocol, _: 79, 72; get_header_checksum, _: 95, 79; get_source_address, _: 127, 96; get_destination_address, _: 159, 128; } ``` In this example, all the fields are read-only, the _ as setter name signals to skip the setter method. The range at the end (e.g. 3, 0) defines the bit range where the information is encoded. ## Documentation The documentation of the released version is available on [doc.rs](https://docs.rs/bitfield). ## License Licensed under either of * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. bitfield-0.17.0/examples/bits_position.rs000064400000000000000000000034531046102023000165510ustar 00000000000000#[macro_use] extern crate bitfield; use bitfield::BitMut; use bitfield::BitRangeMut; bitfield! { struct BitsLocations([u8]); } bitfield! { struct BitsLocationsMsb0(MSB0 [u8]); } fn println_slice_bits(slice: &[u8]) { if slice.is_empty() { println!("[]"); } else { print!("[{:08b}", slice[0]); for byte in &slice[1..] { print!(", {:08b}", byte); } println!("]"); } } fn main() { let mut bits_locations = BitsLocations([0; 3]); let mut bits_locations_msb0 = BitsLocationsMsb0([0; 3]); println!("Default version:"); for i in 0..(3 * 8) { bits_locations.set_bit(i, true); print!("{:2}: ", i); println_slice_bits(&bits_locations.0); bits_locations.set_bit(i, false); } for i in 0..(3 * 8 - 3) { let msb = i + 3; let lsb = i; for value in &[0b1111u8, 0b0001, 0b1000] { bits_locations.set_bit_range(msb, lsb, *value); print!("{:2} - {:2} ({:04b}): ", msb, lsb, value); println_slice_bits(&bits_locations.0); } println!(); bits_locations.set_bit_range(msb, lsb, 0u8); } println!("MSB0 version:"); for i in 0..(3 * 8) { bits_locations_msb0.set_bit(i, true); print!("{:2}: ", i); println_slice_bits(&bits_locations_msb0.0); bits_locations_msb0.set_bit(i, false); } for i in 0..(3 * 8 - 3) { let msb = i + 3; let lsb = i; for value in &[0b1111u8, 0b0001, 0b1000] { bits_locations_msb0.set_bit_range(msb, lsb, *value); print!("{:2} - {:2} ({:04b}): ", msb, lsb, value); println_slice_bits(&bits_locations_msb0.0); } println!(); bits_locations_msb0.set_bit_range(msb, lsb, 0u8); } } bitfield-0.17.0/examples/ipv4.rs000064400000000000000000000027601046102023000145460ustar 00000000000000#![allow(dead_code)] #[macro_use] extern crate bitfield; use std::net::Ipv4Addr; bitfield! { struct IpV4Header(MSB0 [u8]); impl Debug; u32; get_version, _: 3, 0; get_ihl, _: 7, 4; get_dscp, _: 13, 8; get_ecn, _: 15, 14; get_total_length, _: 31, 16; get_identification, _: 47, 32; get_df, _: 49; get_mf, _: 50; get_fragment_offset, _: 63, 51; get_time_to_live, _: 71, 64; get_protocol, _: 79, 72; get_header_checksum, _: 95, 80; u8, get_source_address, _: 103, 96, 4; u32, into Ipv4Addr, get_destination_address, _: 159, 128; } impl> IpV4Header { fn get_source_as_ip_addr(&self) -> Ipv4Addr { let mut src = [0; 4]; for (i, src) in src.iter_mut().enumerate() { *src = self.get_source_address(i); } src.into() } } fn main() { let data = [ 0x45, 0x00, 0x00, 0x40, 0x69, 0x27, 0x40, 0x00, 0x40, 0x11, 0x4d, 0x0d, 0xc0, 0xa8, 0x01, 0x2a, 0xc0, 0xa8, 0x01, 0xfe, ]; let header = IpV4Header(data); assert_eq!(header.get_version(), 4); assert_eq!(header.get_total_length(), 64); assert_eq!(header.get_identification(), 0x6927); assert!(header.get_df()); assert!(!header.get_mf()); assert_eq!(header.get_fragment_offset(), 0); assert_eq!(header.get_protocol(), 0x11); println!( "from {} to {}", header.get_source_as_ip_addr(), header.get_destination_address() ); println!("{:#?}", header); } bitfield-0.17.0/multitest.toml000064400000000000000000000010421046102023000144170ustar 00000000000000[[tests]] name = "cargo-test-{{toolchain}}" command = ["cargo", "+{{toolchain}}", "test", "--all", "--frozen"] [[tests.env]] name = "CARGO_TARGET_DIR" value = "target/{{name}}" [tests.variables] toolchain = ["stable", "beta", "nightly", "1.79.0"] [[tests]] name = "cargo-clippy" command = ["cargo", "+stable", "clippy", "--all", "--frozen", "--all-targets", "--", "-D", "warnings"] [[tests.env]] name = "CARGO_TARGET_DIR" value = "target/cargo-test-nightly" [[tests]] name = "cargo-fmt" command = ["cargo", "fmt", "--all", "--", "--check"] bitfield-0.17.0/src/lib.rs000064400000000000000000001271051046102023000134040ustar 00000000000000#![no_std] #![deny( missing_docs, unused_extern_crates, unused_import_braces, unused_qualifications )] //! This crate provides macros to generate bitfield-like struct. //! //! See the documentation of the macros for how to use them. //! //! Examples and tests are also a great way to understand how to use these macros. /// Generates and dispatches trait implementations for a struct /// /// This must be called outside of any `impl` block. /// /// The syntax is `TheNameOfTheTrait for struct TheNameOfTheStruct(TheInnerType);` followed by the syntax of bitfield_fields. /// /// Supported traits: /// * Debug /// * BitAnd /// * BitOr /// * BitXor /// /// Additional derivations: /// * new /// * Creates a constructor, including parameters for all fields with a setter /// * new{constructor_name(setter_name: setter_type, ...)} /// * Creates a constructor using the given name and parameters. In order to compile correctly, each `setter_name` /// must be the setter of a field of type `setter_type` specified later in the macro. #[macro_export(local_inner_macros)] macro_rules! bitfield_impl { (Debug for struct $name:ident([$t:ty]); $($rest:tt)*) => { impl + $crate::fmt::Debug> $crate::fmt::Debug for $name { bitfield_debug!{struct $name; $($rest)*} } }; (Debug for struct $name:ident($t:ty); $($rest:tt)*) => { impl $crate::fmt::Debug for $name { bitfield_debug!{struct $name; $($rest)*} } }; (BitAnd for struct $name:ident([$t:ty]); $($rest:tt)*) => { bitfield_impl!{@bitwise BitAnd bitand BitAndAssign bitand_assign $name([$t]) &=} }; (BitAnd for struct $name:ident($t:ty); $($rest:tt)*) => { bitfield_impl!{@bitwise BitAnd bitand BitAndAssign bitand_assign $name($t) &=} }; (BitOr for struct $name:ident([$t:ty]); $($rest:tt)*) => { bitfield_impl!{@bitwise BitOr bitor BitOrAssign bitor_assign $name([$t]) |=} }; (BitOr for struct $name:ident($t:ty); $($rest:tt)*) => { bitfield_impl!{@bitwise BitOr bitor BitOrAssign bitor_assign $name($t) |=} }; (BitXor for struct $name:ident([$t:ty]); $($rest:tt)*) => { bitfield_impl!{@bitwise BitXor bitxor BitXorAssign bitxor_assign $name([$t]) ^=} }; (BitXor for struct $name:ident($t:ty); $($rest:tt)*) => { bitfield_impl!{@bitwise BitXor bitxor BitXorAssign bitxor_assign $name($t) ^=} }; (@bitwise $bitwise:ident $func:ident $bitwise_assign:ident $func_assign:ident $name:ident([$t:ty]) $op:tt) => { impl + AsRef<[$t]>> $crate::ops::$bitwise for $name { type Output = Self; fn $func(mut self, rhs: Self) -> Self { bitfield_impl!(@mutate self rhs $op); self } } impl + AsRef<[$t]>> $crate::ops::$bitwise_assign for $name { fn $func_assign(&mut self, rhs: Self) { bitfield_impl!(@mutate self rhs $op); } } }; (@bitwise $bitwise:ident $func:ident $bitwise_assign:ident $func_assign:ident $name:ident($t:ty) $op:tt) => { impl $crate::ops::$bitwise for $name { type Output = Self; fn $func(mut self, rhs: Self) -> Self { self.0 $op rhs.0; self } } impl $crate::ops::$bitwise_assign for $name { fn $func_assign(&mut self, rhs: Self) { self.0 $op rhs.0; } } }; (@mutate $self:ident $rhs:ident $op:tt) => {{ let as_mut = AsMut::<[_]>::as_mut(&mut $self.0); let rhs = AsRef::<[_]>::as_ref(&$rhs.0); for i in 0..as_mut.len() { as_mut[i] $op rhs[i]; } }}; (new for struct $name:ident([$t:ty]); $($rest:tt)*) => { impl + Default> $name { bitfield_constructor!{() -> {}; $($rest)*} } }; (new for struct $name:ident($t:ty); $($rest:tt)*) => { impl $name { bitfield_constructor!{() -> {}; $($rest)*} } }; (new{$new:ident ($($setter_name:ident: $setter_type:ty),*$(,)?)} for struct $name:ident([$t:ty]); $($rest:tt)*) => { impl + Default> $name { pub fn $new($($setter_name: $setter_type),*) -> Self { let mut value = Self(T::default()); $( value.$setter_name($setter_name); )* value } } }; (new{$new:ident ($($setter_name:ident: $setter_type:ty),*$(,)?)} for struct $name:ident($t:ty); $($rest:tt)*) => { impl $name { pub fn $new($($setter_name: $setter_type),*) -> Self { let mut value = Self($t::default()); $( value.$setter_name($setter_name); )* value } } }; // display a more friendly error message when someone tries to use `impl ;` syntax when not supported ($macro:ident for struct $name:ident $($rest:tt)*) => { ::std::compile_error!(::std::stringify!(Unsupported impl $macro for struct $name)); }; } /// Declares the fields of struct. /// /// This macro will generate the methods to access the fields of a bitfield. It must be called /// from an `impl` block for a type that implements the `BitRange` and/or the `Bit` traits /// (which traits are required depending on what type of fields are used). /// /// The syntax of this macro is composed of declarations ended by semicolons. There are two types /// of declarations: default type, and fields. /// /// A default type is just a type followed by a semicolon. This will affect all the following field /// declarations. /// /// A field declaration is composed of the following: /// /// * Optional attributes (`#[...]`), documentation comments (`///`) are attributes; /// * An optional pub keyword to make the methods public /// * An optional type followed by a comma /// * Optionally, the word `into` followed by a type, followed by a comma /// * The getter and setter idents, separated by a comma /// * A colon /// * One to three expressions of type `usize` /// /// The attributes and pub will be applied to the two methods generated. /// /// If the `into` part is used, the getter will convert the field after reading it. /// /// The getter and setter idents can be `_` to not generate one of the two. For example, if the /// setter is `_`, the field will be read-only. /// /// The expressions at the end are the bit positions. Their meaning depends on the number of /// expressions: /// /// * One expression: the field is a single bit. The type is ignored and `bool` is used. The trait /// `Bit` is used. /// * Two expressions: `msb, lsb`, the field is composed of the bits from `msb` to `lsb`, included. /// * Three expressions: `msb, lsb, count`, the field is an array. The first element is composed of /// the bits from `msb` to `lsb`. The following elements are consecutive bits range of the same /// size. /// /// # Example /// /// ```rust /// # #[macro_use] extern crate bitfield; /// # fn main() {} /// # struct FooBar(u64); /// # bitfield_bitrange!{struct FooBar(u64)} /// # impl From for FooBar{ fn from(_: u32) -> FooBar {unimplemented!()}} /// # impl From for u32{ fn from(_: FooBar) -> u32 {unimplemented!()}} /// # impl FooBar { /// bitfield_fields!{ /// // The default type will be `u64 /// u64; /// // filed1 is read-write, public, the methods are inline /// #[inline] /// pub field1, set_field1: 10, 0; /// // `field2` is read-only, private, and of type bool. /// field2, _ : 0; /// // `field3` will be read as an `u32` and then converted to `FooBar`. /// // The setter is not affected, it still need an `u32` value. /// u32, into FooBar, field3, set_field3: 10, 0; /// // `field4` will be read as an `u32` and then converted to `FooBar`. /// // The setter will take a `FooBar`, and converted back to an `u32`. /// u32, from into FooBar, field4, set_field4: 10, 0; /// // `field5` will be read as an `u32` and then converted to `FooBar`. /// // The setter will take a `FooBar`, and converted back to an `u32`. /// // The struct will have an associated constant `FIELD5_MASK` of type u64 /// //with the bits of field5 set /// u32, mask FIELD5_MASK(u64), from into FooBar, field5, set_field5: 10, 0; /// } /// # } /// ``` #[macro_export(local_inner_macros)] macro_rules! bitfield_fields { (only mask; @field $(#[$attribute:meta])* ($($vis:tt)*) $t:ty, $mask:ident($mask_t:ty), $from:ty, $into:ty, _, $setter:ident: $($exprs:expr),*) => { bitfield_fields!(only mask; @field $(#[$attribute])* ($($vis)*) $t, $mask($mask_t): $($exprs),*); }; (only mask; @field $(#[$attribute:meta])* ($($vis:tt)*) $t:ty, $mask:ident($mask_t:ty), $from:ty, $into:ty, $getter:ident, _: $($exprs:expr),*) => { bitfield_fields!(only mask; @field $(#[$attribute])* ($($vis)*) $t, $mask($mask_t): $($exprs),*); }; (only mask; @field $(#[$attribute:meta])* ($($vis:tt)*) $t:ty, __NO_MASK_FOR_FIELD($mask_t:ty): $($exprs:expr),*) => {}; (only mask; @field $(#[$attribute:meta])* ($($vis:tt)*) $t:ty, $mask:ident($mask_t:ty): $bit:expr) => { $($vis)* const $mask: $mask_t = 1 << $bit; }; (only mask; @field $(#[$attribute:meta])* ($($vis:tt)*) $t:ty, $mask:ident($mask_t:ty): $msb:expr, $lsb:expr) => { $($vis)* const $mask: $mask_t = { let msb = $msb; let lsb = $lsb; let mut i = lsb; let mut acc = 0; while i <= msb { acc |= 1< { $($vis)* const $mask: $mask_t = { let msb = $msb; let lsb = $lsb; let width = msb - lsb; let full_msb = msb + width * $count; let mut i = lsb; let mut acc = 0; while i <= full_msb { acc |= 1< { $(#[$attribute])* #[allow(unknown_lints)] #[allow(eq_op)] $($vis)* fn $setter(&mut self, index: usize, value: $from) { use $crate::BitRangeMut; __bitfield_debug_assert!(index < $count); let width = $msb - $lsb + 1; let lsb = $lsb + index*width; let msb = lsb + width - 1; self.set_bit_range(msb, lsb, $crate::Into::<$t>::into(value)); } }; (only setter; @field $(#[$attribute:meta])* ($($vis:tt)*) $t:ty, $mask:ident($mask_t:ty), $from:ty, $into:ty, _, $setter:ident: $msb:expr, $lsb:expr) => { $(#[$attribute])* $($vis)* fn $setter(&mut self, value: $from) { use $crate::BitRangeMut; self.set_bit_range($msb, $lsb, $crate::Into::<$t>::into(value)); } }; (only setter; @field $(#[$attribute:meta])* ($($vis:tt)*) $t:ty, $mask:ident($mask_t:ty), $from:ty, $into:ty, _, $setter:ident: $bit:expr) => { $(#[$attribute])* $($vis)* fn $setter(&mut self, value: bool) { use $crate::BitMut; self.set_bit($bit, value); } }; (only getter; @field $(#[$attribute:meta])* ($($vis:tt)*) $t:ty, $mask:ident($mask_t:ty), $from:ty, $into:ty, _, $setter:ident: $($exprs:expr),*) => {}; (only getter; @field $(#[$attribute:meta])* ($($vis:tt)*) $t:ty, $mask:ident($mask_t:ty), $from:ty, $into:ty, $getter:ident, _: $msb:expr, $lsb:expr, $count:expr) => { $(#[$attribute])* #[allow(unknown_lints)] #[allow(eq_op)] $($vis)* fn $getter(&self, index: usize) -> $into { use $crate::BitRange; __bitfield_debug_assert!(index < $count); let width = $msb - $lsb + 1; let lsb = $lsb + index*width; let msb = lsb + width - 1; let raw_value: $t = self.bit_range(msb, lsb); $crate::Into::into(raw_value) } }; (only getter; @field $(#[$attribute:meta])* ($($vis:tt)*) $t:ty, $mask:ident($mask_t:ty), $from:ty, $into:ty, $getter:ident, _: $msb:expr, $lsb:expr) => { $(#[$attribute])* $($vis)* fn $getter(&self) -> $into { use $crate::BitRange; let raw_value: $t = self.bit_range($msb, $lsb); $crate::Into::into(raw_value) } }; (only getter; @field $(#[$attribute:meta])* ($($vis:tt)*) $t:ty, $mask:ident($mask_t:ty), $from:ty, $into:ty, $getter:ident, _: $bit:expr) => { $(#[$attribute])* $($vis)* fn $getter(&self) -> bool { use $crate::Bit; self.bit($bit) } }; (only setter; @field $(#[$attribute:meta])* ($($vis:tt)*) $t:ty, $mask:ident($mask_t:ty), $from:ty, $into:ty, $getter:ident, _: $($exprs:expr),*) => {}; (only $only:tt; @field $(#[$attribute:meta])* ($($vis:tt)*) $t:ty, $mask:ident($mask_t:ty), $from:ty, $into:ty, $getter:ident, $setter:ident: $($exprs:expr),*) => { bitfield_fields!(only $only; @field $(#[$attribute])* ($($vis)*) $t, $mask($mask_t), $from, $into, $getter, _: $($exprs),*); bitfield_fields!(only $only; @field $(#[$attribute])* ($($vis)*) $t, __NO_MASK_FOR_FIELD(u8), $from, $into, _, $setter: $($exprs),*); }; (only $only:tt; $t:ty;) => {}; (only $only:tt; $default_ty:ty; pub $($rest:tt)*) => { bitfield_fields!{only $only; $default_ty; () pub $($rest)*} }; (only $only:tt; $default_ty:ty; #[$attribute:meta] $($rest:tt)*) => { bitfield_fields!{only $only; $default_ty; (#[$attribute]) $($rest)*} }; (only $only:tt; $default_ty:ty; ($(#[$attributes:meta])*) #[$attribute:meta] $($rest:tt)*) => { bitfield_fields!{only $only; $default_ty; ($(#[$attributes])* #[$attribute]) $($rest)*} }; (only $only:tt; $default_ty:ty; ($(#[$attribute:meta])*) pub $t:ty, mask $mask:ident($mask_t:ty), from into $into:ty, $getter:tt, $setter:tt: $($exprs:expr),*; $($rest:tt)*) => { bitfield_fields!{only $only; @field $(#[$attribute])* (pub) $t, $mask($mask_t), $into, $into, $getter, $setter: $($exprs),*} bitfield_fields!{only $only; $default_ty; $($rest)*} }; (only $only:tt; $default_ty:ty; ($(#[$attribute:meta])*) pub $t:ty, mask $mask:ident($mask_t:ty), into $into:ty, $getter:tt, $setter:tt: $($exprs:expr),*; $($rest:tt)*) => { bitfield_fields!{only $only; @field $(#[$attribute])* (pub) $t, $mask($mask_t), $t, $into, $getter, $setter: $($exprs),*} bitfield_fields!{only $only; $default_ty; $($rest)*} }; (only $only:tt; $default_ty:ty; ($(#[$attribute:meta])*) pub $t:ty, mask $mask:ident($mask_t:ty), $getter:tt, $setter:tt: $($exprs:expr),*; $($rest:tt)*) => { bitfield_fields!{only $only; @field $(#[$attribute])* (pub) $t, $mask($mask_t), $t, $t, $getter, $setter: $($exprs),*} bitfield_fields!{only $only; $default_ty; $($rest)*} }; (only $only:tt; $default_ty:ty; ($(#[$attribute:meta])*) pub mask $mask:ident($mask_t:ty), from into $into:ty, $getter:tt, $setter:tt: $($exprs:expr),*; $($rest:tt)*) => { bitfield_fields!{only $only; @field $(#[$attribute])* (pub) $default_ty, $mask($mask_t), $into, $into, $getter, $setter: $($exprs),*} bitfield_fields!{only $only; $default_ty; $($rest)*} }; (only $only:tt; $default_ty:ty; ($(#[$attribute:meta])*) pub mask $mask:ident($mask_t:ty), into $into:ty, $getter:tt, $setter:tt: $($exprs:expr),*; $($rest:tt)*) => { bitfield_fields!{only $only; @field $(#[$attribute])* (pub) $default_ty, $mask($mask_t), $default_ty, $into, $getter, $setter: $($exprs),*} bitfield_fields!{only $only; $default_ty; $($rest)*} }; (only $only:tt; $default_ty:ty; ($(#[$attribute:meta])*) pub mask $mask:ident($mask_t:ty), $getter:tt, $setter:tt: $($exprs:expr),*; $($rest:tt)*) => { bitfield_fields!{only $only; @field $(#[$attribute])* (pub) $default_ty, $mask($mask_t), $default_ty, $default_ty, $getter, $setter: $($exprs),*} bitfield_fields!{only $only; $default_ty; $($rest)*} }; (only $only:tt; $default_ty:ty; ($(#[$attribute:meta])*) pub $t:ty, from into $into:ty, $getter:tt, $setter:tt: $($exprs:expr),*; $($rest:tt)*) => { bitfield_fields!{only $only; @field $(#[$attribute])* (pub) $t, __NO_MASK_FOR_FIELD(u8), $into, $into, $getter, $setter: $($exprs),*} bitfield_fields!{only $only; $default_ty; $($rest)*} }; (only $only:tt; $default_ty:ty; ($(#[$attribute:meta])*) pub $t:ty, into $into:ty, $getter:tt, $setter:tt: $($exprs:expr),*; $($rest:tt)*) => { bitfield_fields!{only $only; @field $(#[$attribute])* (pub) $t, __NO_MASK_FOR_FIELD(u8), $t, $into, $getter, $setter: $($exprs),*} bitfield_fields!{only $only; $default_ty; $($rest)*} }; (only $only:tt; $default_ty:ty; ($(#[$attribute:meta])*) pub $t:ty, $getter:tt, $setter:tt: $($exprs:expr),*; $($rest:tt)*) => { bitfield_fields!{only $only; @field $(#[$attribute])* (pub) $t, __NO_MASK_FOR_FIELD(u8), $t, $t, $getter, $setter: $($exprs),*} bitfield_fields!{only $only; $default_ty; $($rest)*} }; (only $only:tt; $default_ty:ty; ($(#[$attribute:meta])*) pub from into $into:ty, $getter:tt, $setter:tt: $($exprs:expr),*; $($rest:tt)*) => { bitfield_fields!{only $only; @field $(#[$attribute])* (pub) $default_ty, __NO_MASK_FOR_FIELD(u8), $into, $into, $getter, $setter: $($exprs),*} bitfield_fields!{only $only; $default_ty; $($rest)*} }; (only $only:tt; $default_ty:ty; ($(#[$attribute:meta])*) pub into $into:ty, $getter:tt, $setter:tt: $($exprs:expr),*; $($rest:tt)*) => { bitfield_fields!{only $only; @field $(#[$attribute])* (pub) $default_ty, __NO_MASK_FOR_FIELD(u8), $default_ty, $into, $getter, $setter: $($exprs),*} bitfield_fields!{only $only; $default_ty; $($rest)*} }; (only $only:tt; $default_ty:ty; ($(#[$attribute:meta])*) pub $getter:tt, $setter:tt: $($exprs:expr),*; $($rest:tt)*) => { bitfield_fields!{only $only; @field $(#[$attribute])* (pub) $default_ty, __NO_MASK_FOR_FIELD(u8), $default_ty, $default_ty, $getter, $setter: $($exprs),*} bitfield_fields!{only $only; $default_ty; $($rest)*} }; (only $only:tt; $default_ty:ty; ($(#[$attribute:meta])*) $t:ty, mask $mask:ident($mask_t:ty), from into $into:ty, $getter:tt, $setter:tt: $($exprs:expr),*; $($rest:tt)*) => { bitfield_fields!{only $only; @field $(#[$attribute])* () $t, $mask($mask_t), $into, $into, $getter, $setter: $($exprs),*} bitfield_fields!{only $only; $default_ty; $($rest)*} }; (only $only:tt; $default_ty:ty; ($(#[$attribute:meta])*) $t:ty, mask $mask:ident($mask_t:ty), into $into:ty, $getter:tt, $setter:tt: $($exprs:expr),*; $($rest:tt)*) => { bitfield_fields!{only $only; @field $(#[$attribute])* () $t, $mask($mask_t), $t, $into, $getter, $setter: $($exprs),*} bitfield_fields!{only $only; $default_ty; $($rest)*} }; (only $only:tt; $default_ty:ty; ($(#[$attribute:meta])*) $t:ty, mask $mask:ident($mask_t:ty), $getter:tt, $setter:tt: $($exprs:expr),*; $($rest:tt)*) => { bitfield_fields!{only $only; @field $(#[$attribute])* () $t, $mask($mask_t), $t, $t, $getter, $setter: $($exprs),*} bitfield_fields!{only $only; $default_ty; $($rest)*} }; (only $only:tt; $default_ty:ty; ($(#[$attribute:meta])*) mask $mask:ident($mask_t:ty), from into $into:ty, $getter:tt, $setter:tt: $($exprs:expr),*; $($rest:tt)*) => { bitfield_fields!{only $only; @field $(#[$attribute])* () $default_ty, $mask($mask_t), $into, $into, $getter, $setter: $($exprs),*} bitfield_fields!{only $only; $default_ty; $($rest)*} }; (only $only:tt; $default_ty:ty; ($(#[$attribute:meta])*) mask $mask:ident($mask_t:ty), into $into:ty, $getter:tt, $setter:tt: $($exprs:expr),*; $($rest:tt)*) => { bitfield_fields!{only $only; @field $(#[$attribute])* () $default_ty, $mask($mask_t), $default_ty, $into, $getter, $setter: $($exprs),*} bitfield_fields!{only $only; $default_ty; $($rest)*} }; (only $only:tt; $default_ty:ty; ($(#[$attribute:meta])*) mask $mask:ident($mask_t:ty), $getter:tt, $setter:tt: $($exprs:expr),*; $($rest:tt)*) => { bitfield_fields!{only $only; @field $(#[$attribute])* () $default_ty, $mask($mask_t), $default_ty, $default_ty, $getter, $setter: $($exprs),*} bitfield_fields!{only $only; $default_ty; $($rest)*} }; (only $only:tt; $default_ty:ty; ($(#[$attribute:meta])*) $t:ty, from into $into:ty, $getter:tt, $setter:tt: $($exprs:expr),*; $($rest:tt)*) => { bitfield_fields!{only $only; @field $(#[$attribute])* () $t, __NO_MASK_FOR_FIELD(u8), $into, $into, $getter, $setter: $($exprs),*} bitfield_fields!{only $only; $default_ty; $($rest)*} }; (only $only:tt; $default_ty:ty; ($(#[$attribute:meta])*) $t:ty, into $into:ty, $getter:tt, $setter:tt: $($exprs:expr),*; $($rest:tt)*) => { bitfield_fields!{only $only; @field $(#[$attribute])* () $t, __NO_MASK_FOR_FIELD(u8), $t, $into, $getter, $setter: $($exprs),*} bitfield_fields!{only $only; $default_ty; $($rest)*} }; (only $only:tt; $default_ty:ty; ($(#[$attribute:meta])*) $t:ty, $getter:tt, $setter:tt: $($exprs:expr),*; $($rest:tt)*) => { bitfield_fields!{only $only; @field $(#[$attribute])* () $t, __NO_MASK_FOR_FIELD(u8), $t, $t, $getter, $setter: $($exprs),*} bitfield_fields!{only $only; $default_ty; $($rest)*} }; (only $only:tt; $default_ty:ty; ($(#[$attribute:meta])*) from into $into:ty, $getter:tt, $setter:tt: $($exprs:expr),*; $($rest:tt)*) => { bitfield_fields!{only $only; @field $(#[$attribute])* () $default_ty, __NO_MASK_FOR_FIELD(u8), $into, $into, $getter, $setter: $($exprs),*} bitfield_fields!{only $only; $default_ty; $($rest)*} }; (only $only:tt; $default_ty:ty; ($(#[$attribute:meta])*) into $into:ty, $getter:tt, $setter:tt: $($exprs:expr),*; $($rest:tt)*) => { bitfield_fields!{only $only; @field $(#[$attribute])* () $default_ty, __NO_MASK_FOR_FIELD(u8), $default_ty, $into, $getter, $setter: $($exprs),*} bitfield_fields!{only $only; $default_ty; $($rest)*} }; (only $only:tt; $default_ty:ty; ($(#[$attribute:meta])*) $getter:tt, $setter:tt: $($exprs:expr),*; $($rest:tt)*) => { bitfield_fields!{only $only; @field $(#[$attribute])* () $default_ty, __NO_MASK_FOR_FIELD(u8), $default_ty, $default_ty, $getter, $setter: $($exprs),*} bitfield_fields!{only $only; $default_ty; $($rest)*} }; (only $only:tt; $previous_default_ty:ty; $default_ty:ty; $($rest:tt)*) => { bitfield_fields!{only $only; $default_ty; $($rest)*} }; (only $only:tt; $default_ty:ty; $($rest:tt)*) => { bitfield_fields!{only $only; $default_ty; () $($rest)*} }; (only $only:tt; $($rest:tt)*) => { bitfield_fields!{only $only; SET_A_DEFAULT_TYPE_OR_SPECIFY_THE_TYPE_FOR_EACH_FIELDS; $($rest)*} }; ($($rest:tt)*) => { bitfield_fields!{only getter; $($rest)*} bitfield_fields!{only setter; $($rest)*} bitfield_fields!{only mask; $($rest)*} } } /// Generates a `fmt::Debug` implementation. /// /// This macros must be called from a `impl Debug for ...` block. It will generate the `fmt` method. /// /// In most of the case, you will not directly call this macros, but use `bitfield`. /// /// The syntax is `struct TheNameOfTheStruct` followed by the syntax of `bitfield_fields`. /// /// The write-only fields are ignored. /// /// # Example /// /// ```rust /// # #[macro_use] extern crate bitfield; /// struct FooBar(u32); /// bitfield_bitrange!{struct FooBar(u32)} /// impl FooBar{ /// bitfield_fields!{ /// u32; /// field1, _: 7, 0; /// field2, _: 31, 24; /// } /// } /// /// impl std::fmt::Debug for FooBar { /// bitfield_debug!{ /// struct FooBar; /// field1, _: 7, 0; /// field2, _: 31, 24; /// } /// } /// /// fn main() { /// let foobar = FooBar(0x11223344); /// println!("{:?}", foobar); /// } /// ``` #[macro_export(local_inner_macros)] macro_rules! bitfield_debug { (struct $name:ident; $($rest:tt)*) => { fn fmt(&self, f: &mut $crate::fmt::Formatter) -> $crate::fmt::Result { let mut debug_struct = f.debug_struct(__bitfield_stringify!($name)); debug_struct.field(".0", &self.0); bitfield_debug!{debug_struct, self, $($rest)*} debug_struct.finish() } }; ($debug_struct:ident, $self:ident, mask $mask:ident($mask_t:ty), $($rest:tt)*) => { bitfield_debug!{$debug_struct, $self, $($rest)*} }; ($debug_struct:ident, $self:ident, #[$attribute:meta] $($rest:tt)*) => { bitfield_debug!{$debug_struct, $self, $($rest)*} }; ($debug_struct:ident, $self:ident, pub $($rest:tt)*) => { bitfield_debug!{$debug_struct, $self, $($rest)*} }; ($debug_struct:ident, $self:ident, _, $setter:tt: $($exprs:expr),*; $($rest:tt)*) => { bitfield_debug!{$debug_struct, $self, $($rest)*} }; ($debug_struct:ident, $self:ident, $type:ty; $($rest:tt)*) => { bitfield_debug!{$debug_struct, $self, $($rest)*} }; ($debug_struct:ident, $self:ident, $getter:ident, $setter:tt: $msb:expr, $lsb:expr, $count:expr; $($rest:tt)*) => { let mut array = [$self.$getter(0); $count]; for (i, e) in (&mut array).into_iter().enumerate() { *e = $self.$getter(i); } $debug_struct.field(__bitfield_stringify!($getter), &array); bitfield_debug!{$debug_struct, $self, $($rest)*} }; ($debug_struct:ident, $self:ident, $getter:ident, $setter:tt: $($exprs:expr),*; $($rest:tt)*) => { $debug_struct.field(__bitfield_stringify!($getter), &$self.$getter()); bitfield_debug!{$debug_struct, $self, $($rest)*} }; ($debug_struct:ident, $self:ident, from into $into:ty, $($rest:tt)*) => { bitfield_debug!{$debug_struct, $self, $($rest)*} }; ($debug_struct:ident, $self:ident, into $into:ty, $($rest:tt)*) => { bitfield_debug!{$debug_struct, $self, $($rest)*} }; ($debug_struct:ident, $self:ident, $type:ty, $($rest:tt)*) => { bitfield_debug!{$debug_struct, $self, $($rest)*} }; ($debug_struct:ident, $self:ident, ) => {}; } /// Implements an exhaustive constructor function for a bitfield. Should only be called by `bitfield!` when using `impl new;` /// /// # Examples /// /// ```rs /// bitfield_constructor {0; () -> {}; u8; foo1, set_foo1: 2,0; foo2, set_foo2: 7,2} /// ``` /// Generates: /// ```rs /// pub fn new(set_foo1: u8, set_foo2: u8) -> Self { /// let mut value = Self(0); /// value.set_foo1(set_foo1); /// value.set_foo2(set_foo2); /// value /// } /// ``` #[macro_export(local_inner_macros)] macro_rules! bitfield_constructor { (() -> {}; $($rest:tt)*) => { bitfield_constructor!{@value; () -> {let mut value = Self(Default::default());}; bool; $($rest)*} }; (@$value:ident; ($($param:ident: $ty:ty,)*) -> {$($stmt:stmt;)*}; $old_ty:ty; impl $_trait:ident$({$($trait_arg:tt)*})?; $($rest:tt)*) => { bitfield_constructor!{@$value; ($($param: $ty,)*) -> {$($stmt;)*}; $old_ty; $($rest)*} }; (@$value:ident; ($($param:ident: $ty:ty,)*) -> {$($stmt:stmt;)*}; $old_ty:ty; $new_ty:ty; $($rest:tt)*) => { bitfield_constructor!{@$value; ($($param: $ty,)*) -> {$($stmt;)*}; $new_ty; $($rest)*} }; (@$value:ident; ($($param:ident: $ty:ty,)*) -> {$($stmt:stmt;)*}; $default_ty:ty; $(#[$_:meta])* $(pub)? $(into $_into:ty,)? $_getter:ident, $setter:ident: $($_expr:expr),*; $($rest:tt)* ) => { bitfield_constructor!{@$value; ($($param: $ty,)* $setter: $default_ty,) -> {$($stmt;)* $value.$setter($setter);}; $default_ty; $($rest)*} }; (@$value:ident; ($($param:ident: $ty:ty,)*) -> {$($stmt:stmt;)*}; $default_ty:ty; $(#[$_:meta])* $(pub)? $field_type:ty, $(into $_into:ty,)? $_getter:ident, $setter:ident: $($_expr:expr),*; $($rest:tt)* ) => { bitfield_constructor!{@$value; ($($param: $ty,)* $setter: $field_type,) -> {$($stmt;)* $value.$setter($setter);}; $default_ty; $($rest)*} }; (@$value:ident; ($($param:ident: $ty:ty,)*) -> {$($stmt:stmt;)*}; $_:ty;) => { #[allow(clippy::too_many_arguments)] pub fn new($($param: $ty),*) -> Self { $($stmt;)* $value } }; } /// Implements `BitRange` and `BitRangeMut` for a tuple struct (or "newtype"). /// /// This macro will generate an implementation of the `BitRange` trait for an existing single /// element tuple struct. /// /// The syntax is more or less the same as declaring a "newtype", **without** the attributes, /// documentation comments and pub keyword. /// /// The difference with a normal "newtype" is the type in parentheses. If the type is `[t]` (where /// `t` is any of the unsigned integer type), the "newtype" will be generic and implement /// `BitRange` for `T: AsRef<[t]>` and `BitRangeMut` for `T: AsMut<[t]>` (for example a slice, an array or a `Vec`). You can /// also use `MSB0 [t]`. The difference will be the positions of the bit. You can use the /// `bits_positions` example to see where each bits is. If the type is neither of this two, the /// "newtype" will wrap a value of the specified type and implements `BitRange` the same ways as /// the wrapped type. /// /// # Examples /// /// ```rust /// # #[macro_use] extern crate bitfield; /// # fn main() {} /// struct BitField1(u32); /// bitfield_bitrange!{struct BitField1(u32)} /// /// struct BitField2(T); /// bitfield_bitrange!{struct BitField2([u8])} /// /// struct BitField3(T); /// bitfield_bitrange!{struct BitField3(MSB0 [u8])} /// ``` /// #[macro_export(local_inner_macros)] macro_rules! bitfield_bitrange { (@impl_bitrange_slice $name:ident, $slice_ty:ty, $bitrange_ty:ty) => { impl> $crate::BitRange<$bitrange_ty> for $name { fn bit_range(&self, msb: usize, lsb: usize) -> $bitrange_ty { let bit_len = $crate::size_of::<$slice_ty>()*8; let value_bit_len = $crate::size_of::<$bitrange_ty>()*8; let mut value = 0; for i in (lsb..=msb).rev() { value <<= 1; value |= ((self.0.as_ref()[i/bit_len] >> (i%bit_len)) & 1) as $bitrange_ty; } value << (value_bit_len - (msb - lsb + 1)) >> (value_bit_len - (msb - lsb + 1)) } } impl> $crate::BitRangeMut<$bitrange_ty> for $name { fn set_bit_range(&mut self, msb: usize, lsb: usize, value: $bitrange_ty) { let bit_len = $crate::size_of::<$slice_ty>()*8; let mut value = value; for i in lsb..=msb { self.0.as_mut()[i/bit_len] &= !(1 << (i%bit_len)); self.0.as_mut()[i/bit_len] |= (value & 1) as $slice_ty << (i%bit_len); value >>= 1; } } } }; (@impl_bitrange_slice_msb0 $name:ident, $slice_ty:ty, $bitrange_ty:ty) => { impl> $crate::BitRange<$bitrange_ty> for $name { fn bit_range(&self, msb: usize, lsb: usize) -> $bitrange_ty { let bit_len = $crate::size_of::<$slice_ty>()*8; let value_bit_len = $crate::size_of::<$bitrange_ty>()*8; let mut value = 0; for i in lsb..=msb { value <<= 1; value |= ((self.0.as_ref()[i/bit_len] >> (bit_len - i%bit_len - 1)) & 1) as $bitrange_ty; } value << (value_bit_len - (msb - lsb + 1)) >> (value_bit_len - (msb - lsb + 1)) } } impl> $crate::BitRangeMut<$bitrange_ty> for $name { fn set_bit_range(&mut self, msb: usize, lsb: usize, value: $bitrange_ty) { let bit_len = $crate::size_of::<$slice_ty>()*8; let mut value = value; for i in (lsb..=msb).rev() { self.0.as_mut()[i/bit_len] &= !(1 << (bit_len - i%bit_len - 1)); self.0.as_mut()[i/bit_len] |= (value & 1) as $slice_ty << (bit_len - i%bit_len - 1); value >>= 1; } } } }; (struct $name:ident([$t:ty])) => { bitfield_bitrange!(@impl_bitrange_slice $name, $t, u8); bitfield_bitrange!(@impl_bitrange_slice $name, $t, u16); bitfield_bitrange!(@impl_bitrange_slice $name, $t, u32); bitfield_bitrange!(@impl_bitrange_slice $name, $t, u64); bitfield_bitrange!(@impl_bitrange_slice $name, $t, u128); bitfield_bitrange!(@impl_bitrange_slice $name, $t, i8); bitfield_bitrange!(@impl_bitrange_slice $name, $t, i16); bitfield_bitrange!(@impl_bitrange_slice $name, $t, i32); bitfield_bitrange!(@impl_bitrange_slice $name, $t, i64); bitfield_bitrange!(@impl_bitrange_slice $name, $t, i128); }; (struct $name:ident(MSB0 [$t:ty])) => { bitfield_bitrange!(@impl_bitrange_slice_msb0 $name, $t, u8); bitfield_bitrange!(@impl_bitrange_slice_msb0 $name, $t, u16); bitfield_bitrange!(@impl_bitrange_slice_msb0 $name, $t, u32); bitfield_bitrange!(@impl_bitrange_slice_msb0 $name, $t, u64); bitfield_bitrange!(@impl_bitrange_slice_msb0 $name, $t, u128); bitfield_bitrange!(@impl_bitrange_slice_msb0 $name, $t, i8); bitfield_bitrange!(@impl_bitrange_slice_msb0 $name, $t, i16); bitfield_bitrange!(@impl_bitrange_slice_msb0 $name, $t, i32); bitfield_bitrange!(@impl_bitrange_slice_msb0 $name, $t, i64); bitfield_bitrange!(@impl_bitrange_slice_msb0 $name, $t, i128); }; (struct $name:ident($t:ty)) => { impl $crate::BitRange for $name where $t: $crate::BitRange { fn bit_range(&self, msb: usize, lsb: usize) -> T { self.0.bit_range(msb, lsb) } } impl $crate::BitRangeMut for $name where $t: $crate::BitRangeMut { fn set_bit_range(&mut self, msb: usize, lsb: usize, value: T) { self.0.set_bit_range(msb, lsb, value); } } }; } /// Combines `bitfield_bitrange` and `bitfield_fields`. /// /// The syntax of this macro is the syntax of a tuple struct, including attributes and /// documentation comments, followed by a semicolon, some optional elements, and finally the fields /// as described in the `bitfield_fields` documentation. /// /// The first optional element is `no default BitRange;`. With that, no implementation of /// `BitRange` will be generated. /// /// The second optional element is a set of lines of the form `impl ;`. The following traits are supported: /// * `Debug`; This will generate an implementation of `fmt::Debug` with the `bitfield_debug` macro. /// * `BitAnd`, `BitOr`, `BitXor`; These will generate implementations of the relevant `ops::Bit___` and `ops::Bit___Assign` traits. /// * `new`; This will generate a constructor that calls all of the bitfield's setter methods with an argument of the appropriate type /// * `new{constructor_name(setter_name: setter_type, ...)}`; This will generate a constructor that calls a given subset of the bitfield's setter methods /// /// The difference with calling those macros separately is that `bitfield_fields` is called /// from an appropriate `impl` block. If you use the non-slice form of `bitfield_bitrange`, the /// default type for `bitfield_fields` will be set to the wrapped fields. /// /// See the documentation of these macros for more information on their respective syntax. /// /// # Example /// /// ```rust /// # #[macro_use] extern crate bitfield; /// # fn main() {} /// bitfield!{ /// pub struct BitField1(u16); /// impl Debug; /// // The fields default to u16 /// field1, set_field1: 10, 0; /// pub field2, _ : 12, 3; /// } /// ``` /// /// or with a custom `BitRange` and `BitRangeMut` implementation : /// ```rust /// # #[macro_use] extern crate bitfield; /// # use bitfield::{BitRange, BitRangeMut}; /// # fn main() {} /// bitfield!{ /// pub struct BitField1(u16); /// no default BitRange; /// impl Debug; /// impl BitAnd; /// u8; /// field1, set_field1: 10, 0; /// pub field2, _ : 12, 3; /// } /// impl BitRange for BitField1 { /// fn bit_range(&self, msb: usize, lsb: usize) -> u8 { /// let width = msb - lsb + 1; /// let mask = (1 << width) - 1; /// ((self.0 >> lsb) & mask) as u8 /// } /// } /// impl BitRangeMut for BitField1 { /// fn set_bit_range(&mut self, msb: usize, lsb: usize, value: u8) { /// self.0 = (value as u16) << lsb; /// } /// } /// ``` #[macro_export(local_inner_macros)] macro_rules! bitfield { // Force `impl ` to always be after `no default BitRange` it the two are present. // This simplify the rest of the macro. ($(#[$attribute:meta])* $vis:vis struct $name:ident($($type:tt)*); $(impl $trait:ident$({$($trait_arg:tt)*})?;)+ no default BitRange; $($rest:tt)*) => { bitfield!{$(#[$attribute])* $vis struct $name($($type)*); no default BitRange; $(impl $trait$({$($trait_arg)*})?;)* $($rest)*} }; // If we have `impl ` without `no default BitRange`, we will still match, because when // we call `bitfield_bitrange`, we add `no default BitRange`. ($(#[$attribute:meta])* $vis:vis struct $name:ident([$t:ty]); no default BitRange; impl $trait:ident$({$($trait_arg:tt)*})?; $($rest:tt)*) => { bitfield_impl!{$trait$({$($trait_arg)*})? for struct $name([$t]); $($rest)*} bitfield!{$(#[$attribute])* $vis struct $name([$t]); no default BitRange; $($rest)*} }; ($(#[$attribute:meta])* $vis:vis struct $name:ident([$t:ty]); no default BitRange; $($rest:tt)*) => { $(#[$attribute])* $vis struct $name(pub T); //impl + AsRef<[$t]>> $name { // bitfield_fields!{$($rest)*} //} impl> $name { bitfield_fields!{only getter; $($rest)*} } impl> $name { bitfield_fields!{only setter; $($rest)*} } }; ($(#[$attribute:meta])* $vis:vis struct $name:ident([$t:ty]); $($rest:tt)*) => { bitfield_bitrange!(struct $name([$t])); bitfield!{$(#[$attribute])* $vis struct $name([$t]); no default BitRange; $($rest)*} }; // The only difference between the MSB0 version anf the non-MSB0 version, is the BitRange // implementation. We delegate everything else to the non-MSB0 version of the macro. ($(#[$attribute:meta])* $vis:vis struct $name:ident(MSB0 [$t:ty]); no default BitRange; $($rest:tt)*) => { bitfield!{$(#[$attribute])* $vis struct $name([$t]); no default BitRange; $($rest)*} }; ($(#[$attribute:meta])* $vis:vis struct $name:ident(MSB0 [$t:ty]); $($rest:tt)*) => { bitfield_bitrange!(struct $name(MSB0 [$t])); bitfield!{$(#[$attribute])* $vis struct $name([$t]); no default BitRange; $($rest)*} }; ($(#[$attribute:meta])* $vis:vis struct $name:ident($t:ty); no default BitRange; impl $trait:ident$({$($trait_arg:tt)*})?; $($rest:tt)*) => { bitfield_impl!{$trait$({$($trait_arg)*})? for struct $name($t); $($rest)*} bitfield!{$(#[$attribute])* $vis struct $name($t); no default BitRange; $($rest)*} }; ($(#[$attribute:meta])* $vis:vis struct $name:ident($t:ty); no default BitRange; $($rest:tt)*) => { $(#[$attribute])* $vis struct $name(pub $t); impl $name { bitfield_fields!{$t; $($rest)*} } }; ($(#[$attribute:meta])* $vis:vis struct $name:ident($t:ty); $($rest:tt)*) => { bitfield_bitrange!(struct $name($t)); bitfield!{$(#[$attribute])* $vis struct $name($t); no default BitRange; $($rest)*} }; } #[doc(hidden)] pub use core::convert::Into; #[doc(hidden)] pub use core::fmt; #[doc(hidden)] pub use core::mem::size_of; #[doc(hidden)] pub use core::ops; /// A trait to get ranges of bits. pub trait BitRange { /// Get a range of bits. fn bit_range(&self, msb: usize, lsb: usize) -> T; } /// A trait to set ranges of bits. pub trait BitRangeMut { /// Set a range of bits. fn set_bit_range(&mut self, msb: usize, lsb: usize, value: T); } /// A trait to get a single bit. /// /// This trait is implemented for all type that implement `BitRange`. pub trait Bit { /// Get a single bit. fn bit(&self, bit: usize) -> bool; } /// A trait to set a single bit. /// /// This trait is implemented for all type that implement `BitRangeMut`. pub trait BitMut { /// Set a single bit. fn set_bit(&mut self, bit: usize, value: bool); } impl> Bit for T { fn bit(&self, bit: usize) -> bool { self.bit_range(bit, bit) != 0 } } impl> BitMut for T { fn set_bit(&mut self, bit: usize, value: bool) { self.set_bit_range(bit, bit, value as u8); } } macro_rules! impl_bitrange_for_u { ($t:ty, $bitrange_ty:ty) => { impl BitRange<$bitrange_ty> for $t { #[inline] #[allow(clippy::cast_lossless)] #[allow(clippy::manual_bits)] fn bit_range(&self, msb: usize, lsb: usize) -> $bitrange_ty { let bit_len = size_of::<$t>()*8; let result_bit_len = size_of::<$bitrange_ty>()*8; let result = ((*self << (bit_len - msb - 1)) >> (bit_len - msb - 1 + lsb)) as $bitrange_ty; result << (result_bit_len - (msb - lsb + 1)) >> (result_bit_len - (msb - lsb + 1)) } } impl BitRangeMut<$bitrange_ty> for $t { #[inline] #[allow(clippy::cast_lossless)] #[allow(clippy::manual_bits)] fn set_bit_range(&mut self, msb: usize, lsb: usize, value: $bitrange_ty) { let bit_len = size_of::<$t>()*8; let mask: $t = !(0 as $t) << (bit_len - msb - 1) >> (bit_len - msb - 1 + lsb) << (lsb); *self &= !mask; *self |= (value as $t << lsb) & mask; } } } } macro_rules! impl_bitrange_for_u_combinations { ((),($($bitrange_ty:ty),*)) => { }; (($t:ty),($($bitrange_ty:ty),*)) => { $(impl_bitrange_for_u!{$t, $bitrange_ty})* }; (($t_head:ty, $($t_rest:ty),*),($($bitrange_ty:ty),*)) => { impl_bitrange_for_u_combinations!{($t_head), ($($bitrange_ty),*)} impl_bitrange_for_u_combinations!{($($t_rest),*), ($($bitrange_ty),*)} }; } impl_bitrange_for_u_combinations! {(u8, u16, u32, u64, u128), (u8, u16, u32, u64, u128)} impl_bitrange_for_u_combinations! {(u8, u16, u32, u64, u128), (i8, i16, i32, i64, i128)} // Same as std::stringify but callable from local_inner_macros macros defined inside // this crate. #[macro_export] #[doc(hidden)] macro_rules! __bitfield_stringify { ($s:ident) => { stringify!($s) }; } // Same as std::debug_assert but callable from local_inner_macros macros defined inside // this crate. #[macro_export] #[doc(hidden)] macro_rules! __bitfield_debug_assert { ($e:expr) => { debug_assert!($e) }; } bitfield-0.17.0/tests/lib.rs000064400000000000000000001042521046102023000137550ustar 00000000000000#![recursion_limit = "128"] #![allow(clippy::cognitive_complexity)] #[macro_use] extern crate bitfield; // We use a constant to make sure bits positions don't need to be literals but // can also be constants or expressions. const THREE: usize = 3; #[derive(Copy, Clone, Debug)] pub struct Foo(u16); impl From for Foo { fn from(value: u8) -> Foo { Foo(u16::from(value)) } } impl From for u8 { fn from(value: Foo) -> u8 { value.0 as u8 } } bitfield! { #[derive(Copy, Clone)] /// documentation comments also work! struct FooBar(u32); impl Debug; impl BitOr; foo1, set_foo1: 0, 0; u8; foo2, set_foo2: 31, 31; foo3, set_foo3: THREE, 0; // We make sure attributes are applied to fields. If attributes were not // applied, the compilation would fail with a `duplicate definition` // error. #[cfg(not(test))] foo3, set_foo3: 3, 0; u16, foo4, set_foo4: 31, 28; foo5, set_foo5: 0, 0, 32; u32; foo6, set_foo6: 5, THREE, THREE; mask GETTER_MASK(u32), getter_only, _: 3, 1; mask SETTER_MASK(u32), _, setter_only: 2*2, 2; pub mask PUB_GETTER_MASK(u32), pub_getter_only, _: 3, 1; pub mask PUB_SETTER_MASK(u32), _, pub_setter_only: 2*2, 2; getter_only_array, _: 5, 3, 3; _, setter_only_array: 2*THREE, 4, 3; all_bits, set_all_bits: 31, 0; mask SINGLE_BIT_MASK(u32), single_bit, set_single_bit: 3; u8, into Foo, into_foo1, set_into_foo1: 31, 31; pub u8, mask PUB_MASK(u32), into Foo, into_foo2, set_into_foo2: 31, 31; u8, from into Foo, from_foo1, set_from_foo1: 31, 31; u8, from into Foo, _, set_from_foo2: 31, 31; u8; into Foo, into_foo3, set_into_foo3: 31, 31; pub into Foo, into_foo4, set_into_foo4: 31, 31; into Foo, _, set_into_foo5: 31, 31; into Foo, into_foo6, _: 29, 29, 3; from into Foo, from_foo3, set_from_foo3: 31, 31; from into Foo, _, set_from_foo4: 31, 31; from into Foo, from_foo5, set_from_foo5: 29, 29, 3; from into Foo, from_foo6, _: 31, 31; i8; signed_single_bit, set_signed_single_bit: 0, 0; signed_two_bits, set_signed_two_bits: 1, 0; signed_eight_bits, set_signed_eight_bits: 7, 0; signed_eight_bits_unaligned, set_signed_eight_bits_unaligned: 8, 1; u128, mask U128_MASK(u128), u128_getter, set_u128: 8, 1; i128, mask I128_MASK(i128), i128_getter, set_i128: 8, 1; } impl FooBar { bitfield_fields! { // Boolean field don't need a type foo7, _: 1; } bitfield_fields! { // If all fields have a type, we don't need to specify a default type u8, foo8,_: 1, 0; u32, foo9, _: 2, 0; } bitfield_fields! { // We can still set a default type u16; foo10, _: 2, 0; u32, foo11, _: 2, 0; foo12, _: 2, 0; } // Check if an empty bitfield_fields compiles without errors. bitfield_fields! {} } #[test] fn test_single_bit() { let mut fb = FooBar(0); fb.set_foo1(1); assert_eq!(0x1, fb.0); assert_eq!(0x1, fb.foo1()); assert_eq!(0x0, fb.foo2()); assert!(!fb.single_bit()); assert_eq!(-1, fb.signed_single_bit()); fb.set_foo2(1); assert_eq!(0x8000_0001, fb.0); assert_eq!(0x1, fb.foo1()); assert_eq!(0x1, fb.foo2()); assert!(!fb.single_bit()); assert_eq!(-1, fb.signed_single_bit()); fb.set_foo1(0); assert_eq!(0x8000_0000, fb.0); assert_eq!(0x0, fb.foo1()); assert_eq!(0x1, fb.foo2()); assert!(!fb.single_bit()); assert_eq!(0, fb.signed_single_bit()); fb.set_single_bit(true); assert_eq!(0x8000_0008, fb.0); assert_eq!(0x0, fb.foo1()); assert_eq!(0x1, fb.foo2()); assert!(fb.single_bit()); assert_eq!(0, fb.signed_single_bit()); fb.set_signed_single_bit(-1); assert_eq!(0x8000_0009, fb.0); assert_eq!(0x1, fb.foo1()); assert_eq!(0x1, fb.foo2()); assert!(fb.single_bit()); assert_eq!(-1, fb.signed_single_bit()); } #[test] fn test_single_bit_plus_garbage() { let mut fb = FooBar(0); fb.set_foo1(0b10); assert_eq!(0x0, fb.0); assert_eq!(0x0, fb.foo1()); assert_eq!(0x0, fb.foo2()); fb.set_foo1(0b11); assert_eq!(0x1, fb.0); assert_eq!(0x1, fb.foo1()); assert_eq!(0x0, fb.foo2()); } #[test] fn test_multiple_bit() { let mut fb = FooBar(0); fb.set_foo3(0x0F); assert_eq!(0xF, fb.0); assert_eq!(0xF, fb.foo3()); assert_eq!(0x0, fb.foo4()); fb.set_foo4(0x0F); assert_eq!(0xF000_000F, fb.0); assert_eq!(0xF, fb.foo3()); assert_eq!(0xF, fb.foo4()); fb.set_foo3(0); assert_eq!(0xF000_0000, fb.0); assert_eq!(0x0, fb.foo3()); assert_eq!(0xF, fb.foo4()); fb.set_foo3(0xA); assert_eq!(0xF000_000A, fb.0); assert_eq!(0xA, fb.foo3()); assert_eq!(0xF, fb.foo4()); } bitfield! { #[derive(Clone, Copy)] struct FourFields(u8); impl BitOr; impl BitAnd; impl BitXor; impl new; a, set_a: 0; b, set_b: 1; c, set_c: 2; d, set_d: 3; } #[test] fn test_bitwise_ops() { let mut ff1 = FourFields(0); ff1.set_a(true); ff1.set_b(true); let mut ff2 = FourFields(0); ff2.set_a(true); ff2.set_c(true); let ffand = ff1 & ff2; assert!(ffand.a()); assert!(!ffand.b()); assert!(!ffand.c()); assert!(!ffand.d()); let ffor = ff1 | ff2; assert!(ffor.a()); assert!(ffor.b()); assert!(ffor.c()); assert!(!ffor.d()); let ffxor = ff1 ^ ff2; assert!(!ffxor.a()); assert!(ffxor.b()); assert!(ffxor.c()); assert!(!ffxor.d()); ff1 ^= ff2; assert!(!ff1.a()); assert!(ff1.b()); assert!(ff1.c()); assert!(!ff1.d()); } #[test] fn test_constructor() { let ff1 = FourFields::new(true, false, true, false); assert!(ff1.a()); assert!(!ff1.b()); assert!(ff1.c()); assert!(!ff1.d()); } #[test] fn test_getter_setter_only() { let mut fb = FooBar(0); fb.setter_only(0x7); assert_eq!(0x1C, fb.0); assert_eq!(0x6, fb.getter_only()); } #[test] fn test_array_field1() { let mut fb = FooBar(0); fb.set_foo5(0, 1); assert_eq!(0x1, fb.0); assert_eq!(1, fb.foo5(0)); fb.set_foo5(0, 0); assert_eq!(0x0, fb.0); assert_eq!(0, fb.foo5(0)); fb.set_foo5(0, 1); fb.set_foo5(6, 1); fb.set_foo5(31, 1); assert_eq!(0x8000_0041, fb.0); assert_eq!(1, fb.foo5(0)); assert_eq!(1, fb.foo5(6)); assert_eq!(1, fb.foo5(31)); assert_eq!(0, fb.foo5(1)); assert_eq!(0, fb.foo5(5)); assert_eq!(0, fb.foo5(7)); assert_eq!(0, fb.foo5(30)); } #[test] fn test_array_field2() { let mut fb = FooBar(0); fb.set_foo6(0, 1); assert_eq!(0x8, fb.0); assert_eq!(1, fb.foo6(0)); assert_eq!(0, fb.foo6(1)); assert_eq!(0, fb.foo6(2)); fb.set_foo6(0, 7); assert_eq!(0x38, fb.0); assert_eq!(7, fb.foo6(0)); assert_eq!(0, fb.foo6(1)); assert_eq!(0, fb.foo6(2)); fb.set_foo6(2, 7); assert_eq!(0xE38, fb.0); assert_eq!(7, fb.foo6(0)); assert_eq!(0, fb.foo6(1)); assert_eq!(7, fb.foo6(2)); fb.set_foo6(0, 0); assert_eq!(0xE00, fb.0); assert_eq!(0, fb.foo6(0)); assert_eq!(0, fb.foo6(1)); assert_eq!(7, fb.foo6(2)); } #[allow(clippy::identity_op)] #[allow(clippy::erasing_op)] #[test] fn test_setter_only_array() { let mut fb = FooBar(0); fb.setter_only_array(0, 0); assert_eq!(0x0, fb.0); fb.setter_only_array(0, 0b111); assert_eq!(0b111 << (4 + 0 * 2), fb.0); fb.setter_only_array(0, 0); fb.setter_only_array(1, 0b111); assert_eq!(0b111 << (4 + 1 * 3), fb.0); fb.setter_only_array(1, 0); fb.setter_only_array(2, 0b111); assert_eq!(0b111 << (4 + 2 * 3), fb.0); } #[test] fn test_getter_only_array() { let mut fb = FooBar(0); assert_eq!(0, fb.getter_only_array(0)); assert_eq!(0, fb.getter_only_array(1)); assert_eq!(0, fb.getter_only_array(2)); fb.0 = !(0x1FF << 3); assert_eq!(0, fb.getter_only_array(0)); assert_eq!(0, fb.getter_only_array(1)); assert_eq!(0, fb.getter_only_array(2)); fb.0 = 0xF << 3; assert_eq!(0b111, fb.getter_only_array(0)); assert_eq!(0b001, fb.getter_only_array(1)); assert_eq!(0, fb.getter_only_array(2)); fb.0 = 0xF << 6; assert_eq!(0, fb.getter_only_array(0)); assert_eq!(0b111, fb.getter_only_array(1)); assert_eq!(0b001, fb.getter_only_array(2)); fb.0 = 0xF << 8; assert_eq!(0, fb.getter_only_array(0)); assert_eq!(0b100, fb.getter_only_array(1)); assert_eq!(0b111, fb.getter_only_array(2)); fb.0 = 0b101_010_110 << 3; assert_eq!(0b110, fb.getter_only_array(0)); assert_eq!(0b010, fb.getter_only_array(1)); assert_eq!(0b101, fb.getter_only_array(2)); } #[test] fn test_signed() { let mut fb = FooBar(0); assert_eq!(0, fb.signed_two_bits()); assert_eq!(0, fb.signed_eight_bits()); assert_eq!(0, fb.signed_eight_bits_unaligned()); fb.set_signed_two_bits(-2); assert_eq!(0b10, fb.0); assert_eq!(-2, fb.signed_two_bits()); assert_eq!(2, fb.signed_eight_bits()); assert_eq!(1, fb.signed_eight_bits_unaligned()); fb.set_signed_two_bits(-1); assert_eq!(0b11, fb.0); assert_eq!(-1, fb.signed_two_bits()); assert_eq!(3, fb.signed_eight_bits()); assert_eq!(1, fb.signed_eight_bits_unaligned()); fb.set_signed_two_bits(0); assert_eq!(0, fb.0); assert_eq!(0, fb.signed_two_bits()); assert_eq!(0, fb.signed_eight_bits()); assert_eq!(0, fb.signed_eight_bits_unaligned()); fb.set_signed_two_bits(1); assert_eq!(1, fb.0); assert_eq!(1, fb.signed_two_bits()); assert_eq!(1, fb.signed_eight_bits()); assert_eq!(0, fb.signed_eight_bits_unaligned()); fb.set_signed_eight_bits(0); assert_eq!(0, fb.0); assert_eq!(0, fb.signed_two_bits()); assert_eq!(0, fb.signed_eight_bits()); assert_eq!(0, fb.signed_eight_bits_unaligned()); fb.set_signed_eight_bits(-1); assert_eq!(0xFF, fb.0); assert_eq!(-1, fb.signed_two_bits()); assert_eq!(-1, fb.signed_eight_bits()); assert_eq!(127, fb.signed_eight_bits_unaligned()); fb.set_signed_eight_bits(-128); assert_eq!(0x80, fb.0); assert_eq!(0, fb.signed_two_bits()); assert_eq!(-128, fb.signed_eight_bits()); assert_eq!(64, fb.signed_eight_bits_unaligned()); fb.set_signed_eight_bits(127); assert_eq!(0x7F, fb.0); assert_eq!(-1, fb.signed_two_bits()); assert_eq!(127, fb.signed_eight_bits()); assert_eq!(63, fb.signed_eight_bits_unaligned()); fb.set_signed_eight_bits_unaligned(0); assert_eq!(1, fb.0); assert_eq!(1, fb.signed_two_bits()); assert_eq!(1, fb.signed_eight_bits()); assert_eq!(0, fb.signed_eight_bits_unaligned()); fb.set_signed_eight_bits(0); fb.set_signed_eight_bits_unaligned(-1); assert_eq!(0x1FE, fb.0); assert_eq!(-2, fb.signed_two_bits()); assert_eq!(-2, fb.signed_eight_bits()); assert_eq!(-1, fb.signed_eight_bits_unaligned()); fb.set_signed_eight_bits_unaligned(-128); assert_eq!(0x100, fb.0); assert_eq!(0, fb.signed_two_bits()); assert_eq!(0, fb.signed_eight_bits()); assert_eq!(-128, fb.signed_eight_bits_unaligned()); fb.set_signed_eight_bits_unaligned(127); assert_eq!(0xFE, fb.0); assert_eq!(-2, fb.signed_two_bits()); assert_eq!(-2, fb.signed_eight_bits()); assert_eq!(127, fb.signed_eight_bits_unaligned()); } #[test] fn test_field_type() { let fb = FooBar(0); let _: u32 = fb.foo1(); let _: u8 = fb.foo2(); let _: u8 = fb.foo3(); let _: u16 = fb.foo4(); let _: u8 = fb.foo5(0); let _: u32 = fb.foo6(0); let _: bool = fb.foo7(); let _: u8 = fb.foo8(); let _: u32 = fb.foo9(); let _: u16 = fb.foo10(); let _: u32 = fb.foo11(); let _: u16 = fb.foo12(); let _: Foo = fb.into_foo1(); let _: Foo = fb.into_foo2(); let _: Foo = fb.into_foo3(); let _: Foo = fb.into_foo4(); let _: Foo = fb.into_foo6(0); let _: Foo = fb.from_foo1(); let _: Foo = fb.from_foo3(); let _: Foo = fb.from_foo5(0); let _: i8 = fb.signed_single_bit(); let _: i8 = fb.signed_two_bits(); let _: i8 = fb.signed_eight_bits(); let _: i8 = fb.signed_eight_bits_unaligned(); let _: u128 = fb.u128_getter(); let _: i128 = fb.i128_getter(); } #[test] fn test_into_setter() { let mut fb = FooBar(0); // We just check that the parameter type is correct fb.set_into_foo1(0u8); fb.set_into_foo2(0u8); fb.set_into_foo3(0u8); fb.set_into_foo4(0u8); } #[test] fn test_from_setter() { let mut fb = FooBar(0); assert_eq!(0, fb.0); fb.set_from_foo1(Foo(1)); assert_eq!(1 << 31, fb.0); fb.set_from_foo1(Foo(0)); assert_eq!(0, fb.0); fb.set_from_foo2(Foo(1)); assert_eq!(1 << 31, fb.0); fb.set_from_foo2(Foo(0)); assert_eq!(0, fb.0); fb.set_from_foo3(Foo(1)); assert_eq!(1 << 31, fb.0); fb.set_from_foo3(Foo(0)); assert_eq!(0, fb.0); fb.set_from_foo4(Foo(1)); assert_eq!(1 << 31, fb.0); fb.set_from_foo4(Foo(0)); assert_eq!(0, fb.0); fb.set_from_foo5(1, Foo(1)); assert_eq!(1 << 30, fb.0); } #[test] fn test_all_bits() { let mut fb = FooBar(0); assert_eq!(0, fb.all_bits()); fb.set_all_bits(!0u32); assert_eq!(!0u32, fb.0); assert_eq!(!0u32, fb.all_bits()); fb.0 = 0x8000_0001; assert_eq!(0x8000_0001, fb.all_bits()); } #[test] fn test_is_copy() { let a = FooBar(0); let _b = a; let _c = a; } #[test] fn test_debug() { let fb = FooBar(1_234_567_890); let expected = "FooBar { .0: 1234567890, foo1: 0, foo2: 0, foo3: 2, foo3: 2, foo4: 4, foo5: [0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0], foo6: [2, 3, 1], getter_only: 1, pub_getter_only: 1, getter_only_array: [2, 3, 1], all_bits: 1234567890, single_bit: false, into_foo1: Foo(0), into_foo2: Foo(0), from_foo1: Foo(0), into_foo3: Foo(0), into_foo4: Foo(0), into_foo6: [Foo(0), Foo(1), Foo(0)], from_foo3: Foo(0), from_foo5: [Foo(0), Foo(1), Foo(0)], from_foo6: Foo(0), signed_single_bit: 0, signed_two_bits: -2, signed_eight_bits: -46, signed_eight_bits_unaligned: 105, u128_getter: 105, i128_getter: 105 }"; assert_eq!(expected, format!("{:?}", fb)) } bitfield! { #[derive(Clone, Copy)] struct ArrayBitfield([u8]); impl BitAnd; impl BitOr; impl BitXor; impl new; impl new{foo_unsigned (set_foo1: u32, set_foo2: u32, set_foo3: u32, set_foo4: u32)}; impl new{foo_signed (set_signed_foo1: i32, set_signed_foo2: i32, set_signed_foo3: i32, set_signed_foo4: i32)}; u32; foo1, set_foo1: 0, 0; foo2, set_foo2: 7, 0; foo3, set_foo3: 8, 1; foo4, set_foo4: 19, 4; i32; signed_foo1, set_signed_foo1: 0, 0; signed_foo2, set_signed_foo2: 7, 0; signed_foo3, set_signed_foo3: 8, 1; signed_foo4, set_signed_foo4: 19, 4; u128, u128_getter, set_u128: 19, 4; } #[test] fn test_arraybitfield() { let mut ab = ArrayBitfield([0; 3]); assert_eq!(0u32, ab.foo1()); assert_eq!(0u32, ab.foo2()); assert_eq!(0u32, ab.foo3()); assert_eq!(0u32, ab.foo4()); assert_eq!(0i32, ab.signed_foo1()); assert_eq!(0i32, ab.signed_foo2()); assert_eq!(0i32, ab.signed_foo3()); assert_eq!(0i32, ab.signed_foo4()); assert_eq!(0u128, ab.u128_getter()); ab.set_foo1(1); assert_eq!([1, 0, 0], ab.0); assert_eq!(1, ab.foo1()); assert_eq!(1, ab.foo2()); assert_eq!(0, ab.foo3()); assert_eq!(0, ab.foo4()); assert_eq!(-1, ab.signed_foo1()); assert_eq!(1, ab.signed_foo2()); assert_eq!(0, ab.signed_foo3()); assert_eq!(0, ab.signed_foo4()); assert_eq!(0, ab.u128_getter()); ab.set_foo1(0); ab.set_foo2(0xFF); assert_eq!([0xFF, 0, 0], ab.0); assert_eq!(1, ab.foo1()); assert_eq!(0xFF, ab.foo2()); assert_eq!(0x7F, ab.foo3()); assert_eq!(0x0F, ab.foo4()); assert_eq!(-1, ab.signed_foo1()); assert_eq!(-1, ab.signed_foo2()); assert_eq!(127, ab.signed_foo3()); assert_eq!(0x0F, ab.signed_foo4()); assert_eq!(0x0F, ab.u128_getter()); ab.set_foo2(0); ab.set_foo3(0xFF); assert_eq!([0xFE, 0x01, 0], ab.0); assert_eq!(0, ab.foo1()); assert_eq!(0xFE, ab.foo2()); assert_eq!(0xFF, ab.foo3()); assert_eq!(0x1F, ab.foo4()); assert_eq!(0, ab.signed_foo1()); assert_eq!(-2, ab.signed_foo2()); assert_eq!(-1, ab.signed_foo3()); assert_eq!(0x1F, ab.signed_foo4()); assert_eq!(0x1F, ab.u128_getter()); ab.set_foo3(0); ab.set_foo4(0xFFFF); assert_eq!([0xF0, 0xFF, 0x0F], ab.0); assert_eq!(0, ab.foo1()); assert_eq!(0xF0, ab.foo2()); assert_eq!(0xF8, ab.foo3()); assert_eq!(0xFFFF, ab.foo4()); assert_eq!(0, ab.signed_foo1()); assert_eq!(-16, ab.signed_foo2()); assert_eq!(-8, ab.signed_foo3()); assert_eq!(-1, ab.signed_foo4()); assert_eq!(0xFFFF, ab.u128_getter()); ab.set_foo4(0x0); ab.set_signed_foo1(0); assert_eq!([0x00, 0x00, 0x00], ab.0); ab.set_signed_foo1(-1); assert_eq!([0x01, 0x00, 0x00], ab.0); ab.set_signed_foo1(0); ab.set_signed_foo2(127); assert_eq!([0x7F, 0x00, 0x00], ab.0); ab.set_signed_foo2(-128); assert_eq!([0x80, 0x00, 0x00], ab.0); ab.set_signed_foo2(1); assert_eq!([0x01, 0x00, 0x00], ab.0); ab.set_signed_foo2(-1); assert_eq!([0xFF, 0x00, 0x00], ab.0); ab.set_signed_foo2(0); ab.set_signed_foo3(127); assert_eq!([0xFE, 0x00, 0x00], ab.0); ab.set_signed_foo3(-1); assert_eq!([0xFE, 0x01, 0x00], ab.0); ab.set_signed_foo3(0); ab.set_signed_foo4(-1); assert_eq!([0xF0, 0xFF, 0x0F], ab.0); ab.set_signed_foo4(0); ab.set_u128(0xFFFF); assert_eq!([0xF0, 0xFF, 0x0F], ab.0); } #[test] fn test_arraybitfield2() { // Check that the macro can be called from a function. bitfield! { struct ArrayBitfield2([u16]); impl Debug; u32; foo1, set_foo1: 0, 0; foo2, set_foo2: 7, 0; foo3, set_foo3: 8, 1; foo4, set_foo4: 20, 4; } let mut ab = ArrayBitfield2([0; 2]); assert_eq!(0, ab.foo1()); assert_eq!(0, ab.foo2()); assert_eq!(0, ab.foo3()); assert_eq!(0, ab.foo4()); ab.set_foo1(1); assert_eq!([1, 0], ab.0); assert_eq!(1, ab.foo1()); assert_eq!(1, ab.foo2()); assert_eq!(0, ab.foo3()); assert_eq!(0, ab.foo4()); ab.set_foo1(0); ab.set_foo2(0xFF); assert_eq!([0xFF, 0], ab.0); assert_eq!(1, ab.foo1()); assert_eq!(0xFF, ab.foo2()); assert_eq!(0x7F, ab.foo3()); assert_eq!(0x0F, ab.foo4()); ab.set_foo2(0); ab.set_foo3(0xFF); assert_eq!([0x1FE, 0x0], ab.0); assert_eq!(0, ab.foo1()); assert_eq!(0xFE, ab.foo2()); assert_eq!(0xFF, ab.foo3()); assert_eq!(0x1F, ab.foo4()); ab.set_foo3(0); ab.set_foo4(0xFFFF); assert_eq!([0xFFF0, 0xF], ab.0); assert_eq!(0, ab.foo1()); assert_eq!(0xF0, ab.foo2()); assert_eq!(0xF8, ab.foo3()); assert_eq!(0xFFFF, ab.foo4()); } bitfield! { pub(self) struct ArrayBitfieldMsb0(MSB0 [u8]); impl Debug; u32; foo1, set_foo1: 0, 0; foo2, set_foo2: 7, 0; foo3, set_foo3: 8, 1; foo4, set_foo4: 19, 4; i32; signed_foo1, set_signed_foo1: 0, 0; signed_foo2, set_signed_foo2: 7, 0; signed_foo3, set_signed_foo3: 8, 1; signed_foo4, set_signed_foo4: 19, 4; } #[test] fn test_arraybitfield_msb0() { let mut ab = ArrayBitfieldMsb0([0; 3]); assert_eq!(0, ab.foo1()); assert_eq!(0, ab.foo2()); assert_eq!(0, ab.foo3()); assert_eq!(0, ab.foo4()); assert_eq!(0, ab.signed_foo1()); assert_eq!(0, ab.signed_foo2()); assert_eq!(0, ab.signed_foo3()); assert_eq!(0, ab.signed_foo4()); ab.set_foo1(1); assert_eq!([0b1000_0000, 0, 0], ab.0); assert_eq!(1, ab.foo1()); assert_eq!(0b1000_0000, ab.foo2()); assert_eq!(0, ab.foo3()); assert_eq!(0, ab.foo4()); assert_eq!(-1, ab.signed_foo1()); assert_eq!(-128, ab.signed_foo2()); assert_eq!(0, ab.signed_foo3()); assert_eq!(0, ab.signed_foo4()); ab.set_foo1(0); ab.set_foo2(0xFF); assert_eq!([0b1111_1111, 0, 0], ab.0); assert_eq!(1, ab.foo1()); assert_eq!(0b1111_1111, ab.foo2()); assert_eq!(0b1111_1110, ab.foo3()); assert_eq!(0b1111_0000_0000_0000, ab.foo4()); assert_eq!(-1, ab.signed_foo1()); assert_eq!(-1, ab.signed_foo2()); assert_eq!(-2, ab.signed_foo3()); assert_eq!(-4096, ab.signed_foo4()); ab.set_foo2(0); ab.set_foo3(0xFF); assert_eq!([0b0111_1111, 0b1000_0000, 0], ab.0); assert_eq!(0, ab.foo1()); assert_eq!(0b0111_1111, ab.foo2()); assert_eq!(0xFF, ab.foo3()); assert_eq!(0b1111_1000_0000_0000, ab.foo4()); assert_eq!(0, ab.signed_foo1()); assert_eq!(127, ab.signed_foo2()); assert_eq!(-1, ab.signed_foo3()); assert_eq!(-2048, ab.signed_foo4()); ab.set_foo3(0); ab.set_foo4(0xFFFF); assert_eq!([0x0F, 0xFF, 0xF0], ab.0); assert_eq!(0, ab.foo1()); assert_eq!(0x0F, ab.foo2()); assert_eq!(0b0001_1111, ab.foo3()); assert_eq!(0xFFFF, ab.foo4()); assert_eq!(0, ab.signed_foo1()); assert_eq!(0x0F, ab.signed_foo2()); assert_eq!(0b0001_1111, ab.signed_foo3()); assert_eq!(-1, ab.signed_foo4()); ab.set_foo4(0x0); ab.set_signed_foo1(0); assert_eq!([0x00, 0x00, 0x00], ab.0); ab.set_signed_foo1(-1); assert_eq!([0b1000_0000, 0x00, 0x00], ab.0); ab.set_signed_foo1(0); ab.set_signed_foo2(127); assert_eq!([0x7F, 0x00, 0x00], ab.0); ab.set_signed_foo2(-128); assert_eq!([0x80, 0x00, 0x00], ab.0); ab.set_signed_foo2(1); assert_eq!([0x01, 0x00, 0x00], ab.0); ab.set_signed_foo2(-1); assert_eq!([0xFF, 0x00, 0x00], ab.0); ab.set_signed_foo2(0); ab.set_signed_foo3(127); assert_eq!([0b0011_1111, 0b1000_0000, 0], ab.0); ab.set_signed_foo3(-1); assert_eq!([0b0111_1111, 0b1000_0000, 0], ab.0); ab.set_signed_foo3(0); ab.set_signed_foo4(-1); assert_eq!([0x0F, 0xFF, 0xF0], ab.0); } #[test] fn test_arraybitfield_bitops() { let mut a = ArrayBitfield([1u8; 3]); let b = ArrayBitfield([1u8, 2u8, 4u8]); let c = a | b; assert_eq!(c.0, [1, 3, 5]); let d = a & b; assert_eq!(d.0, [1, 0, 0]); let e = a ^ b; assert_eq!(e.0, [0, 3, 5]); a ^= b; assert_eq!(a.0, [0, 3, 5]); let mut vec_a = ArrayBitfield(vec![1u8; 3]); let vec_b = ArrayBitfield(vec![1u8, 2u8, 4u8]); let vec_c = vec_a.clone() | vec_b.clone(); assert_eq!(vec_c.0, [1, 3, 5]); let vec_d = vec_a.clone() & vec_b.clone(); assert_eq!(vec_d.0, [1, 0, 0]); let vec_e = vec_a.clone() ^ vec_b.clone(); assert_eq!(vec_e.0, [0, 3, 5]); vec_a ^= vec_b; assert_eq!(vec_a.0, [0, 3, 5]); } #[test] fn test_arraybitfield_constructor() { let a: ArrayBitfield<[u8; 3]> = ArrayBitfield::new(1, 2, 3, 4, -1, -2, -3, -4, 0b0001_0000); println!("{:b}", a.0[0]); assert_eq!(a.foo1(), 0); assert_eq!(a.foo2(), 10); assert_eq!(a.foo3(), 133); assert_eq!(a.foo4(), 16); let b: ArrayBitfield<[u8; 3]> = ArrayBitfield::foo_unsigned(1, 4, 6, u32::MAX); assert_eq!(b.signed_foo1(), 0); assert_eq!(b.signed_foo2(), -4); assert_eq!(b.signed_foo3(), -2); assert_eq!(b.signed_foo4(), -1); } mod some_module { bitfield! { pub(super) struct PubBitFieldInAModule(u32); impl Debug; /// Attribute works on pub fields pub field1, set_field1: 1; pub field2, _: 1; pub _, set_field3: 1; pub u16, field4, set_field4: 1; /// Check if multiple attributes are applied #[cfg(not(test))] pub u16, field4, set_field4: 1; pub u16, _, set_field5: 1; pub u16, field6, _: 1; pub field7, set_field7: 1; pub field8, set_field8: 1, 1; #[cfg(not(test))] /// And make sure not only the last attributes is applied pub field8, set_field8: 1, 1; pub field9, set_field9: 1, 1, 1; pub u32, field10, set_field10: 1; pub u32, field11, set_field11: 1, 1; pub u32, field12, set_field12: 1, 1, 1; } } #[test] fn struct_can_be_public() { let _ = some_module::PubBitFieldInAModule(0); } #[test] fn field_can_be_public() { let mut a = some_module::PubBitFieldInAModule(0); let _ = a.field1(); a.set_field1(true); let _ = a.field2(); a.set_field3(true); let _ = a.field4(); a.set_field4(true); a.set_field5(true); let _ = a.field6(); let _ = a.field7(); a.set_field7(true); let _ = a.field8(); a.set_field8(0); let _ = a.field9(0); a.set_field9(0, 0); let _ = a.field10(); a.set_field10(true); let _ = a.field11(); a.set_field11(0); let _ = a.field12(0); a.set_field12(0, 0); } // Everything in this module is to make sure that its possible to specify types // in most of the possible ways. #[allow(dead_code)] mod test_types { use bitfield::{BitRange, BitRangeMut}; use std::sync::atomic::{self, AtomicUsize}; struct Foo; impl Foo { bitfield_fields! { std::sync::atomic::AtomicUsize, field1, set_field1: 0, 0; std::sync::atomic::AtomicUsize; field2, set_field2: 0, 0; ::std::sync::atomic::AtomicUsize, field3, set_field3: 0, 0; ::std::sync::atomic::AtomicUsize; field4, set_field4: 0, 0; atomic::AtomicUsize, field5, set_field5: 0, 0; atomic::AtomicUsize; field6, set_field6: 0, 0; AtomicUsize, field7, set_field7: 0, 0; AtomicUsize; field8, set_field8: 0, 0; Vec, field9, set_field9: 0, 0; Vec; field10, set_field10: 0, 0; Vec<::std::sync::atomic::AtomicUsize>, field11, set_field11: 0, 0; Vec<::std::sync::atomic::AtomicUsize>; field12, set_field12: 0, 0; Vec, field13, set_field13: 0, 0; Vec; field14, set_field14: 0, 0; Vec, field15, set_field15: 0, 0; Vec; field16, set_field16: 0, 0; &str, field17, set_field17: 0, 0; &str; field18, set_field18: 0, 0; &'static str, field19, set_field19: 0, 0; &'static str; field20, set_field20: 0, 0; } } impl BitRange for Foo { fn bit_range(&self, _msb: usize, _lsb: usize) -> AtomicUsize { AtomicUsize::new(0) } } impl BitRangeMut for Foo { fn set_bit_range(&mut self, _msb: usize, _lsb: usize, _value: AtomicUsize) {} } impl BitRange> for Foo { fn bit_range(&self, _msb: usize, _lsb: usize) -> Vec { vec![AtomicUsize::new(0)] } } impl BitRangeMut> for Foo { fn set_bit_range(&mut self, _msb: usize, _lsb: usize, _value: Vec) {} } impl<'a> BitRange<&'a str> for Foo { fn bit_range(&self, _msb: usize, _lsb: usize) -> &'a str { "" } } impl<'a> BitRangeMut<&'a str> for Foo { fn set_bit_range(&mut self, _msb: usize, _lsb: usize, _value: &'a str) {} } #[test] fn test_field_type() { let test = Foo; let _: AtomicUsize = test.field1(); let _: AtomicUsize = test.field2(); let _: AtomicUsize = test.field3(); let _: AtomicUsize = test.field4(); let _: AtomicUsize = test.field5(); let _: AtomicUsize = test.field6(); let _: AtomicUsize = test.field7(); let _: AtomicUsize = test.field8(); let _: Vec = test.field9(); let _: Vec = test.field10(); let _: Vec = test.field11(); let _: Vec = test.field12(); let _: Vec = test.field13(); let _: Vec = test.field14(); let _: Vec = test.field15(); let _: Vec = test.field16(); let _: &str = test.field17(); let _: &str = test.field18(); let _: &'static str = test.field19(); let _: &'static str = test.field20(); } } #[allow(dead_code)] mod test_no_default_bitrange { use bitfield::{BitRange, BitRangeMut}; use std::fmt::Debug; use std::fmt::Error; use std::fmt::Formatter; use crate::FooBar; bitfield! { #[derive(Eq, PartialEq)] pub struct BitField1(u16); no default BitRange; impl Debug; u8; field1, set_field1: 10, 0; pub field2, _ : 12, 3; field3, set_field3: 2; } impl BitRange for BitField1 { fn bit_range(&self, msb: usize, lsb: usize) -> u8 { (msb + lsb) as u8 } } impl BitRangeMut for BitField1 { fn set_bit_range(&mut self, msb: usize, lsb: usize, value: u8) { self.0 = msb as u16 + lsb as u16 + u16::from(value) } } #[allow(clippy::identity_op)] #[test] fn custom_bitrange_implementation_is_used() { let mut bf = BitField1(0); assert_eq!(bf.field1(), 10 + 0); assert_eq!(bf.field2(), 12 + 3); assert!(bf.field3()); bf.set_field1(42); assert_eq!(bf, BitField1(10 + 0 + 42)); } bitfield! { pub(crate) struct BitField2(u16); no default BitRange; u8; field1, set_field1: 10, 0; pub field2, _ : 12, 3; field3, set_field3: 0; } impl BitRange for BitField2 { fn bit_range(&self, _msb: usize, _lsb: usize) -> u8 { 0 } } impl BitRangeMut for BitField2 { fn set_bit_range(&mut self, _msb: usize, _lsb: usize, _value: u8) {} } // Make sure Debug wasn't implemented by implementing it. impl Debug for BitField2 { fn fmt(&self, _: &mut Formatter) -> Result<(), Error> { unimplemented!() } } // Check that we can put `impl Debug` before `no default BitRange` bitfield! { pub struct BitField3(u16); impl Debug; no default BitRange; u8; field1, set_field1: 10, 0; pub field2, _ : 12, 3; field3, set_field3: 0; } impl BitRange for BitField3 { fn bit_range(&self, _msb: usize, _lsb: usize) -> u8 { 0 } } impl BitRangeMut for BitField3 { fn set_bit_range(&mut self, _msb: usize, _lsb: usize, _value: u8) {} } bitfield! { #[derive(Eq, PartialEq)] pub struct BitField4([u16]); no default BitRange; impl Debug; u8; field1, set_field1: 10, 0; pub field2, _ : 12, 3; field3, set_field3: 2; } impl BitRange for BitField4 { fn bit_range(&self, _msb: usize, _lsb: usize) -> u8 { 0 } } impl BitRangeMut for BitField4 { fn set_bit_range(&mut self, _msb: usize, _lsb: usize, _value: u8) {} } bitfield! { pub struct BitField5([u16]); no default BitRange; u8; field1, set_field1: 10, 0; pub field2, _ : 12, 3; field3, set_field3: 0; } impl BitRange for BitField5 { fn bit_range(&self, _msb: usize, _lsb: usize) -> u8 { 0 } } impl BitRangeMut for BitField5 { fn set_bit_range(&mut self, _msb: usize, _lsb: usize, _value: u8) {} } // Make sure Debug wasn't implemented by implementing it. impl Debug for BitField5 { fn fmt(&self, _: &mut Formatter) -> Result<(), Error> { unimplemented!() } } // Check that we can put `impl Debug` before `no default BitRange` bitfield! { pub struct BitField6([u16]); impl Debug; no default BitRange; u8; field1, set_field1: 10, 0; pub field2, _ : 12, 3; field3, set_field3: 0; } impl BitRange for BitField6 { fn bit_range(&self, _msb: usize, _lsb: usize) -> u8 { 0 } } impl BitRangeMut for BitField6 { fn set_bit_range(&mut self, _msb: usize, _lsb: usize, _value: u8) {} } bitfield! { #[derive(Eq, PartialEq)] pub struct BitField7(MSB0 [u16]); no default BitRange; impl Debug; u8; field1, set_field1: 10, 0; pub field2, _ : 12, 3; field3, set_field3: 2; } impl BitRange for BitField7 { fn bit_range(&self, _msb: usize, _lsb: usize) -> u8 { 0 } } impl BitRangeMut for BitField7 { fn set_bit_range(&mut self, _msb: usize, _lsb: usize, _value: u8) {} } bitfield! { pub struct BitField8(MSB0 [u16]); no default BitRange; u8; field1, set_field1: 10, 0; pub field2, _ : 12, 3; field3, set_field3: 0; } impl BitRange for BitField8 { fn bit_range(&self, _msb: usize, _lsb: usize) -> u8 { 0 } } impl BitRangeMut for BitField8 { fn set_bit_range(&mut self, _msb: usize, _lsb: usize, _value: u8) {} } // Make sure Debug wasn't implemented by implementing it. impl Debug for BitField8 { fn fmt(&self, _: &mut Formatter) -> Result<(), Error> { unimplemented!() } } // Check that we can put `impl Debug` before `no default BitRange` bitfield! { pub struct BitField9([u16]); impl Debug; no default BitRange; u8; field1, set_field1: 10, 0; pub field2, _ : 12, 3; field3, set_field3: 0; } impl BitRange for BitField9 { fn bit_range(&self, _msb: usize, _lsb: usize) -> u8 { 0 } } impl BitRangeMut for BitField9 { fn set_bit_range(&mut self, _msb: usize, _lsb: usize, _value: u8) {} } #[test] fn test_debug_is_implemented_with_no_default_bitrange() { format!("{:?}", BitField1(0)); format!("{:?}", BitField3(0)); format!("{:?}", BitField4([0; 1])); format!("{:?}", BitField6([0; 1])); format!("{:?}", BitField7([0; 1])); format!("{:?}", BitField9([0; 1])); } #[test] fn masks() { assert_eq!(FooBar::I128_MASK, 0b111111110i128); assert_eq!(FooBar::U128_MASK, 0b111111110u128); assert_eq!(FooBar::SETTER_MASK, 0b11100u32); assert_eq!(FooBar::GETTER_MASK, 0b1110u32); assert_eq!(FooBar::PUB_SETTER_MASK, 0b11100u32); assert_eq!(FooBar::PUB_GETTER_MASK, 0b1110u32); assert_eq!(FooBar::SINGLE_BIT_MASK, 1 << 3); assert_eq!(FooBar::PUB_MASK, 1 << 31); } }