Skip to content

Instantly share code, notes, and snippets.

@ldunn
Created September 24, 2013 04:29
Show Gist options
  • Save ldunn/6680374 to your computer and use it in GitHub Desktop.
Save ldunn/6680374 to your computer and use it in GitHub Desktop.
use vec;
pub trait BitField {
fn get(&self, index: u8) -> bool;
fn set(&mut self, index: u8, value: bool);
fn ensure_size(&mut self, byte: u8);
}
pub struct U8BitField {
u8s: ~[u8],
alloc: u8
}
impl BitField for U8BitField {
fn set(&mut self, index: u8, value: bool) {
let bit = index % 8;
let idx = index - (bit * 8);
self.ensure_size(idx + 1);
let byte = self.u8s[idx];
if (value) {
self.u8s[idx] = byte | (1 << bit)
} else {
self.u8s[idx] = byte & !((1 << bit) as u8)
}
}
fn get(&self, index: u8) -> bool {
let bit = index % 8;
let idx = index - (bit * 8);
if (self.alloc < idx + 1) {
return false
}
let byte = self.u8s[idx];
(byte & (1 << bit)) > 0
}
fn ensure_size(&mut self, byte: u8) {
unsafe {
while (self.alloc < byte) {
self.u8s.push_fast(0);
self.alloc += 1
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment