summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorInna Palant <ipalant@google.com>2024-03-22 03:01:41 +0000
committerInna Palant <ipalant@google.com>2024-03-22 03:01:41 +0000
commit3afddda14faa778851cc456df1f3b0505e519d0f (patch)
tree401a79a5f81a945cb701767d6262c5576b5910af
parentb93bab535ded25865413e00068b26bb01334cc85 (diff)
parentac9261cc7b17552ff974957f4c6007bc7021b14c (diff)
downloadbit_field-3afddda14faa778851cc456df1f3b0505e519d0f.tar.gz
Merge remote-tracking branch 'origin/upstream'
Import b/326114231
-rw-r--r--.cargo_vcs_info.json6
-rw-r--r--.gitignore2
-rw-r--r--.travis.yml16
-rw-r--r--Cargo.toml36
-rw-r--r--Cargo.toml.orig19
-rw-r--r--Changelog.md37
-rw-r--r--LICENSE225
-rw-r--r--LICENSE-APACHE201
-rw-r--r--LICENSE-MIT21
-rw-r--r--METADATA20
-rw-r--r--MODULE_LICENSE_APACHE20
-rw-r--r--OWNERS1
-rw-r--r--README.md31
-rw-r--r--benches/bench.rs233
-rw-r--r--src/lib.rs374
-rw-r--r--src/tests.rs450
16 files changed, 1672 insertions, 0 deletions
diff --git a/.cargo_vcs_info.json b/.cargo_vcs_info.json
new file mode 100644
index 0000000..3268818
--- /dev/null
+++ b/.cargo_vcs_info.json
@@ -0,0 +1,6 @@
+{
+ "git": {
+ "sha1": "9a5f9ed6216537947ca82ec2d3ecf3dcbf157cec"
+ },
+ "path_in_vcs": ""
+} \ No newline at end of file
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..a9d37c5
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
+target
+Cargo.lock
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 0000000..c2628e3
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,16 @@
+language: rust
+rust:
+ - stable
+ - beta
+ - nightly
+
+cache: cargo
+
+sudo: false
+
+script:
+ - cargo build --verbose --all
+ - cargo test --verbose --all
+ - if [ "${TRAVIS_RUST_VERSION}" = "nightly" ]; then
+ cargo bench --verbose --all;
+ fi
diff --git a/Cargo.toml b/Cargo.toml
new file mode 100644
index 0000000..b52a63e
--- /dev/null
+++ b/Cargo.toml
@@ -0,0 +1,36 @@
+# 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 = "bit_field"
+version = "0.10.2"
+authors = ["Philipp Oppermann <dev@phil-opp.com>"]
+description = "Simple bit field trait providing get_bit, get_bits, set_bit, and set_bits methods for Rust's integral types."
+documentation = "https://docs.rs/bit_field"
+readme = "README.md"
+keywords = ["no_std"]
+license = "Apache-2.0/MIT"
+repository = "https://github.com/phil-opp/rust-bit-field"
+
+[package.metadata.release]
+dev-version = false
+pre-release-commit-message = "Release version {{version}}"
+
+[[package.metadata.release.pre-release-replacements]]
+file = "Changelog.md"
+search = "## Unreleased"
+replace = """
+## Unreleased
+
+# {{version}} – {{date}}"""
+exactly = 1
+
+[dependencies]
diff --git a/Cargo.toml.orig b/Cargo.toml.orig
new file mode 100644
index 0000000..cb6a5ee
--- /dev/null
+++ b/Cargo.toml.orig
@@ -0,0 +1,19 @@
+[package]
+name = "bit_field"
+version = "0.10.2"
+authors = ["Philipp Oppermann <dev@phil-opp.com>"]
+license = "Apache-2.0/MIT"
+
+description = "Simple bit field trait providing get_bit, get_bits, set_bit, and set_bits methods for Rust's integral types."
+keywords = ["no_std"]
+repository = "https://github.com/phil-opp/rust-bit-field"
+documentation = "https://docs.rs/bit_field"
+
+[dependencies]
+
+[package.metadata.release]
+dev-version = false
+pre-release-replacements = [
+ { file = "Changelog.md", search = "## Unreleased", replace = "## Unreleased\n\n# {{version}} – {{date}}", exactly = 1 },
+]
+pre-release-commit-message = "Release version {{version}}"
diff --git a/Changelog.md b/Changelog.md
new file mode 100644
index 0000000..ae3f483
--- /dev/null
+++ b/Changelog.md
@@ -0,0 +1,37 @@
+## Unreleased
+
+# 0.10.2 – 2023-02-25
+
+- Add `#[track_caller]` to methods ([#27](https://github.com/phil-opp/rust-bit-field/pull/27))
+
+# 0.10.1 – 2020-08-23
+
+- Added bit manipulation functions for 128-bit integers ([#24](https://github.com/phil-opp/rust-bit-field/pull/24))
+
+## [0.10.0] - 2019-05-03
+### Added
+ - Support all range types (`Range`, `RangeInclusive`, `RangeFrom`, …) for `get_bits` and `set_bits` methods ([#22](https://github.com/phil-opp/rust-bit-field/pull/22))
+
+### Changed
+ - **Breaking**: `BitField` trait now has a `BIT_LENGTH` associated const instead of a `bit_length` associated function.
+ - `BitField` and `BitArray` methods are now inlined which causes much higher performance.
+
+## [0.9.0] - 2017-10-15
+### Changed
+ - Bit indexes in `BitField` is now `usize` instead of `u8`.
+
+## [0.8.0] - 2017-07-16
+### Added
+ - `BitArray` trait to make bit indexing possible with slices.
+### Changed
+ - `bit_length` in `BitField` is now an associated function instead of a method (`bit_length()` instead of `bit_length(&self)`)
+
+## [0.7.0] - 2017-01-16
+### Added
+ - `BitField` was also implemented for: `i8`, `i16`, `i32`, `i64` and `isize`
+### Changed
+ - `length()` method in `BitField` is now called `bit_length()`
+ - `get_range()` method in `BitField` is now called `get_bits()`
+ - `set_range()` method in `BitField` is now called `set_bits()`
+### Removed
+ - `zero()` and `one()` constructor was removed from `BitField` trait.
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..6f34b16
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,225 @@
+ 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.
+
+-----
+
+The MIT License (MIT)
+
+Copyright (c) 2016 Philipp Oppermann
+
+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.
diff --git a/LICENSE-APACHE b/LICENSE-APACHE
new file mode 100644
index 0000000..8dada3e
--- /dev/null
+++ b/LICENSE-APACHE
@@ -0,0 +1,201 @@
+ 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.
diff --git a/LICENSE-MIT b/LICENSE-MIT
new file mode 100644
index 0000000..260d0de
--- /dev/null
+++ b/LICENSE-MIT
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2016 Philipp Oppermann
+
+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.
diff --git a/METADATA b/METADATA
new file mode 100644
index 0000000..81a2f8e
--- /dev/null
+++ b/METADATA
@@ -0,0 +1,20 @@
+name: "bit_field"
+description: "Simple bit field trait providing get_bit, get_bits, set_bit, and set_bits methods for Rust\'s integral types."
+third_party {
+ identifier {
+ type: "crates.io"
+ value: "https://crates.io/crates/bit_field"
+ }
+ identifier {
+ type: "Archive"
+ value: "https://static.crates.io/crates/bit_field/bit_field-0.10.2.crate"
+ }
+ version: "0.10.2"
+ # Dual-licensed, using the least restrictive per go/thirdpartylicenses#same.
+ license_type: NOTICE
+ last_upgrade_date {
+ year: 2024
+ month: 2
+ day: 26
+ }
+}
diff --git a/MODULE_LICENSE_APACHE2 b/MODULE_LICENSE_APACHE2
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/MODULE_LICENSE_APACHE2
diff --git a/OWNERS b/OWNERS
new file mode 100644
index 0000000..5a2b844
--- /dev/null
+++ b/OWNERS
@@ -0,0 +1 @@
+include platform/prebuilts/rust:main:/OWNERS
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..ef47b9e
--- /dev/null
+++ b/README.md
@@ -0,0 +1,31 @@
+# bit_field
+
+A simple crate which provides the `BitField` trait, which provides methods for operating on individual bits and ranges
+of bits on Rust's integral types.
+
+## Documentation
+Documentation is available on [docs.rs](https://docs.rs/bit_field)
+
+## Usage
+```TOML
+[dependencies]
+bit_field = "0.10.1"
+```
+
+## Example
+```rust
+extern crate bit_field;
+use bit_field::BitField;
+
+let mut x: u8 = 0;
+
+x.set_bit(7, true);
+assert_eq!(x, 0b1000_0000);
+
+x.set_bits(0..4, 0b1001);
+assert_eq!(x, 0b1000_1001);
+
+```
+
+## License
+This crate is dual-licensed under MIT or the Apache License (Version 2.0). See LICENSE-APACHE and LICENSE-MIT for details.
diff --git a/benches/bench.rs b/benches/bench.rs
new file mode 100644
index 0000000..676461b
--- /dev/null
+++ b/benches/bench.rs
@@ -0,0 +1,233 @@
+#![feature(test)]
+
+extern crate bit_field;
+
+use bit_field::*;
+
+pub trait BitOper {
+ const BIT_LEN: usize;
+ fn get_b(&self, idx: usize) -> bool;
+ fn set_b(&mut self, idx: usize, val: bool);
+ fn toggle(&mut self, idx: usize);
+}
+
+pub trait BitArrayOper<T: BitOper> {
+ fn get_blen(&self) -> usize;
+ fn get_b(&self, idx: usize) -> bool;
+ fn set_b(&mut self, idx: usize, val: bool);
+ fn toggle(&mut self, idx: usize);
+}
+
+impl BitOper for u8 {
+ const BIT_LEN: usize = std::mem::size_of::<Self>() as usize * 8;
+
+ fn set_b(&mut self, idx: usize, val: bool) {
+ assert!(idx < Self::BIT_LEN);
+ if val {
+ *self |= 1 << idx;
+ } else {
+ *self &= !(1 << idx);
+ }
+ }
+
+ fn get_b(&self, idx: usize) -> bool {
+ assert!(idx < Self::BIT_LEN);
+ (self & 1 << idx) != 0
+ }
+
+ fn toggle(&mut self, idx: usize) {
+ assert!(idx < Self::BIT_LEN);
+ *self ^= 1 << idx;
+ }
+}
+
+impl BitOper for u32 {
+ const BIT_LEN: usize = std::mem::size_of::<Self>() as usize * 8;
+ fn set_b(&mut self, idx: usize, val: bool) {
+ assert!(idx < Self::BIT_LEN);
+ if val {
+ *self |= 1 << idx;
+ } else {
+ *self &= !(1 << idx);
+ }
+ }
+
+ fn get_b(&self, idx: usize) -> bool {
+ assert!(idx < Self::BIT_LEN);
+ (self & 1 << idx) != 0
+ }
+
+ fn toggle(&mut self, idx: usize) {
+ assert!(idx < Self::BIT_LEN);
+ *self ^= 1 << idx;
+ }
+}
+
+impl BitOper for u64 {
+ const BIT_LEN: usize = std::mem::size_of::<Self>() as usize * 8;
+ fn set_b(&mut self, idx: usize, val: bool) {
+ assert!(idx < Self::BIT_LEN);
+ if val {
+ *self |= 1 << idx;
+ } else {
+ *self &= !(1 << idx);
+ }
+ }
+
+ fn get_b(&self, idx: usize) -> bool {
+ assert!(idx < Self::BIT_LEN);
+ (self & 1 << idx) != 0
+ }
+
+ fn toggle(&mut self, idx: usize) {
+ assert!(idx < Self::BIT_LEN);
+ *self ^= 1 << idx;
+ }
+}
+
+impl<T: BitOper> BitArrayOper<T> for [T] {
+ fn get_blen(&self) -> usize {
+ self.len() * T::BIT_LEN
+ }
+
+ fn get_b(&self, idx: usize) -> bool {
+ self[idx / T::BIT_LEN].get_b(idx % T::BIT_LEN)
+ }
+
+ fn set_b(&mut self, idx: usize, val: bool) {
+ self[idx / T::BIT_LEN].set_b(idx % T::BIT_LEN, val);
+ }
+
+ fn toggle(&mut self, idx: usize) {
+ self[idx / T::BIT_LEN].toggle(idx % T::BIT_LEN);
+ }
+}
+
+extern crate test;
+
+use test::Bencher;
+
+const LEN: usize = 256;
+
+fn set_bitfield<T: BitField>(v: &mut Vec<T>) {
+ for i in 0..v.len() * T::BIT_LENGTH {
+ v.as_mut_slice().set_bit(i, true);;
+ }
+}
+
+fn get_bitfield<T: BitField>(v: &Vec<T>) {
+ for i in 0..v.len() * T::BIT_LENGTH {
+ let _b = v.as_slice().get_bit(i);
+ }
+}
+
+fn set_trivial<T: BitOper>(v: &mut Vec<T>) {
+ for i in 0..v.len() * T::BIT_LEN {
+ v.set_b(i, true);
+ }
+}
+
+fn get_trivial<T: BitOper>(v: &Vec<T>) {
+ for i in 0..v.len() * T::BIT_LEN {
+ let _b = v.get_b(i);
+ }
+}
+
+#[bench]
+fn u8_set_bitfield(b: &mut Bencher) {
+ let mut v = vec![0u8; LEN];
+ b.iter(|| {
+ set_bitfield(&mut v);
+ });
+}
+
+#[bench]
+fn u8_set_trivial(b: &mut Bencher) {
+ let mut v = vec![0u8; LEN];
+
+ b.iter(|| {
+ set_trivial(&mut v);
+ });
+}
+
+#[bench]
+fn u8_get_bitfield(b: &mut Bencher) {
+ let v = vec![1u8; LEN];
+ b.iter(|| {
+ get_bitfield(&v);
+ });
+}
+
+#[bench]
+fn u8_get_trivial(b: &mut Bencher) {
+ let v = vec![1u8; LEN];
+ b.iter(|| {
+ get_trivial(&v);
+ });
+}
+
+#[bench]
+fn u32_set_bitfield(b: &mut Bencher) {
+ let mut v = vec![0u32; LEN];
+ b.iter(|| {
+ set_bitfield(&mut v);
+ });
+}
+
+#[bench]
+fn u32_set_trivial(b: &mut Bencher) {
+ let mut v = vec![0u32; LEN];
+
+ b.iter(|| {
+ set_trivial(&mut v);
+ });
+}
+
+#[bench]
+fn u32_get_bitfield(b: &mut Bencher) {
+ let v = vec![1u32; LEN];
+ b.iter(|| {
+ get_bitfield(&v);
+ });
+}
+
+#[bench]
+fn u32_get_trivial(b: &mut Bencher) {
+ let v = vec![1u32; LEN];
+ b.iter(|| {
+ get_trivial(&v);
+ });
+}
+
+#[bench]
+fn u64_set_bitfield(b: &mut Bencher) {
+ let mut v = vec![0u64; LEN];
+ b.iter(|| {
+ set_bitfield(&mut v);
+ });
+}
+
+#[bench]
+fn u64_set_trivial(b: &mut Bencher) {
+ let mut v = vec![0u64; LEN];
+
+ b.iter(|| {
+ set_trivial(&mut v);
+ });
+}
+
+#[bench]
+fn u64_get_bitfield(b: &mut Bencher) {
+ let v = vec![1u64; LEN];
+ b.iter(|| {
+ get_bitfield(&v);
+ });
+}
+
+#[bench]
+fn u64_get_trivial(b: &mut Bencher) {
+ let v = vec![1u64; LEN];
+ b.iter(|| {
+ get_trivial(&v);
+ });
+}
diff --git a/src/lib.rs b/src/lib.rs
new file mode 100644
index 0000000..21e682b
--- /dev/null
+++ b/src/lib.rs
@@ -0,0 +1,374 @@
+//! Provides the abstraction of a bit field, which allows for bit-level update and retrieval
+//! operations.
+
+#![no_std]
+
+#[cfg(test)]
+mod tests;
+
+use core::ops::{Bound, Range, RangeBounds};
+
+/// A generic trait which provides methods for extracting and setting specific bits or ranges of
+/// bits.
+pub trait BitField {
+ /// The number of bits in this bit field.
+ ///
+ /// ```rust
+ /// use bit_field::BitField;
+ ///
+ /// assert_eq!(u32::BIT_LENGTH, 32);
+ /// assert_eq!(u64::BIT_LENGTH, 64);
+ /// ```
+ const BIT_LENGTH: usize;
+
+ /// Obtains the bit at the index `bit`; note that index 0 is the least significant bit, while
+ /// index `length() - 1` is the most significant bit.
+ ///
+ /// ```rust
+ /// use bit_field::BitField;
+ ///
+ /// let value: u32 = 0b110101;
+ ///
+ /// assert_eq!(value.get_bit(1), false);
+ /// assert_eq!(value.get_bit(2), true);
+ /// ```
+ ///
+ /// ## Panics
+ ///
+ /// This method will panic if the bit index is out of bounds of the bit field.
+ fn get_bit(&self, bit: usize) -> bool;
+
+ /// Obtains the range of bits specified by `range`; note that index 0 is the least significant
+ /// bit, while index `length() - 1` is the most significant bit.
+ ///
+ /// ```rust
+ /// use bit_field::BitField;
+ ///
+ /// let value: u32 = 0b110101;
+ ///
+ /// assert_eq!(value.get_bits(0..3), 0b101);
+ /// assert_eq!(value.get_bits(2..6), 0b1101);
+ /// assert_eq!(value.get_bits(..), 0b110101);
+ /// assert_eq!(value.get_bits(3..=3), value.get_bit(3) as u32);
+ /// ```
+ ///
+ /// ## Panics
+ ///
+ /// This method will panic if the start or end indexes of the range are out of bounds of the
+ /// bit field.
+ fn get_bits<T: RangeBounds<usize>>(&self, range: T) -> Self;
+
+ /// Sets the bit at the index `bit` to the value `value` (where true means a value of '1' and
+ /// false means a value of '0'); note that index 0 is the least significant bit, while index
+ /// `length() - 1` is the most significant bit.
+ ///
+ /// ```rust
+ /// use bit_field::BitField;
+ ///
+ /// let mut value = 0u32;
+ ///
+ /// value.set_bit(1, true);
+ /// assert_eq!(value, 2u32);
+ ///
+ /// value.set_bit(3, true);
+ /// assert_eq!(value, 10u32);
+ ///
+ /// value.set_bit(1, false);
+ /// assert_eq!(value, 8u32);
+ /// ```
+ ///
+ /// ## Panics
+ ///
+ /// This method will panic if the bit index is out of the bounds of the bit field.
+ fn set_bit(&mut self, bit: usize, value: bool) -> &mut Self;
+
+ /// Sets the range of bits defined by the range `range` to the lower bits of `value`; to be
+ /// specific, if the range is N bits long, the N lower bits of `value` will be used; if any of
+ /// the other bits in `value` are set to 1, this function will panic.
+ ///
+ /// ```rust
+ /// use bit_field::BitField;
+ ///
+ /// let mut value = 0u32;
+ ///
+ /// value.set_bits(0..2, 0b11);
+ /// assert_eq!(value, 0b11);
+ ///
+ /// value.set_bits(2..=3, 0b11);
+ /// assert_eq!(value, 0b1111);
+ ///
+ /// value.set_bits(..4, 0b1010);
+ /// assert_eq!(value, 0b1010);
+ /// ```
+ ///
+ /// ## Panics
+ ///
+ /// This method will panic if the range is out of bounds of the bit field, or if there are `1`s
+ /// not in the lower N bits of `value`.
+ fn set_bits<T: RangeBounds<usize>>(&mut self, range: T, value: Self) -> &mut Self;
+}
+
+pub trait BitArray<T: BitField> {
+ /// Returns the length, eg number of bits, in this bit array.
+ ///
+ /// ```rust
+ /// use bit_field::BitArray;
+ ///
+ /// assert_eq!([0u8, 4u8, 8u8].bit_length(), 24);
+ /// assert_eq!([0u32, 5u32].bit_length(), 64);
+ /// ```
+ fn bit_length(&self) -> usize;
+
+ /// Obtains the bit at the index `bit`; note that index 0 is the least significant bit, while
+ /// index `length() - 1` is the most significant bit.
+ ///
+ /// ```rust
+ /// use bit_field::BitArray;
+ ///
+ /// let value: [u32; 1] = [0b110101];
+ ///
+ /// assert_eq!(value.get_bit(1), false);
+ /// assert_eq!(value.get_bit(2), true);
+ /// ```
+ ///
+ /// ## Panics
+ ///
+ /// This method will panic if the bit index is out of bounds of the bit array.
+ fn get_bit(&self, bit: usize) -> bool;
+
+ /// Obtains the range of bits specified by `range`; note that index 0 is the least significant
+ /// bit, while index `length() - 1` is the most significant bit.
+ ///
+ /// ```rust
+ /// use bit_field::BitArray;
+ ///
+ /// let value: [u32; 2] = [0b110101, 0b11];
+ ///
+ /// assert_eq!(value.get_bits(0..3), 0b101);
+ /// assert_eq!(value.get_bits(..6), 0b110101);
+ /// assert_eq!(value.get_bits(31..33), 0b10);
+ /// assert_eq!(value.get_bits(5..=32), 0b1_0000_0000_0000_0000_0000_0000_001);
+ /// assert_eq!(value.get_bits(34..), 0);
+ /// ```
+ ///
+ /// ## Panics
+ ///
+ /// This method will panic if the start or end indexes of the range are out of bounds of the
+ /// bit array, or if the range can't be contained by the bit field T.
+ fn get_bits<U: RangeBounds<usize>>(&self, range: U) -> T;
+
+ /// Sets the bit at the index `bit` to the value `value` (where true means a value of '1' and
+ /// false means a value of '0'); note that index 0 is the least significant bit, while index
+ /// `length() - 1` is the most significant bit.
+ ///
+ /// ```rust
+ /// use bit_field::BitArray;
+ ///
+ /// let mut value = [0u32];
+ ///
+ /// value.set_bit(1, true);
+ /// assert_eq!(value, [2u32]);
+ ///
+ /// value.set_bit(3, true);
+ /// assert_eq!(value, [10u32]);
+ ///
+ /// value.set_bit(1, false);
+ /// assert_eq!(value, [8u32]);
+ /// ```
+ ///
+ /// ## Panics
+ ///
+ /// This method will panic if the bit index is out of the bounds of the bit array.
+ fn set_bit(&mut self, bit: usize, value: bool);
+
+ /// Sets the range of bits defined by the range `range` to the lower bits of `value`; to be
+ /// specific, if the range is N bits long, the N lower bits of `value` will be used; if any of
+ /// the other bits in `value` are set to 1, this function will panic.
+ ///
+ /// ```rust
+ /// use bit_field::BitArray;
+ ///
+ /// let mut value = [0u32, 0u32];
+ ///
+ /// value.set_bits(0..2, 0b11);
+ /// assert_eq!(value, [0b11, 0u32]);
+ ///
+ /// value.set_bits(31..35, 0b1010);
+ /// assert_eq!(value, [0x0003, 0b101]);
+ /// ```
+ ///
+ /// ## Panics
+ ///
+ /// This method will panic if the range is out of bounds of the bit array,
+ /// if the range can't be contained by the bit field T, or if there are `1`s
+ /// not in the lower N bits of `value`.
+ fn set_bits<U: RangeBounds<usize>>(&mut self, range: U, value: T);
+}
+
+/// An internal macro used for implementing BitField on the standard integral types.
+macro_rules! bitfield_numeric_impl {
+ ($($t:ty)*) => ($(
+ impl BitField for $t {
+ const BIT_LENGTH: usize = ::core::mem::size_of::<Self>() as usize * 8;
+
+ #[track_caller]
+ #[inline]
+ fn get_bit(&self, bit: usize) -> bool {
+ assert!(bit < Self::BIT_LENGTH);
+
+ (*self & (1 << bit)) != 0
+ }
+
+ #[track_caller]
+ #[inline]
+ fn get_bits<T: RangeBounds<usize>>(&self, range: T) -> Self {
+ let range = to_regular_range(&range, Self::BIT_LENGTH);
+
+ assert!(range.start < Self::BIT_LENGTH);
+ assert!(range.end <= Self::BIT_LENGTH);
+ assert!(range.start < range.end);
+
+ // shift away high bits
+ let bits = *self << (Self::BIT_LENGTH - range.end) >> (Self::BIT_LENGTH - range.end);
+
+ // shift away low bits
+ bits >> range.start
+ }
+
+ #[track_caller]
+ #[inline]
+ fn set_bit(&mut self, bit: usize, value: bool) -> &mut Self {
+ assert!(bit < Self::BIT_LENGTH);
+
+ if value {
+ *self |= 1 << bit;
+ } else {
+ *self &= !(1 << bit);
+ }
+
+ self
+ }
+
+ #[track_caller]
+ #[inline]
+ fn set_bits<T: RangeBounds<usize>>(&mut self, range: T, value: Self) -> &mut Self {
+ let range = to_regular_range(&range, Self::BIT_LENGTH);
+
+ assert!(range.start < Self::BIT_LENGTH);
+ assert!(range.end <= Self::BIT_LENGTH);
+ assert!(range.start < range.end);
+ assert!(value << (Self::BIT_LENGTH - (range.end - range.start)) >>
+ (Self::BIT_LENGTH - (range.end - range.start)) == value,
+ "value does not fit into bit range");
+
+ let bitmask: Self = !(!0 << (Self::BIT_LENGTH - range.end) >>
+ (Self::BIT_LENGTH - range.end) >>
+ range.start << range.start);
+
+ // set bits
+ *self = (*self & bitmask) | (value << range.start);
+
+ self
+ }
+ }
+ )*)
+}
+
+bitfield_numeric_impl! { u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize }
+
+impl<T: BitField> BitArray<T> for [T] {
+ #[inline]
+ fn bit_length(&self) -> usize {
+ self.len() * T::BIT_LENGTH
+ }
+
+ #[track_caller]
+ #[inline]
+ fn get_bit(&self, bit: usize) -> bool {
+ let slice_index = bit / T::BIT_LENGTH;
+ let bit_index = bit % T::BIT_LENGTH;
+ self[slice_index].get_bit(bit_index)
+ }
+
+ #[track_caller]
+ #[inline]
+ fn get_bits<U: RangeBounds<usize>>(&self, range: U) -> T {
+ let range = to_regular_range(&range, self.bit_length());
+
+ assert!(range.len() <= T::BIT_LENGTH);
+
+ let slice_start = range.start / T::BIT_LENGTH;
+ let slice_end = range.end / T::BIT_LENGTH;
+ let bit_start = range.start % T::BIT_LENGTH;
+ let bit_end = range.end % T::BIT_LENGTH;
+ let len = range.len();
+
+ assert!(slice_end - slice_start <= 1);
+
+ if slice_start == slice_end {
+ self[slice_start].get_bits(bit_start..bit_end)
+ } else if bit_end == 0 {
+ self[slice_start].get_bits(bit_start..T::BIT_LENGTH)
+ } else {
+ let mut ret = self[slice_start].get_bits(bit_start..T::BIT_LENGTH);
+ ret.set_bits(
+ (T::BIT_LENGTH - bit_start)..len,
+ self[slice_end].get_bits(0..bit_end),
+ );
+ ret
+ }
+ }
+
+ #[track_caller]
+ #[inline]
+ fn set_bit(&mut self, bit: usize, value: bool) {
+ let slice_index = bit / T::BIT_LENGTH;
+ let bit_index = bit % T::BIT_LENGTH;
+ self[slice_index].set_bit(bit_index, value);
+ }
+
+ #[track_caller]
+ #[inline]
+ fn set_bits<U: RangeBounds<usize>>(&mut self, range: U, value: T) {
+ let range = to_regular_range(&range, self.bit_length());
+
+ assert!(range.len() <= T::BIT_LENGTH);
+
+ let slice_start = range.start / T::BIT_LENGTH;
+ let slice_end = range.end / T::BIT_LENGTH;
+ let bit_start = range.start % T::BIT_LENGTH;
+ let bit_end = range.end % T::BIT_LENGTH;
+
+ assert!(slice_end - slice_start <= 1);
+
+ if slice_start == slice_end {
+ self[slice_start].set_bits(bit_start..bit_end, value);
+ } else if bit_end == 0 {
+ self[slice_start].set_bits(bit_start..T::BIT_LENGTH, value);
+ } else {
+ self[slice_start].set_bits(
+ bit_start..T::BIT_LENGTH,
+ value.get_bits(0..T::BIT_LENGTH - bit_start),
+ );
+ self[slice_end].set_bits(
+ 0..bit_end,
+ value.get_bits(T::BIT_LENGTH - bit_start..T::BIT_LENGTH),
+ );
+ }
+ }
+}
+
+fn to_regular_range<T: RangeBounds<usize>>(generic_rage: &T, bit_length: usize) -> Range<usize> {
+ let start = match generic_rage.start_bound() {
+ Bound::Excluded(&value) => value + 1,
+ Bound::Included(&value) => value,
+ Bound::Unbounded => 0,
+ };
+ let end = match generic_rage.end_bound() {
+ Bound::Excluded(&value) => value,
+ Bound::Included(&value) => value + 1,
+ Bound::Unbounded => bit_length,
+ };
+
+ start..end
+}
diff --git a/src/tests.rs b/src/tests.rs
new file mode 100644
index 0000000..dd470e8
--- /dev/null
+++ b/src/tests.rs
@@ -0,0 +1,450 @@
+use BitArray;
+use BitField;
+
+#[test]
+fn test_integer_bit_lengths() {
+ assert_eq!(u8::BIT_LENGTH, 8);
+ assert_eq!(u16::BIT_LENGTH, 16);
+ assert_eq!(u32::BIT_LENGTH, 32);
+ assert_eq!(u64::BIT_LENGTH, 64);
+ assert_eq!(u128::BIT_LENGTH, 128);
+
+ assert_eq!(i8::BIT_LENGTH, 8);
+ assert_eq!(i16::BIT_LENGTH, 16);
+ assert_eq!(i32::BIT_LENGTH, 32);
+ assert_eq!(i64::BIT_LENGTH, 64);
+ assert_eq!(i128::BIT_LENGTH, 128);
+}
+
+#[test]
+fn test_set_reset_u8() {
+ let mut field = 0b11110010u8;
+ let mut bit_i = |i| {
+ field.set_bit(i, true);
+ assert_eq!(field.get_bit(i), true);
+ field.set_bit(i, false);
+ assert_eq!(field.get_bit(i), false);
+ field.set_bit(i, true);
+ assert_eq!(field.get_bit(i), true);
+ };
+ for i in 0..8 {
+ bit_i(i);
+ }
+}
+
+#[test]
+fn test_set_reset_u16() {
+ let mut field = 0b1111001010010110u16;
+ let mut bit_i = |i| {
+ field.set_bit(i, true);
+ assert_eq!(field.get_bit(i), true);
+ field.set_bit(i, false);
+ assert_eq!(field.get_bit(i), false);
+ field.set_bit(i, true);
+ assert_eq!(field.get_bit(i), true);
+ };
+ for i in 0..16 {
+ bit_i(i);
+ }
+}
+
+#[test]
+fn test_read_u32() {
+ let field = 0b1111111111010110u32;
+ assert_eq!(field.get_bit(0), false);
+ assert_eq!(field.get_bit(1), true);
+ assert_eq!(field.get_bit(2), true);
+ assert_eq!(field.get_bit(3), false);
+ assert_eq!(field.get_bit(4), true);
+ assert_eq!(field.get_bit(5), false);
+ for i in 6..16 {
+ assert_eq!(field.get_bit(i), true);
+ }
+ for i in 16..32 {
+ assert_eq!(field.get_bit(i), false);
+ }
+
+ assert_eq!(field.get_bits(16..), 0);
+ assert_eq!(field.get_bits(16..32), 0);
+ assert_eq!(field.get_bits(16..=31), 0);
+
+ assert_eq!(field.get_bits(6..16), 0b1111111111);
+ assert_eq!(field.get_bits(6..=15), 0b1111111111);
+
+ assert_eq!(field.get_bits(..6), 0b010110);
+ assert_eq!(field.get_bits(0..6), 0b010110);
+ assert_eq!(field.get_bits(0..=5), 0b010110);
+
+ assert_eq!(field.get_bits(..10), 0b1111010110);
+ assert_eq!(field.get_bits(0..10), 0b1111010110);
+ assert_eq!(field.get_bits(0..=9), 0b1111010110);
+
+ assert_eq!(field.get_bits(5..12), 0b1111110);
+ assert_eq!(field.get_bits(5..=11), 0b1111110);
+}
+
+#[test]
+fn test_set_reset_u32() {
+ let mut field = 0b1111111111010110u32;
+ let mut bit_i = |i| {
+ field.set_bit(i, true);
+ assert_eq!(field.get_bit(i), true);
+ field.set_bit(i, false);
+ assert_eq!(field.get_bit(i), false);
+ field.set_bit(i, true);
+ assert_eq!(field.get_bit(i), true);
+ };
+ for i in 0..32 {
+ bit_i(i);
+ }
+}
+
+#[test]
+fn test_set_range_u32() {
+ let mut field = 0b1111111111010110u32;
+ field.set_bits(10..15, 0b00000);
+ assert_eq!(field.get_bits(10..15), 0b00000);
+ assert_eq!(field.get_bits(10..=14), 0b00000);
+ field.set_bits(10..15, 0b10101);
+ assert_eq!(field.get_bits(10..15), 0b10101);
+ assert_eq!(field.get_bits(10..=14), 0b10101);
+ field.set_bits(10..15, 0b01010);
+ assert_eq!(field.get_bits(10..15), 0b01010);
+ assert_eq!(field.get_bits(10..=14), 0b01010);
+ field.set_bits(10..15, 0b11111);
+ assert_eq!(field.get_bits(10..15), 0b11111);
+ assert_eq!(field.get_bits(10..=14), 0b11111);
+
+ field.set_bits(10..=14, 0b00000);
+ assert_eq!(field.get_bits(10..15), 0b00000);
+ assert_eq!(field.get_bits(10..=14), 0b00000);
+ field.set_bits(10..=14, 0b10101);
+ assert_eq!(field.get_bits(10..15), 0b10101);
+ assert_eq!(field.get_bits(10..=14), 0b10101);
+ field.set_bits(10..=14, 0b01010);
+ assert_eq!(field.get_bits(10..15), 0b01010);
+ assert_eq!(field.get_bits(10..=14), 0b01010);
+ field.set_bits(10..=14, 0b11111);
+ assert_eq!(field.get_bits(10..15), 0b11111);
+ assert_eq!(field.get_bits(10..=14), 0b11111);
+
+ field.set_bits(0..16, 0xdead);
+ field.set_bits(14..32, 0xbeaf);
+ assert_eq!(field.get_bits(0..16), 0xdead);
+ assert_eq!(field.get_bits(14..32), 0xbeaf);
+
+ field.set_bits(..16, 0xdead);
+ field.set_bits(14.., 0xbeaf);
+ assert_eq!(field.get_bits(..16), 0xdead);
+ assert_eq!(field.get_bits(14..), 0xbeaf);
+}
+
+#[test]
+fn test_read_u64() {
+ let field = 0b1111111111010110u64 << 32;
+ for i in 0..32 {
+ assert_eq!(field.get_bit(i), false);
+ }
+ assert_eq!(field.get_bit(32), false);
+ assert_eq!(field.get_bit(33), true);
+ assert_eq!(field.get_bit(34), true);
+ assert_eq!(field.get_bit(35), false);
+ assert_eq!(field.get_bit(36), true);
+ assert_eq!(field.get_bit(37), false);
+ for i in 38..48 {
+ assert_eq!(field.get_bit(i), true);
+ }
+ for i in 48..64 {
+ assert_eq!(field.get_bit(i), false);
+ }
+
+ assert_eq!(field.get_bits(..32), 0);
+ assert_eq!(field.get_bits(0..32), 0);
+ assert_eq!(field.get_bits(0..=31), 0);
+
+ assert_eq!(field.get_bits(48..), 0);
+ assert_eq!(field.get_bits(48..64), 0);
+ assert_eq!(field.get_bits(48..=63), 0);
+
+ assert_eq!(field.get_bits(38..48), 0b1111111111);
+ assert_eq!(field.get_bits(38..=47), 0b1111111111);
+
+ assert_eq!(field.get_bits(32..38), 0b010110);
+ assert_eq!(field.get_bits(32..=37), 0b010110);
+
+ assert_eq!(field.get_bits(32..42), 0b1111010110);
+ assert_eq!(field.get_bits(32..=41), 0b1111010110);
+
+ assert_eq!(field.get_bits(37..44), 0b1111110);
+ assert_eq!(field.get_bits(37..=43), 0b1111110);
+}
+
+#[test]
+fn test_set_reset_u64() {
+ let mut field = 0b1111111111010110u64 << 32;
+ let mut bit_i = |i| {
+ field.set_bit(i, true);
+ assert_eq!(field.get_bit(i), true);
+ field.set_bit(i, false);
+ assert_eq!(field.get_bit(i), false);
+ field.set_bit(i, true);
+ assert_eq!(field.get_bit(i), true);
+ };
+ for i in 0..64 {
+ bit_i(i);
+ }
+}
+
+#[test]
+fn test_set_range_u64() {
+ let mut field = 0b1111111111010110u64 << 32;
+ field.set_bits(42..47, 0b00000);
+ assert_eq!(field.get_bits(42..47), 0b00000);
+ assert_eq!(field.get_bits(42..=46), 0b00000);
+ field.set_bits(10..15, 0b10101);
+ assert_eq!(field.get_bits(10..15), 0b10101);
+ assert_eq!(field.get_bits(10..=14), 0b10101);
+ field.set_bits(40..45, 0b01010);
+ assert_eq!(field.get_bits(40..45), 0b01010);
+ assert_eq!(field.get_bits(40..=44), 0b01010);
+ field.set_bits(40..45, 0b11111);
+ assert_eq!(field.get_bits(40..45), 0b11111);
+ assert_eq!(field.get_bits(40..=44), 0b11111);
+
+ field.set_bits(42..=46, 0b00000);
+ assert_eq!(field.get_bits(42..47), 0b00000);
+ assert_eq!(field.get_bits(42..=46), 0b00000);
+ field.set_bits(10..=14, 0b10101);
+ assert_eq!(field.get_bits(10..15), 0b10101);
+ assert_eq!(field.get_bits(10..=14), 0b10101);
+ field.set_bits(40..=44, 0b01010);
+ assert_eq!(field.get_bits(40..45), 0b01010);
+ assert_eq!(field.get_bits(40..=44), 0b01010);
+ field.set_bits(40..=44, 0b11111);
+ assert_eq!(field.get_bits(40..45), 0b11111);
+ assert_eq!(field.get_bits(40..=44), 0b11111);
+
+ field.set_bits(0..16, 0xdead);
+ field.set_bits(14..32, 0xbeaf);
+ field.set_bits(32..64, 0xcafebabe);
+ assert_eq!(field.get_bits(0..16), 0xdead);
+ assert_eq!(field.get_bits(14..32), 0xbeaf);
+ assert_eq!(field.get_bits(32..64), 0xcafebabe);
+
+ field.set_bits(..16, 0xdead);
+ field.set_bits(14..=31, 0xbeaf);
+ field.set_bits(32.., 0xcafebabe);
+ assert_eq!(field.get_bits(..16), 0xdead);
+ assert_eq!(field.get_bits(14..=31), 0xbeaf);
+ assert_eq!(field.get_bits(32..), 0xcafebabe);
+}
+
+#[test]
+fn test_read_u128() {
+ let field = 0b1111111111010110u128 << 32;
+ for i in 0..32 {
+ assert_eq!(field.get_bit(i), false);
+ }
+ assert_eq!(field.get_bit(32), false);
+ assert_eq!(field.get_bit(33), true);
+ assert_eq!(field.get_bit(34), true);
+ assert_eq!(field.get_bit(35), false);
+ assert_eq!(field.get_bit(36), true);
+ assert_eq!(field.get_bit(37), false);
+ for i in 38..48 {
+ assert_eq!(field.get_bit(i), true);
+ }
+ for i in 48..64 {
+ assert_eq!(field.get_bit(i), false);
+ }
+
+ assert_eq!(field.get_bits(..32), 0);
+ assert_eq!(field.get_bits(0..32), 0);
+ assert_eq!(field.get_bits(0..=31), 0);
+
+ assert_eq!(field.get_bits(48..), 0);
+ assert_eq!(field.get_bits(48..64), 0);
+ assert_eq!(field.get_bits(48..=63), 0);
+
+ assert_eq!(field.get_bits(38..48), 0b1111111111);
+ assert_eq!(field.get_bits(38..=47), 0b1111111111);
+
+ assert_eq!(field.get_bits(32..38), 0b010110);
+ assert_eq!(field.get_bits(32..=37), 0b010110);
+
+ assert_eq!(field.get_bits(32..42), 0b1111010110);
+ assert_eq!(field.get_bits(32..=41), 0b1111010110);
+
+ assert_eq!(field.get_bits(37..44), 0b1111110);
+ assert_eq!(field.get_bits(37..=43), 0b1111110);
+}
+
+#[test]
+fn test_set_reset_u128() {
+ let mut field = 0b1111111111010110u128 << 32;
+ let mut bit_i = |i| {
+ field.set_bit(i, true);
+ assert_eq!(field.get_bit(i), true);
+ field.set_bit(i, false);
+ assert_eq!(field.get_bit(i), false);
+ field.set_bit(i, true);
+ assert_eq!(field.get_bit(i), true);
+ };
+ for i in 0..64 {
+ bit_i(i);
+ }
+}
+
+#[test]
+fn test_set_range_u128() {
+ let mut field = 0b1111111111010110u128 << 32;
+ field.set_bits(42..47, 0b00000);
+ assert_eq!(field.get_bits(42..47), 0b00000);
+ assert_eq!(field.get_bits(42..=46), 0b00000);
+ field.set_bits(10..15, 0b10101);
+ assert_eq!(field.get_bits(10..15), 0b10101);
+ assert_eq!(field.get_bits(10..=14), 0b10101);
+ field.set_bits(40..45, 0b01010);
+ assert_eq!(field.get_bits(40..45), 0b01010);
+ assert_eq!(field.get_bits(40..=44), 0b01010);
+ field.set_bits(40..45, 0b11111);
+ assert_eq!(field.get_bits(40..45), 0b11111);
+ assert_eq!(field.get_bits(40..=44), 0b11111);
+
+ field.set_bits(42..=46, 0b00000);
+ assert_eq!(field.get_bits(42..47), 0b00000);
+ assert_eq!(field.get_bits(42..=46), 0b00000);
+ field.set_bits(10..=14, 0b10101);
+ assert_eq!(field.get_bits(10..15), 0b10101);
+ assert_eq!(field.get_bits(10..=14), 0b10101);
+ field.set_bits(40..=44, 0b01010);
+ assert_eq!(field.get_bits(40..45), 0b01010);
+ assert_eq!(field.get_bits(40..=44), 0b01010);
+ field.set_bits(40..=44, 0b11111);
+ assert_eq!(field.get_bits(40..45), 0b11111);
+ assert_eq!(field.get_bits(40..=44), 0b11111);
+
+ field.set_bits(0..16, 0xdead);
+ field.set_bits(14..32, 0xbeaf);
+ field.set_bits(32..64, 0xcafebabe);
+ assert_eq!(field.get_bits(0..16), 0xdead);
+ assert_eq!(field.get_bits(14..32), 0xbeaf);
+ assert_eq!(field.get_bits(32..64), 0xcafebabe);
+
+ field.set_bits(..16, 0xdead);
+ field.set_bits(14..=31, 0xbeaf);
+ field.set_bits(32.., 0xcafebabe);
+ assert_eq!(field.get_bits(..16), 0xdead);
+ assert_eq!(field.get_bits(14..=31), 0xbeaf);
+ assert_eq!(field.get_bits(32..), 0xcafebabe);
+}
+
+#[test]
+fn test_array_length() {
+ assert_eq!((&[2u8, 3u8, 4u8]).bit_length(), 24);
+ assert_eq!((&[2i8, 3i8, 4i8, 5i8]).bit_length(), 32);
+
+ assert_eq!((&[2u16, 3u16, 4u16]).bit_length(), 48);
+ assert_eq!((&[2i16, 3i16, 4i16, 5i16]).bit_length(), 64);
+
+ assert_eq!((&[2u32, 3u32, 4u32]).bit_length(), 96);
+ assert_eq!((&[2i32, 3i32, 4i32, 5i32]).bit_length(), 128);
+
+ assert_eq!((&[2u64, 3u64, 4u64]).bit_length(), 192);
+ assert_eq!((&[2i64, 3i64, 4i64, 5i64]).bit_length(), 256);
+}
+
+#[test]
+fn test_set_bit_array() {
+ let mut test_val = [0xffu8];
+ &test_val.set_bit(0, false);
+ assert_eq!(test_val, [0xfeu8]);
+ &test_val.set_bit(4, false);
+ assert_eq!(test_val, [0xeeu8]);
+
+ let mut test_array = [0xffu8, 0x00u8, 0xffu8];
+ &test_array.set_bit(7, false);
+ &test_array.set_bit(8, true);
+ &test_array.set_bit(16, false);
+
+ assert_eq!(test_array, [0x7fu8, 0x01u8, 0xfeu8]);
+}
+
+#[test]
+fn test_get_bit_array() {
+ let test_val = [0xefu8];
+ assert_eq!(test_val.get_bit(1), true);
+ assert_eq!(test_val.get_bit(4), false);
+
+ let test_array = [0xffu8, 0x00u8, 0xffu8];
+ assert_eq!(test_array.get_bit(7), true);
+ assert_eq!(test_array.get_bit(8), false);
+ assert_eq!(test_array.get_bit(16), true);
+}
+
+#[test]
+fn test_set_bits_array() {
+ let mut test_val = [0xffu8];
+
+ test_val.set_bits(0..4, 0x0u8);
+ assert_eq!(test_val, [0xf0u8]);
+
+ test_val.set_bits(0..4, 0xau8);
+ assert_eq!(test_val, [0xfau8]);
+
+ test_val.set_bits(4..8, 0xau8);
+ assert_eq!(test_val, [0xaau8]);
+
+ test_val.set_bits(.., 0xffu8);
+ assert_eq!(test_val, [0xffu8]);
+
+ test_val.set_bits(2..=5, 0x0u8);
+ assert_eq!(test_val, [0xc3u8]);
+
+ let mut test_array = [0xffu8, 0x00u8, 0xffu8];
+
+ test_array.set_bits(7..9, 0b10);
+ assert_eq!(test_array, [0x7f, 0x01, 0xff]);
+
+ test_array.set_bits(12..20, 0xaa);
+ assert_eq!(test_array, [0x7f, 0xa1, 0xfa]);
+
+ test_array.set_bits(16..24, 0xaa);
+ assert_eq!(test_array, [0x7f, 0xa1, 0xaa]);
+
+ test_array.set_bits(6..14, 0x00);
+ assert_eq!(test_array, [0x3f, 0x80, 0xaa]);
+
+ test_array.set_bits(..4, 0x00);
+ assert_eq!(test_array, [0x30, 0x80, 0xaa]);
+
+ test_array.set_bits(20.., 0x00);
+ assert_eq!(test_array, [0x30, 0x80, 0x0a]);
+
+ test_array.set_bits(7..=11, 0x1f);
+ assert_eq!(test_array, [0xb0, 0x8f, 0x0a]);
+}
+
+#[test]
+fn test_get_bits_array() {
+ let mut test_val = [0xf0u8];
+ assert_eq!(test_val.get_bits(0..4), 0x0u8);
+
+ test_val = [0xfau8];
+ assert_eq!(test_val.get_bits(0..4), 0xau8);
+
+ test_val = [0xaau8];
+ assert_eq!(test_val.get_bits(4..8), 0xau8);
+
+ let mut test_array: [u8; 3] = [0xff, 0x01, 0xff];
+ assert_eq!(test_array.get_bits(7..9), 0b11u8);
+
+ test_array = [0x7f, 0xa1, 0xfa];
+ assert_eq!(test_array.get_bits(12..20), 0xaa);
+
+ test_array = [0x7f, 0xa1, 0xaa];
+ assert_eq!(test_array.get_bits(16..24), 0xaa);
+
+ test_array = [0x3f, 0x80, 0xaa];
+ assert_eq!(test_array.get_bits(6..14), 0x00);
+}