primal-bit-0.3.1/.cargo_vcs_info.json0000644000000001500000000000100130710ustar { "git": { "sha1": "ebd1ba9d75e865d94a1d47c3451c5c14acf8183a" }, "path_in_vcs": "primal-bit" }primal-bit-0.3.1/Cargo.toml0000644000000020020000000000100110650ustar # 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] edition = "2018" name = "primal-bit" version = "0.3.1" authors = [ "Huon Wilson ", "The Rust Project Developers", ] description = """ Bit-vector specialised to the prime-number-related needs of `primal`. """ homepage = "https://github.com/huonw/primal" documentation = "http://docs.rs/primal-bit/" keywords = [ "math", "mathematics", "primes", "number-theory", ] license = "MIT OR Apache-2.0" repository = "https://github.com/huonw/primal" [dependencies.hamming] version = "0.1" [features] unstable = [] primal-bit-0.3.1/Cargo.toml.orig000064400000000000000000000010261046102023000145530ustar 00000000000000[package] name = "primal-bit" version = "0.3.1" authors = ["Huon Wilson ", "The Rust Project Developers"] edition = "2018" homepage = "https://github.com/huonw/primal" repository = "https://github.com/huonw/primal" documentation = "http://docs.rs/primal-bit/" license = "MIT OR Apache-2.0" keywords = ["math", "mathematics", "primes", "number-theory"] description = """ Bit-vector specialised to the prime-number-related needs of `primal`. """ [dependencies] hamming = "0.1" [features] unstable = [] primal-bit-0.3.1/LICENSE-APACHE000064400000000000000000000251371046102023000136210ustar 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. primal-bit-0.3.1/LICENSE-MIT000064400000000000000000000020361046102023000133220ustar 00000000000000Copyright (c) 2014 Huon Wilson 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.primal-bit-0.3.1/src/inner.rs000064400000000000000000000106261046102023000141420ustar 00000000000000//! Internals that unsafely rely on consistency between `BitVec` fields, //! encapsulated in a module to reduce scope. #![allow(unsafe_code)] use crate::BITS; /// The bitvector type. pub struct BitVec { /// Internal representation of the bit vector storage: Vec, /// The number of valid bits in the internal representation nbits: usize, } impl BitVec { /// Creates an empty `BitVec`. /// /// # Examples /// /// ```ignore /// use std::collections::BitVec; /// let mut bv = BitVec::new(); /// ``` #[inline] pub fn new() -> BitVec { BitVec { storage: Vec::new(), nbits: 0, } } /// Creates a `BitVec` from the given bytes. #[inline] pub fn from_bytes(data: Vec, nbits: usize) -> BitVec { let nbytes = nbits / BITS + usize::from(nbits % BITS != 0); assert_eq!(nbytes, data.len()); let mut ret = BitVec { storage: data, nbits, }; ret.fix_last_block(); ret } /// Creates a `BitVec` that holds `nbits` elements, setting each element /// to `bit`. /// /// # Examples /// /// ```ignore /// use std::collections::BitVec; /// /// let mut bv = BitVec::from_elem(10, false); /// assert_eq!(bv.len(), 10); /// for x in bv.iter() { /// assert_eq!(x, false); /// } /// ``` pub fn from_elem(nbits: usize, bit: bool) -> BitVec { let nbytes = nbits / BITS + usize::from(nbits % BITS != 0); let out_vec = vec![if bit { !0 } else { 0 }; nbytes]; let mut bit_vec = BitVec { storage: out_vec, nbits, }; if bit { bit_vec.fix_last_block(); } bit_vec } /// An operation might screw up the unused bits in the last block of the /// `BitVec`. As per (3), it's assumed to be all 0s. This method fixes it up. pub(crate) fn fix_last_block(&mut self) { let extra_bits = self.nbits % BITS; if extra_bits > 0 { let mask = (1 << extra_bits) - 1; let last = self.storage.last_mut().unwrap(); *last &= mask; } } #[inline] pub fn as_bytes_mut(&mut self) -> &mut [u8] { &mut self.storage } #[inline] pub fn as_bytes(&self) -> &[u8] { &self.storage } #[inline] pub(crate) fn into_bytes(self) -> Vec { self.storage } /// Returns the total number of bits in this vector #[inline] pub fn len(&self) -> usize { self.nbits } /// Retrieves the value at index `i`, or `None` if the index is out of bounds. /// /// # Examples /// /// ```ignore /// use std::collections::BitVec; /// /// let bv = BitVec::from_bytes(&[0b01100000]); /// assert_eq!(bv.get(0), Some(false)); /// assert_eq!(bv.get(1), Some(true)); /// assert_eq!(bv.get(100), None); /// /// // Can also use array indexing /// assert_eq!(bv[1], true); /// ``` #[inline] pub fn get(&self, i: usize) -> Option { if i >= self.nbits { return None; } let w = i / BITS; let b = i % BITS; let mask = 1 << b; unsafe { let block = *self.storage.get_unchecked(w); Some(block & mask != 0) } } /// Sets the value of a bit at an index `i`. /// /// # Panics /// /// Panics if `i` is out of bounds. /// /// # Examples /// /// ```ignore /// use std::collections::BitVec; /// /// let mut bv = BitVec::from_elem(5, false); /// bv.set(3, true); /// assert_eq!(bv[3], true); /// ``` #[inline] pub fn set(&mut self, i: usize, x: bool) { assert!(i < self.nbits, "index out of bounds"); let w = i / BITS; let b = i % BITS; let mask = 1 << b; let bit = u8::from(x) << b; unsafe { let ptr = self.storage.get_unchecked_mut(w); *ptr = (*ptr & !mask) | bit; } } } impl Clone for BitVec { #[inline] fn clone(&self) -> BitVec { BitVec { storage: self.storage.clone(), nbits: self.nbits, } } #[inline] fn clone_from(&mut self, source: &BitVec) { self.nbits = 0; // safe default while storage is modified self.storage.clone_from(&source.storage); self.nbits = source.nbits; } } primal-bit-0.3.1/src/iter.rs000064400000000000000000000121411046102023000137640ustar 00000000000000use std::iter; use std::mem; use std::ops::Range; use std::slice; use std::vec; use crate::BitVec; use crate::BITS; impl BitVec { /// Returns an iterator over the elements of the vector in order. /// /// # Examples /// /// ```ignore /// use std::collections::BitVec; /// /// let bv = BitVec::from_bytes(&[0b01110100, 0b10010010]); /// assert_eq!(bv.iter().filter(|x| *x).count(), 7); /// ``` #[inline] pub fn iter(&self) -> Iter<'_> { Iter { bit_vec: self, idx: 0..self.len(), } } } /// An iterator for `BitVec`. #[derive(Clone)] pub struct Iter<'a> { bit_vec: &'a BitVec, idx: Range, } impl<'a> Iterator for Iter<'a> { type Item = bool; #[inline] fn next(&mut self) -> Option { self.bit_vec.get(self.idx.next()?) } #[inline] fn size_hint(&self) -> (usize, Option) { self.idx.size_hint() } } impl<'a> DoubleEndedIterator for Iter<'a> { #[inline] fn next_back(&mut self) -> Option { self.bit_vec.get(self.idx.next_back()?) } } impl<'a> ExactSizeIterator for Iter<'a> {} impl<'a> IntoIterator for &'a BitVec { type Item = bool; type IntoIter = Iter<'a>; #[inline] fn into_iter(self) -> Iter<'a> { self.iter() } } impl BitVec { #[inline] pub fn ones_from(&self, from: usize) -> Ones<'_> { let (byte, bit) = (from / BITS, from % BITS); let mask = (!0) << bit; let mut iter = self.as_bytes()[byte..].iter().copied(); let (current, _) = usize_from_bytes(&mut iter); InnerOnes { base: byte * BITS, current: current & mask, iter, } } #[inline] pub fn into_ones(self) -> IntoOnes { let mut iter = self.into_bytes().into_iter(); let (current, _) = usize_from_bytes(&mut iter); InnerOnes { base: 0, current, iter, } } } pub type Ones<'a> = InnerOnes>>; pub type IntoOnes = InnerOnes>; #[derive(Clone)] pub struct InnerOnes { base: usize, current: usize, iter: I, } impl> Iterator for InnerOnes { type Item = usize; #[inline] fn next(&mut self) -> Option { let mut c = self.current; while c == 0 { let (next, done) = usize_from_bytes(&mut self.iter); if done { return None; } self.base += BITS * mem::size_of::(); c = next; } let lsb = c.trailing_zeros(); self.current = c & (c - 1); Some(self.base + lsb as usize) } } /// Extract a `usize` from an iterator over bytes. /// /// It helps our iterator performance to pull bits from a native word at a time. #[inline] fn usize_from_bytes(iter: &mut impl Iterator) -> (usize, bool) { let mut n = 0; for i in 0..mem::size_of::() { match iter.next() { Some(b) => n |= usize::from(b) << (i * BITS), None => return (n, i == 0), } } (n, false) } #[test] fn iter_ones_from() { let len = 5000; let zeros = BitVec::from_elem(len, false); assert_eq!(zeros.ones_from(0).next(), None); let ones = BitVec::from_elem(len, true); let mut iter = ones.ones_from(0); for i in 0..len { assert_eq!(iter.next(), Some(i)); assert_eq!(ones.ones_from(i).next(), Some(i)); } let mut halves = BitVec::from_elem(len * 2, false); for i in 0..len { halves.set(i * 2, true); } let mut iter = halves.ones_from(0); for i in 0..len { assert_eq!(iter.next(), Some(i * 2)); assert_eq!(halves.ones_from(i * 2).next(), Some(i * 2)); if i > 0 { assert_eq!(halves.ones_from(i * 2 - 1).next(), Some(i * 2)); } assert_eq!(halves.ones_from(i).next(), Some(i + (i % 2))); } let mut sparse = BitVec::from_elem(len * 101, false); for i in 0..len { sparse.set(i * 101, true); } let mut iter = sparse.ones_from(0); for i in 0..len { let i101 = i * 101; assert_eq!(iter.next(), Some(i101)); if i > 0 { for j in i101 - 100..=i101 { assert_eq!(sparse.ones_from(j).next(), Some(i101)); } } } } #[test] fn iter_into_ones() { let len = 5000; let zeros = BitVec::from_elem(len, false); assert_eq!(zeros.into_ones().next(), None); let ones = BitVec::from_elem(len, true); let mut iter = ones.into_ones(); for i in 0..len { assert_eq!(iter.next(), Some(i)); } let mut halves = BitVec::from_elem(len * 2, false); for i in 0..len { halves.set(i * 2, true); } let mut iter = halves.into_ones(); for i in 0..len { assert_eq!(iter.next(), Some(i * 2)); } let mut sparse = BitVec::from_elem(len * 101, false); for i in 0..len { sparse.set(i * 101, true); } let mut iter = sparse.into_ones(); for i in 0..len { assert_eq!(iter.next(), Some(i * 101)); } } primal-bit-0.3.1/src/lib.rs000064400000000000000000000161041046102023000135720ustar 00000000000000// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! A very simple bit-vector that serves the needs of `primal`. #![deny(unsafe_code)] use std::fmt; use std::hash; use std::ops::Index; mod inner; mod iter; pub use crate::inner::BitVec; pub use crate::iter::{Iter, IntoOnes, Ones}; const BITS: usize = 8; impl Index for BitVec { type Output = bool; #[inline] fn index(&self, i: usize) -> &bool { if self.get(i).expect("index out of bounds") { &true } else { &false } } } impl BitVec { /// Count the number of ones in the entire `BitVec`. #[inline] pub fn count_ones(&self) -> usize { hamming::weight(self.as_bytes()) as usize } /// Count the number of ones for the bits up to but not including /// the `bit`th bit. #[inline] pub fn count_ones_before(&self, bit: usize) -> usize { assert!(bit <= self.len()); let (byte, bit) = (bit / BITS, bit % BITS); let mask = (1 << bit) - 1; let bytes = self.as_bytes(); hamming::weight(&bytes[..byte]) as usize + bytes.get(byte).map_or(0, |b| (b & mask).count_ones() as usize) } /// Find the index of the `n`th (0-indexed) set bit. pub fn find_nth_bit(&self, mut n: usize) -> Option { if n >= self.len() { return None; } n += 1; let mut bytes = self.as_bytes(); let mut byte_idx = 0; while bytes.len() > 240 { let ix = bytes.len() / 2; let (first, second) = bytes.split_at(ix); let count = hamming::weight(first) as usize; if count >= n { bytes = first; } else { n -= count; bytes = second; byte_idx += ix; } } let i = bytes.iter().position(|&b| { let count = b.count_ones() as usize; if count >= n { true } else { n -= count; false } })?; // clear the bottom n-1 set bits, so that the lowest one // is the one we care about let mut b = bytes[i]; for _ in 1..n { b &= b - 1; } assert!(b != 0); Some((byte_idx + i) * BITS + b.trailing_zeros() as usize) } /// Sets all bits to 1. /// /// # Examples /// /// ```ignore /// use std::collections::BitVec; /// /// let before = 0b01100000; /// let after = 0b11111111; /// /// let mut bv = BitVec::from_bytes(&[before]); /// bv.set_all(); /// assert_eq!(bv, BitVec::from_bytes(&[after])); /// ``` #[inline] pub fn set_all(&mut self) { for w in self.as_bytes_mut() { *w = !0; } self.fix_last_block(); } /// Clears all bits in this vector. #[inline] pub fn clear(&mut self) { for w in self.as_bytes_mut() { *w = 0; } } /// Returns true if there are no bits in this vector #[inline] pub fn is_empty(&self) -> bool { self.len() == 0 } } impl Default for BitVec { #[inline] fn default() -> BitVec { BitVec::new() } } impl fmt::Debug for BitVec { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { for bit in self { write!(fmt, "{}", if bit { 1 } else { 0 })?; } Ok(()) } } impl hash::Hash for BitVec { fn hash(&self, state: &mut H) { state.write_usize(self.len()); state.write(self.as_bytes()); } } impl PartialEq for BitVec { #[inline] fn eq(&self, other: &BitVec) -> bool { self.len() == other.len() && self.as_bytes() == other.as_bytes() } } impl Eq for BitVec {} #[cfg(test)] mod tests { use super::BitVec; #[test] fn count_ones_before() { let len = 10000; let ones = BitVec::from_elem(len, true); let zeros = BitVec::from_elem(len, false); let mut halves = zeros.clone(); for i in 0..len / 2 { halves.set(i * 2, true); } for i in 0..len + 1 { assert_eq!(ones.count_ones_before(i), i); assert_eq!(zeros.count_ones_before(i), 0); assert_eq!(halves.count_ones_before(i), (i + 1) / 2); } } #[test] fn find_nth_bit() { let len = 5000; let ones = BitVec::from_elem(len, true); let mut halves = BitVec::from_elem(len * 2, false); for i in 0..len { halves.set(i * 2, true); } for i in 0..len { assert_eq!(ones.find_nth_bit(i), Some(i)); assert_eq!(halves.find_nth_bit(i), Some(i * 2)); } assert_eq!(ones.find_nth_bit(len + 1), None); assert_eq!(halves.find_nth_bit(len + 1), None); assert_eq!(BitVec::new().find_nth_bit(0), None); assert_eq!(BitVec::from_elem(len, false).find_nth_bit(0), None); } #[test] fn get() { let len = 10000; let mut halves = BitVec::from_elem(len, false); for i in 0..len { assert_eq!(halves.get(i), Some(false)); } for i in 0..len / 2 { halves.set(i * 2, true); } for i in 0..len { assert_eq!(halves.get(i), Some(i % 2 == 0)); } assert_eq!(halves.get(len), None); } #[test] fn clone() { let len = 10000; let ones = BitVec::from_elem(len, true); let zeros = BitVec::from_elem(len, false); let mut halves = zeros.clone(); for i in 0..len / 2 { halves.set(i * 2, true); } assert_eq!(ones.clone(), ones); assert_eq!(zeros.clone(), zeros); assert_eq!(halves.clone(), halves); let mut bv = BitVec::from_elem(len, false); bv.clone_from(&ones); assert_eq!(bv, ones); bv.clone_from(&zeros); assert_eq!(bv, zeros); bv.clone_from(&halves); assert_eq!(bv, halves); } #[test] fn len_is_empty() { let len = 10000; let ones = BitVec::from_elem(len, true); let zeros = BitVec::from_elem(len, false); let default = BitVec::default(); assert_eq!(ones.len(), len); assert_eq!(zeros.len(), len); assert_eq!(default.len(), 0); assert!(!ones.is_empty()); assert!(!zeros.is_empty()); assert!(default.is_empty()); } #[test] fn clear_set_all() { let len = 10000; let ones = BitVec::from_elem(len, true); let zeros = BitVec::from_elem(len, false); let mut bv = ones.clone(); assert_eq!(bv, ones); bv.clear(); assert_eq!(bv, zeros); bv.set_all(); assert_eq!(bv, ones); } } primal-bit-0.3.1/tests/from_rust.rs000064400000000000000000000361341046102023000154240ustar 00000000000000// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. use primal_bit::BitVec; fn from_bools(bools: &[bool]) -> BitVec { let mut bit_vec = BitVec::from_elem(bools.len(), false); for (i, b) in bools.iter().enumerate() { bit_vec.set(i, *b) } bit_vec } trait Methods { fn eq_vec(&self, v: &[bool]) -> bool; fn from_slice(x: &[u8]) -> BitVec; fn all(&self) -> bool; fn none(&self) -> bool; fn any(&self) -> bool; } impl Methods for BitVec { fn eq_vec(&self, v: &[bool]) -> bool { self.len() == v.len() && self.iter().zip(v).all(|(a, &b)| a == b) } fn from_slice(bytes: &[u8]) -> BitVec { let len = bytes.len().checked_mul(8).expect("capacity overflow"); let mut bit_vec = BitVec::from_elem(len, false); let mut i = 0; for &byte in bytes { for x in (0..8).rev() { bit_vec.set(i, byte & (1 << x) != 0); i += 1 } } bit_vec } fn all(&self) -> bool { self.iter().all(|b| b) } fn none(&self) -> bool { self.iter().all(|b| !b) } fn any(&self) -> bool { !self.none() } } #[test] fn test_to_str() { let zerolen = BitVec::new(); assert_eq!(format!("{:?}", zerolen), ""); let eightbits = BitVec::from_elem(8, false); assert_eq!(format!("{:?}", eightbits), "00000000") } #[test] fn test_0_elements() { let act = BitVec::new(); let exp = Vec::new(); assert!(act.eq_vec(&exp)); assert!(act.none() && act.all()); } #[test] fn test_1_element() { let mut act = BitVec::from_elem(1, false); assert!(act.eq_vec(&[false])); assert!(act.none() && !act.all()); act = BitVec::from_elem(1, true); assert!(act.eq_vec(&[true])); assert!(!act.none() && act.all()); } #[test] fn test_2_elements() { let mut b = BitVec::from_elem(2, false); b.set(0, true); b.set(1, false); assert_eq!(format!("{:?}", b), "10"); assert!(!b.none() && !b.all()); } #[test] fn test_10_elements() { let mut act; // all 0 act = BitVec::from_elem(10, false); assert!((act.eq_vec( &[false, false, false, false, false, false, false, false, false, false]))); assert!(act.none() && !act.all()); // all 1 act = BitVec::from_elem(10, true); assert!((act.eq_vec(&[true, true, true, true, true, true, true, true, true, true]))); assert!(!act.none() && act.all()); // mixed act = BitVec::from_elem(10, false); act.set(0, true); act.set(1, true); act.set(2, true); act.set(3, true); act.set(4, true); assert!((act.eq_vec(&[true, true, true, true, true, false, false, false, false, false]))); assert!(!act.none() && !act.all()); // mixed act = BitVec::from_elem(10, false); act.set(5, true); act.set(6, true); act.set(7, true); act.set(8, true); act.set(9, true); assert!((act.eq_vec(&[false, false, false, false, false, true, true, true, true, true]))); assert!(!act.none() && !act.all()); // mixed act = BitVec::from_elem(10, false); act.set(0, true); act.set(3, true); act.set(6, true); act.set(9, true); assert!((act.eq_vec(&[true, false, false, true, false, false, true, false, false, true]))); assert!(!act.none() && !act.all()); } #[test] fn test_31_elements() { let mut act; // all 0 act = BitVec::from_elem(31, false); assert!(act.eq_vec( &[false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false])); assert!(act.none() && !act.all()); // all 1 act = BitVec::from_elem(31, true); assert!(act.eq_vec( &[true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true])); assert!(!act.none() && act.all()); // mixed act = BitVec::from_elem(31, false); act.set(0, true); act.set(1, true); act.set(2, true); act.set(3, true); act.set(4, true); act.set(5, true); act.set(6, true); act.set(7, true); assert!(act.eq_vec( &[true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false])); assert!(!act.none() && !act.all()); // mixed act = BitVec::from_elem(31, false); act.set(16, true); act.set(17, true); act.set(18, true); act.set(19, true); act.set(20, true); act.set(21, true); act.set(22, true); act.set(23, true); assert!(act.eq_vec( &[false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, false, false, false, false, false, false, false])); assert!(!act.none() && !act.all()); // mixed act = BitVec::from_elem(31, false); act.set(24, true); act.set(25, true); act.set(26, true); act.set(27, true); act.set(28, true); act.set(29, true); act.set(30, true); assert!(act.eq_vec( &[false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, true])); assert!(!act.none() && !act.all()); // mixed act = BitVec::from_elem(31, false); act.set(3, true); act.set(17, true); act.set(30, true); assert!(act.eq_vec( &[false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, true])); assert!(!act.none() && !act.all()); } #[test] fn test_32_elements() { let mut act; // all 0 act = BitVec::from_elem(32, false); assert!(act.eq_vec( &[false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false])); assert!(act.none() && !act.all()); // all 1 act = BitVec::from_elem(32, true); assert!(act.eq_vec( &[true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true])); assert!(!act.none() && act.all()); // mixed act = BitVec::from_elem(32, false); act.set(0, true); act.set(1, true); act.set(2, true); act.set(3, true); act.set(4, true); act.set(5, true); act.set(6, true); act.set(7, true); assert!(act.eq_vec( &[true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false])); assert!(!act.none() && !act.all()); // mixed act = BitVec::from_elem(32, false); act.set(16, true); act.set(17, true); act.set(18, true); act.set(19, true); act.set(20, true); act.set(21, true); act.set(22, true); act.set(23, true); assert!(act.eq_vec( &[false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false])); assert!(!act.none() && !act.all()); // mixed act = BitVec::from_elem(32, false); act.set(24, true); act.set(25, true); act.set(26, true); act.set(27, true); act.set(28, true); act.set(29, true); act.set(30, true); act.set(31, true); assert!(act.eq_vec( &[false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true])); assert!(!act.none() && !act.all()); // mixed act = BitVec::from_elem(32, false); act.set(3, true); act.set(17, true); act.set(30, true); act.set(31, true); assert!(act.eq_vec( &[false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, true, true])); assert!(!act.none() && !act.all()); } #[test] fn test_33_elements() { let mut act; // all 0 act = BitVec::from_elem(33, false); assert!(act.eq_vec( &[false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false])); assert!(act.none() && !act.all()); // all 1 act = BitVec::from_elem(33, true); assert!(act.eq_vec( &[true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true])); assert!(!act.none() && act.all()); // mixed act = BitVec::from_elem(33, false); act.set(0, true); act.set(1, true); act.set(2, true); act.set(3, true); act.set(4, true); act.set(5, true); act.set(6, true); act.set(7, true); assert!(act.eq_vec( &[true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false])); assert!(!act.none() && !act.all()); // mixed act = BitVec::from_elem(33, false); act.set(16, true); act.set(17, true); act.set(18, true); act.set(19, true); act.set(20, true); act.set(21, true); act.set(22, true); act.set(23, true); assert!(act.eq_vec( &[false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false, false])); assert!(!act.none() && !act.all()); // mixed act = BitVec::from_elem(33, false); act.set(24, true); act.set(25, true); act.set(26, true); act.set(27, true); act.set(28, true); act.set(29, true); act.set(30, true); act.set(31, true); assert!(act.eq_vec( &[false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, false])); assert!(!act.none() && !act.all()); // mixed act = BitVec::from_elem(33, false); act.set(3, true); act.set(17, true); act.set(30, true); act.set(31, true); act.set(32, true); assert!(act.eq_vec( &[false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true])); assert!(!act.none() && !act.all()); } #[test] fn test_equal_differing_sizes() { let v0 = BitVec::from_elem(10, false); let v1 = BitVec::from_elem(11, false); assert!(v0 != v1); } #[test] fn test_equal_greatly_differing_sizes() { let v0 = BitVec::from_elem(10, false); let v1 = BitVec::from_elem(110, false); assert!(v0 != v1); } #[test] fn test_equal_sneaky_small() { let mut a = BitVec::from_elem(1, false); a.set(0, true); let mut b = BitVec::from_elem(1, true); b.set(0, true); assert_eq!(a, b); } #[test] fn test_equal_sneaky_big() { let mut a = BitVec::from_elem(100, false); for i in 0..100 { a.set(i, true); } let mut b = BitVec::from_elem(100, true); for i in 0..100 { b.set(i, true); } assert_eq!(a, b); } #[test] fn test_from_bytes() { let bit_vec = BitVec::from_slice(&[0b10110110, 0b00000000, 0b11111111]); let str = concat!("10110110", "00000000", "11111111"); assert_eq!(format!("{:?}", bit_vec), str); } #[test] fn test_to_bools() { let bools = vec![false, false, true, false, false, true, true, false]; assert_eq!(BitVec::from_slice(&[0b00100110]).iter().collect::>(), bools); } #[test] fn test_bit_vec_iterator() { let bools = vec![true, false, true, true]; let bit_vec: BitVec = from_bools(&bools); assert_eq!(bit_vec.iter().collect::>(), bools); let long: Vec<_> = (0..10000).map(|i| i % 2 == 0).collect(); let bit_vec: BitVec = from_bools(&long); assert_eq!(bit_vec.iter().collect::>(), long) } #[test] fn test_small_clear() { let mut b = BitVec::from_elem(14, true); assert!(!b.none() && b.all()); b.clear(); assert!(b.none() && !b.all()); } #[test] fn test_big_clear() { let mut b = BitVec::from_elem(140, true); assert!(!b.none() && b.all()); b.clear(); assert!(b.none() && !b.all()); } #[test] fn test_small_bit_vec_tests() { let v = BitVec::from_slice(&[0]); assert!(!v.all()); assert!(!v.any()); assert!(v.none()); let v = BitVec::from_slice(&[0b00010100]); assert!(!v.all()); assert!(v.any()); assert!(!v.none()); let v = BitVec::from_slice(&[0xFF]); assert!(v.all()); assert!(v.any()); assert!(!v.none()); } #[test] fn test_big_bit_vec_tests() { let v = BitVec::from_slice(&[ // 88 bits 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); assert!(!v.all()); assert!(!v.any()); assert!(v.none()); let v = BitVec::from_slice(&[ // 88 bits 0, 0, 0b00010100, 0, 0, 0, 0, 0b00110100, 0, 0, 0]); assert!(!v.all()); assert!(v.any()); assert!(!v.none()); let v = BitVec::from_slice(&[ // 88 bits 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]); assert!(v.all()); assert!(v.any()); assert!(!v.none()); }