microsoft/qdk
Publicmirrored from https://github.com/microsoft/qdkAvailable
source/paulimer/src/bits/bitchunk.rs
45lines · modecode
| 1 | // Copyright (c) Microsoft Corporation. |
| 2 | // Licensed under the MIT License. |
| 3 | |
| 4 | pub struct BitChunkAccessor<const CHUNK_SIZE: usize> { |
| 5 | pub threshold: u32, |
| 6 | pub shift: u32, |
| 7 | pub word_id: u32, |
| 8 | pub mask: u64, |
| 9 | } |
| 10 | |
| 11 | impl<const CHUNK_SIZE: usize> Default for BitChunkAccessor<CHUNK_SIZE> { |
| 12 | /// # Panics |
| 13 | /// When `CHUNK_SIZE` does not fit into u32 |
| 14 | fn default() -> Self { |
| 15 | Self { |
| 16 | threshold: (u64::BITS / u32::try_from(CHUNK_SIZE).unwrap() - 1) |
| 17 | * u32::try_from(CHUNK_SIZE).unwrap(), |
| 18 | shift: 0, |
| 19 | word_id: 0, |
| 20 | mask: u64::MAX >> (u64::BITS - u32::try_from(CHUNK_SIZE).unwrap()), |
| 21 | } |
| 22 | } |
| 23 | } |
| 24 | |
| 25 | impl<const CHUNK_SIZE: usize> BitChunkAccessor<CHUNK_SIZE> { |
| 26 | /// # Panics |
| 27 | /// When `CHUNK_SIZE` does not fit into u32 |
| 28 | pub fn next(&mut self) { |
| 29 | if self.shift == self.threshold { |
| 30 | self.shift = 0; |
| 31 | self.word_id += 1; |
| 32 | } else { |
| 33 | self.shift += u32::try_from(CHUNK_SIZE).unwrap(); |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | pub fn xor(&self, what: &mut [u64], val: u64) { |
| 38 | what[self.word_id as usize] ^= val << self.shift; |
| 39 | } |
| 40 | |
| 41 | #[must_use] |
| 42 | pub fn get(&self, what: &[u64]) -> u64 { |
| 43 | (what[self.word_id as usize] >> self.shift) & self.mask |
| 44 | } |
| 45 | } |
| 46 | |