use core::mem;
use core::ops::{Deref, DerefMut};
use core::ops::Index;
use core::ops::Range;
use util::div_rem;
use super::{Block, BITS, TRUE, FALSE};
pub struct BitVecSlice {
slice: [Block],
}
impl BitVecSlice {
#[inline]
pub fn new(slice: &[Block]) -> &Self {
unsafe {
mem::transmute(slice)
}
}
#[inline]
pub fn new_mut(slice: &mut [Block]) -> &mut Self {
unsafe {
mem::transmute(slice)
}
}
#[inline]
pub fn iter_bits(&self, len: usize) -> Iter {
Iter { bit_slice: self, range: 0..len }
}
#[inline]
pub fn get(&self, bit: usize) -> bool {
let (block, i) = div_rem(bit, BITS);
match self.slice.get(block) {
None => false,
Some(b) => (b & (1 << i)) != 0,
}
}
}
impl Index<usize> for BitVecSlice {
type Output = bool;
#[inline]
fn index(&self, bit: usize) -> &bool {
let (block, i) = div_rem(bit, BITS);
match self.slice.get(block) {
None => &FALSE,
Some(b) => if (b & (1 << i)) != 0 { &TRUE } else { &FALSE },
}
}
}
impl Deref for BitVecSlice {
type Target = [Block];
#[inline]
fn deref(&self) -> &[Block] {
&self.slice
}
}
impl DerefMut for BitVecSlice {
#[inline]
fn deref_mut(&mut self) -> &mut [Block] {
&mut self.slice
}
}
#[derive(Clone)]
pub struct Iter<'a> {
bit_slice: &'a BitVecSlice,
range: Range<usize>,
}
impl<'a> Iterator for Iter<'a> {
type Item = bool;
#[inline]
fn next(&mut self) -> Option<bool> {
self.range.next().map(|i| self.bit_slice[i])
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.range.size_hint()
}
}