Skip to content

Instantly share code, notes, and snippets.

@mocobeta
Created December 13, 2020 04:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mocobeta/84aa3ea41e3274af6f200ff1864cc06c to your computer and use it in GitHub Desktop.
Save mocobeta/84aa3ea41e3274af6f200ff1864cc06c to your computer and use it in GitHub Desktop.
gamma code in Rust
// https://crates.io/crates/bit-vec
use bit_vec::BitVec;
pub fn encode_gamma(li: &[usize]) -> BitVec {
fn encode(k: usize) -> BitVec {
let body_len: usize = ((k as f64).log2().floor() as usize) + 1;
let body = BitVec::from_bytes(&k.to_be_bytes());
let mut bv = BitVec::from_elem(body_len * 2 - 1, false);
// set selector bit
bv.set(body_len - 1, true);
// set body bits
let mut pos = body_len;
let mut i = body.len() - body_len + 1;
while pos < bv.len() {
if let Some(b) = body.get(i) {
bv.set(pos, b);
}
pos += 1;
i += 1;
}
bv
}
let mut bv_all = BitVec::new();
for &k in li {
let bv = encode(k);
let mut offset = bv_all.len();
bv_all.grow(bv.len(), false);
for bit in bv.iter() {
bv_all.set(offset, bit);
offset += 1;
}
}
bv_all
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment