#![feature(core)]
use std::cmp::Ordering;
use std::cmp;
use std::fmt;
use std::hash;
use std::iter::{Chain, Enumerate, Repeat, Skip, Take, repeat, Cloned};
use std::iter::{self, FromIterator};
use std::slice;
use std::{u8, usize};
pub type Blocks<'a, B> = Cloned<slice::Iter<'a, B>>;
type MutBlocks<'a, B> = slice::IterMut<'a, B>;
type MatchWords<'a, B> = Chain<Enumerate<Blocks<'a, B>>, Skip<Take<Enumerate<Repeat<B>>>>>;
use std::ops::*;
pub trait BitBlock:
Copy +
Add<Self, Output=Self> +
Sub<Self, Output=Self> +
Shl<usize, Output=Self> +
Shr<usize, Output=Self> +
Not<Output=Self> +
BitAnd<Self, Output=Self> +
BitOr<Self, Output=Self> +
BitXor<Self, Output=Self> +
Rem<Self, Output=Self> +
Eq +
Ord +
hash::Hash +
{
fn bits() -> usize;
fn bytes() -> usize { Self::bits() / 8 }
fn from_byte(byte: u8) -> Self;
fn count_ones(self) -> usize;
fn zero() -> Self;
fn one() -> Self;
}
macro_rules! bit_block_impl {
($(($t: ty, $size: expr)),*) => ($(
impl BitBlock for $t {
fn bits() -> usize { $size }
fn from_byte(byte: u8) -> Self { byte as $t }
fn count_ones(self) -> usize { self.count_ones() as usize }
fn one() -> Self { 1 }
fn zero() -> Self { 0 }
}
)*)
}
bit_block_impl!{
(u8, 8),
(u16, 16),
(u32, 32),
(u64, 64)
}
fn reverse_bits(byte: u8) -> u8 {
let mut result = 0;
for i in 0..u8::bits() {
result = result | ((byte >> i) & 1) << (u8::bits() - 1 - i);
}
result
}
static TRUE: bool = true;
static FALSE: bool = false;
pub struct BitVec<B=u32> {
storage: Vec<B>,
nbits: usize
}
impl<B: BitBlock> Index<usize> for BitVec<B> {
type Output = bool;
#[inline]
fn index(&self, i: usize) -> &bool {
if self.get(i).expect("index out of bounds") {
&TRUE
} else {
&FALSE
}
}
}
fn blocks_for_bits<B: BitBlock>(bits: usize) -> usize {
if bits % B::bits() == 0 {
bits / B::bits()
} else {
bits / B::bits() + 1
}
}
fn mask_for_bits<B: BitBlock>(bits: usize) -> B {
!B::zero() >> (B::bits() - bits % B::bits()) % B::bits()
}
impl<B: BitBlock> BitVec<B> {
#[inline]
fn process<F>(&mut self, other: &BitVec<B>, mut op: F) -> bool
where F: FnMut(B, B) -> B {
assert_eq!(self.len(), other.len());
assert_eq!(self.storage.len(), other.storage.len());
let mut changed_bits = B::zero();
for (a, b) in self.blocks_mut().zip(other.blocks()) {
let w = op(*a, b);
changed_bits = changed_bits | (*a ^ w);
*a = w;
}
changed_bits != B::zero()
}
fn blocks_mut(&mut self) -> MutBlocks<B> {
self.storage.iter_mut()
}
pub fn blocks(&self) -> Blocks<B> {
self.storage.iter().cloned()
}
pub fn storage(&self) -> &[B] {
&self.storage
}
pub unsafe fn storage_mut(&mut self) -> &mut Vec<B> {
&mut self.storage
}
fn fix_last_block(&mut self) {
let extra_bits = self.len() % B::bits();
if extra_bits > 0 {
let mask = (B::one() << extra_bits) - B::one();
let storage_len = self.storage.len();
let block = &mut self.storage[storage_len - 1];
*block = *block & mask;
}
}
pub fn new() -> Self {
BitVec { storage: Vec::new(), nbits: 0 }
}
pub fn from_elem(nbits: usize, bit: bool) -> Self {
let nblocks = blocks_for_bits::<B>(nbits);
let mut bit_vec = BitVec {
storage: repeat(if bit { !B::zero() } else { B::zero() }).take(nblocks).collect(),
nbits: nbits
};
bit_vec.fix_last_block();
bit_vec
}
pub fn with_capacity(nbits: usize) -> Self {
BitVec {
storage: Vec::with_capacity(blocks_for_bits::<B>(nbits)),
nbits: 0,
}
}
pub fn from_bytes(bytes: &[u8]) -> Self {
let len = bytes.len().checked_mul(u8::bits()).expect("capacity overflow");
let mut bit_vec = BitVec::with_capacity(len);
let complete_words = bytes.len() / B::bytes();
let extra_bytes = bytes.len() % B::bytes();
bit_vec.nbits = len;
for i in 0..complete_words {
let mut accumulator = B::zero();
for idx in 0..B::bytes() {
accumulator = accumulator |
(B::from_byte(reverse_bits(bytes[i * B::bytes() + idx])) << (i * 8))
}
bit_vec.storage.push(accumulator);
}
if extra_bytes > 0 {
let mut last_word = B::zero();
for (i, &byte) in bytes[complete_words * B::bytes()..].iter().enumerate() {
last_word = last_word |
(B::from_byte(reverse_bits(byte)) << (i * 8));
}
bit_vec.storage.push(last_word);
}
bit_vec
}
pub fn from_fn<F>(len: usize, mut f: F) -> Self
where F: FnMut(usize) -> bool
{
let mut bit_vec = BitVec::from_elem(len, false);
for i in 0..len {
bit_vec.set(i, f(i));
}
bit_vec
}
#[inline]
pub fn get(&self, i: usize) -> Option<bool> {
if i >= self.nbits {
return None;
}
let w = i / B::bits();
let b = i % B::bits();
self.storage.get(w).map(|&block|
(block & (B::one() << b)) != B::zero()
)
}
#[inline]
pub fn set(&mut self, i: usize, x: bool) {
assert!(i < self.nbits);
let w = i / B::bits();
let b = i % B::bits();
let flag = B::one() << b;
let val = if x { self.storage[w] | flag }
else { self.storage[w] & !flag };
self.storage[w] = val;
}
#[inline]
pub fn set_all(&mut self) {
for w in &mut self.storage { *w = !B::zero(); }
self.fix_last_block();
}
#[inline]
pub fn negate(&mut self) {
for w in &mut self.storage { *w = !*w; }
self.fix_last_block();
}
#[inline]
pub fn union(&mut self, other: &Self) -> bool {
self.process(other, |w1, w2| (w1 | w2))
}
#[inline]
pub fn intersect(&mut self, other: &Self) -> bool {
self.process(other, |w1, w2| (w1 & w2))
}
#[inline]
pub fn difference(&mut self, other: &Self) -> bool {
self.process(other, |w1, w2| (w1 & !w2))
}
pub fn all(&self) -> bool {
let mut last_word = !B::zero();
self.blocks().all(|elem| {
let tmp = last_word;
last_word = elem;
tmp == !B::zero()
}) && (last_word == mask_for_bits(self.nbits))
}
#[inline]
pub fn iter(&self) -> Iter<B> {
Iter { bit_vec: self, next_idx: 0, end_idx: self.nbits }
}
pub fn none(&self) -> bool {
self.blocks().all(|w| w == B::zero())
}
#[inline]
pub fn any(&self) -> bool {
!self.none()
}
pub fn to_bytes(&self) -> Vec<u8> {
fn bit<B: BitBlock>(bit_vec: &BitVec<B>, byte: usize, bit: usize) -> u8 {
let offset = byte * 8 + bit;
if offset >= bit_vec.nbits {
0
} else {
(bit_vec[offset] as u8) << (7 - bit)
}
}
let len = self.nbits / 8 +
if self.nbits % 8 == 0 { 0 } else { 1 };
(0..len).map(|i|
bit(self, i, 0) |
bit(self, i, 1) |
bit(self, i, 2) |
bit(self, i, 3) |
bit(self, i, 4) |
bit(self, i, 5) |
bit(self, i, 6) |
bit(self, i, 7)
).collect()
}
pub fn eq_vec(&self, v: &[bool]) -> bool {
assert_eq!(self.nbits, v.len());
iter::order::eq(self.iter(), v.iter().cloned())
}
pub fn truncate(&mut self, len: usize) {
if len < self.len() {
self.nbits = len;
self.storage.truncate(blocks_for_bits::<B>(len));
self.fix_last_block();
}
}
pub fn reserve(&mut self, additional: usize) {
let desired_cap = self.len().checked_add(additional).expect("capacity overflow");
let storage_len = self.storage.len();
if desired_cap > self.capacity() {
self.storage.reserve(blocks_for_bits::<B>(desired_cap) - storage_len);
}
}
pub fn reserve_exact(&mut self, additional: usize) {
let desired_cap = self.len().checked_add(additional).expect("capacity overflow");
let storage_len = self.storage.len();
if desired_cap > self.capacity() {
self.storage.reserve_exact(blocks_for_bits::<B>(desired_cap) - storage_len);
}
}
#[inline]
pub fn capacity(&self) -> usize {
self.storage.capacity().checked_mul(B::bits()).unwrap_or(usize::MAX)
}
pub fn grow(&mut self, n: usize, value: bool) {
let new_nbits = self.nbits.checked_add(n).expect("capacity overflow");
let new_nblocks = blocks_for_bits::<B>(new_nbits);
let full_value = if value { !B::zero() } else { B::zero() };
let num_cur_blocks = blocks_for_bits::<B>(self.nbits);
if self.nbits % B::bits() > 0 {
let mask = mask_for_bits::<B>(self.nbits);
if value {
let block = &mut self.storage[num_cur_blocks - 1];
*block = *block | !mask;
} else {
}
}
let stop_idx = cmp::min(self.storage.len(), new_nblocks);
for idx in num_cur_blocks..stop_idx {
self.storage[idx] = full_value;
}
if new_nblocks > self.storage.len() {
let to_add = new_nblocks - self.storage.len();
self.storage.extend(repeat(full_value).take(to_add));
}
self.nbits = new_nbits;
self.fix_last_block();
}
pub fn pop(&mut self) -> Option<bool> {
if self.is_empty() {
None
} else {
let i = self.nbits - 1;
let ret = self[i];
self.set(i, false);
self.nbits = i;
if self.nbits % B::bits() == 0 {
self.storage.pop();
}
Some(ret)
}
}
pub fn push(&mut self, elem: bool) {
if self.nbits % B::bits() == 0 {
self.storage.push(B::zero());
}
let insert_pos = self.nbits;
self.nbits = self.nbits.checked_add(1).expect("Capacity overflow");
self.set(insert_pos, elem);
}
#[inline]
pub fn len(&self) -> usize { self.nbits }
pub unsafe fn set_len(&mut self, len: usize) {
self.nbits = len;
}
#[inline]
pub fn is_empty(&self) -> bool { self.len() == 0 }
#[inline]
pub fn clear(&mut self) {
for w in &mut self.storage { *w = B::zero(); }
}
}
impl<B: BitBlock> Default for BitVec<B> {
#[inline]
fn default() -> Self { BitVec::new() }
}
impl<B: BitBlock> FromIterator<bool> for BitVec<B> {
fn from_iter<I: IntoIterator<Item=bool>>(iter: I) -> Self {
let mut ret = BitVec::new();
ret.extend(iter);
ret
}
}
impl<B: BitBlock> Extend<bool> for BitVec<B> {
#[inline]
fn extend<I: IntoIterator<Item=bool>>(&mut self, iterable: I) {
let iterator = iterable.into_iter();
let (min, _) = iterator.size_hint();
self.reserve(min);
for element in iterator {
self.push(element)
}
}
}
impl<B: BitBlock> Clone for BitVec<B> {
#[inline]
fn clone(&self) -> Self {
BitVec { storage: self.storage.clone(), nbits: self.nbits }
}
#[inline]
fn clone_from(&mut self, source: &Self) {
self.nbits = source.nbits;
self.storage.clone_from(&source.storage);
}
}
impl<B: BitBlock> PartialOrd for BitVec<B> {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
iter::order::partial_cmp(self.iter(), other.iter())
}
}
impl<B: BitBlock> Ord for BitVec<B> {
#[inline]
fn cmp(&self, other: &Self) -> Ordering {
iter::order::cmp(self.iter(), other.iter())
}
}
impl<B: BitBlock> fmt::Debug for BitVec<B> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
for bit in self {
try!(write!(fmt, "{}", if bit { 1 } else { 0 }));
}
Ok(())
}
}
impl<B: BitBlock> hash::Hash for BitVec<B> {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.nbits.hash(state);
for elem in self.blocks() {
elem.hash(state);
}
}
}
impl<B: BitBlock> cmp::PartialEq for BitVec<B> {
#[inline]
fn eq(&self, other: &Self) -> bool {
if self.nbits != other.nbits {
return false;
}
self.blocks().zip(other.blocks()).all(|(w1, w2)| w1 == w2)
}
}
impl<B: BitBlock> cmp::Eq for BitVec<B> {}
#[derive(Clone)]
pub struct Iter<'a, B: 'a> {
bit_vec: &'a BitVec<B>,
next_idx: usize,
end_idx: usize,
}
impl<'a, B: BitBlock> Iterator for Iter<'a, B> {
type Item = bool;
#[inline]
fn next(&mut self) -> Option<bool> {
if self.next_idx != self.end_idx {
let idx = self.next_idx;
self.next_idx += 1;
Some(self.bit_vec[idx])
} else {
None
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let rem = self.end_idx - self.next_idx;
(rem, Some(rem))
}
}
impl<'a, B: BitBlock> DoubleEndedIterator for Iter<'a, B> {
#[inline]
fn next_back(&mut self) -> Option<bool> {
if self.next_idx != self.end_idx {
self.end_idx -= 1;
Some(self.bit_vec[self.end_idx])
} else {
None
}
}
}
impl<'a, B: BitBlock> ExactSizeIterator for Iter<'a, B> {}
impl<'a, B: BitBlock> IntoIterator for &'a BitVec<B> {
type Item = bool;
type IntoIter = Iter<'a, B>;
fn into_iter(self) -> Iter<'a, B> {
self.iter()
}
}