Created
September 24, 2013 04:29
-
-
Save ldunn/6680374 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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