Set variable to BitSlice in Rust

57 Views Asked by At

I am using the Rust bitvec crate to generate bit strings for a toy application involving zlib compression. I have the following code for adding a bit string corresponding to a specific code point to a BitVec. I would like to be able to refer to the bit string using a variable, but that does not seem to be possible. Is there a better way to do this?

use bitvec::prelude::*;

fn main() {
    let mut compressed = bitvec![u8, Lsb0;];
    let code_point = 127u8; // Arbitrary code point.

    // Ok, but awkward
    println!("{}",&(0b00110000u32 + code_point as u32).view_bits::<Msb0>()[32 - 8..]);
    compressed.extend(&(0b00110000u32 + code_point as u32).view_bits::<Msb0>()[32 - 8..]);

    //Won't compile: creates a temporary value which is freed while still in use
    let code = &(0b00110000u32 + code_point as u32).view_bits::<Msb0>()[32 - 8..];
    println!("{}", code);
    compressed.extend(code);

    //Won't compile: doesn't have a size known at compile-time
    let code = (0b00110000u32 + code_point as u32).view_bits::<Msb0>()[32 - 8..];
    println!("{}", code);
    compressed.extend(&code);
}

Also, it would be nicer to be able to use Lsb0 with [..N], but the reverse() method cannot be chained.

--- EDIT ---

The actual case where I need this is slightly more complex than the above and looks something like this:

// This works
if code_point < 144 {
  compressed.extend(&(0b00110000u32 + code_point as u32).view_bits::<Msb0>()[32 - 8..])
} else {
  compressed.extend(&(0b110010000u32 + (code_point - 144) as u32).view_bits::<Msb0>()[32 - 9..])
};

// But I would like to write something like this:
let code = if code_point < 144 {
  &(0b00110000u32 + code_point as u32).view_bits::<Msb0>()[32 - 8..]
} else {
  &(0b110010000u32 + (code_point - 144) as u32).view_bits::<Msb0>()[32 - 9..]
};
compressed.extend(code);
1

There are 1 best solutions below

3
orlp On BEST ANSWER

You can assign the temporary to a variable to extend its lifetime:

let value = 0b00110000u32 + code_point as u32;
let code = &value.view_bits::<Msb0>()[32 - 8..];

Alternatively, since