Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BitVec incorrectly appends 0s instead of 1s

I am a beginner at Rust. I am trying to use the BitVec library to represent an array of bits. I started playing with it by appending sequences of 0s or 1s, but I am having some problems at doing so. When I append a sequence of x 0s then a sequence of y 1s, what it does instead is to append x+y zeroes. Note that if I just append 1s without appending 0s before, it works. Here is my code:

extern crate bit_vec;
use bit_vec::BitVec;

fn main(){
    let mut bits = BitVec::new();   // creates an empty array of bits
    append_zero(&mut bits);
    append_one(&mut bits);
    append_zero(&mut bits);
    append_one(&mut bits);
    append_one(&mut bits);          // everything works perfectly till here
    append_n_ones(&mut bits, 2);    // this works
    append_n_zeroes(&mut bits, 3);  // this too
    append_n_ones(&mut bits, 2);    // this appends 2 zeroes instead!
    println!("{:?}", bits);
}

fn append_zero(vector: &mut BitVec) {
    vector.push(false);
}

fn append_one(vector: &mut BitVec) {
    vector.push(true);
}

fn append_n_zeroes(vector: &mut BitVec, n: usize) {
    let mut to_append = BitVec::from_elem(n, false);  // creates a BitVec with n 0s
    println!("trying to append: {:?}", to_append);
    vector.append(&mut to_append);
}

fn append_n_ones(vector: &mut BitVec, n: usize) {
    let mut to_append = BitVec::from_elem(n, true);  // creates a BitVec with n 1s
    println!("trying to append: {:?}", to_append);
    vector.append(&mut to_append);
}

This is the output:

trying to append: 11
trying to append: 000
trying to append: 11
010111100000

Note that the last line should have been 010111100011. Moreover, before appending it, 11 is correctly printed. But then it appends 00.

I am using this website to test my Rust code, but locally it has the same problems. I tried to look at the code for the BitVec library but it is too advanced for my level of Rust at the moment.

like image 388
Xito Dev Avatar asked Mar 03 '23 00:03

Xito Dev


1 Answers

The bit_vec crate, while old and popular, is in maintenance-only. I am the author of a replacement, bitvec, which behaves as you desire and (in my opinion) is a better product.

You can use your code as-written by replacing bit_vec with bitvec and BitVec::from_elem with BitVec::<Lsb0, usize>::repeat. Unfortunately, bitvec is not available on the Rust playground, so I can't show you directly.

like image 174
myrrlyn Avatar answered Mar 10 '23 10:03

myrrlyn