From bd009b0d3766600a5be71ad4c29c4dbbf9770088 Mon Sep 17 00:00:00 2001 From: logaritmisk Date: Mon, 18 Dec 2017 17:08:40 +0100 Subject: [PATCH] Initial commit. --- .gitignore | 3 +++ .gitlab-ci.yml | 14 +++++++++++++ Cargo.toml | 6 ++++++ src/lib.rs | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 79 insertions(+) create mode 100644 .gitignore create mode 100644 .gitlab-ci.yml create mode 100644 Cargo.toml create mode 100644 src/lib.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e13de17 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +/target/ + +Cargo.lock diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml new file mode 100644 index 0000000..e92d30c --- /dev/null +++ b/.gitlab-ci.yml @@ -0,0 +1,14 @@ +image: "rust:latest" + +variables: + CARGO_HOME: $CI_PROJECT_DIR/cargo + +test:cargo: + script: + - rustc --version && cargo --version + - time cargo test --verbose --jobs 1 --release + + cache: + paths: + - target/ + - cargo/ diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..9b393a2 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "bit_set" +version = "0.1.0" +authors = ["logaritmisk "] + +[dependencies] diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..331680f --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,56 @@ +pub struct BitSet { + data: Box<[u64]>, +} + +impl BitSet { + pub fn with_capacity(max: usize) -> BitSet { + BitSet { + data: vec![0; max / 64 + if max % 64 == 0 { 0 } else { 1 }].into_boxed_slice() + } + } + + pub fn capacity(&self) -> u64 { + self.data.len() as u64 * 64 + } + + pub fn insert(&mut self, value: usize) { + let block = value / 64 as usize; + let bit = 2u64.pow((value - (block * 64)) as u32); + + self.data[block] |= bit; + } + + pub fn remove(&mut self, value: usize) { + let block = value / 64 as usize; + let bit = 2u64.pow((value - (block * 64)) as u32); + + self.data[block] &= !bit; + } + + pub fn contains(&self, value: usize) -> bool { + let block = value / 64 as usize; + let bit = 2u64.pow((value - (block * 64)) as u32); + + self.data[block] & bit == bit + } +} + + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test() { + let mut set = BitSet::with_capacity(100); + + assert_eq!(set.contains(0), false); + assert_eq!(set.contains(10), false); + + set.insert(0); + set.insert(10); + + assert_eq!(set.contains(0), true); + assert_eq!(set.contains(10), true); + } +}