Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -536,6 +536,23 @@ pub trait BitVector:
/// ```
fn prepend<B: BitVector>(&mut self, prefix: &B);

/// Insert all the bits of the `infix` bit vector at the specified `index`.
/// Will panic if there is not enough capacity and this is a fixed variant.
///
/// ```
/// use bva::{BitVector, Bv};
///
/// let mut a = Bv::from(0b1010u8);
/// a.insert(2, &Bv::ones(2));
/// assert_eq!(a, Bv::from(0b101110u16));
/// ```
fn insert<B: BitVector>(&mut self, index: usize, infix: &B) {
// TODO: could be optimized to avoid multiple allocations
let tmp = self.split_off(index);
self.append(infix);
self.append(&tmp);
}

/// Shift the bits by one to the left.
/// The rightmost bit is set to `bit` and the leftmost bit is returned.
///
Expand Down
36 changes: 36 additions & 0 deletions src/tests/bitvector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -755,6 +755,42 @@ fn prepend_bv() {
prepend_inner::<Bv>(256);
}

fn insert_inner<B: BitVector>(max_capacity: usize) {
let mut rng = thread_rng();
for capacity in 0..max_capacity {
let infix_len = rng.gen_range(0..=max_capacity - capacity);
let insert_pos = rng.gen_range(0..=capacity);
let bv = random_bv::<B>(capacity);
let infix = random_bv::<B>(infix_len);
let mut bv2 = bv.clone();
bv2.insert(insert_pos, &infix);
for i in 0..insert_pos {
assert_eq!(bv.get(i), bv2.get(i));
}
for i in 0..infix_len {
assert_eq!(infix.get(i), bv2.get(insert_pos + i));
}
for i in 0..bv.len() - insert_pos {
assert_eq!(bv.get(insert_pos + i), bv2.get(insert_pos + infix_len + i));
}
}
}

#[test]
fn insert_bvf() {
bvf_inner_unroll_cap!(insert_inner, {u8, u16, u32, u64, u128}, {1, 2, 3, 4, 5});
}

#[test]
fn insert_bvd() {
insert_inner::<Bvd>(256);
}

#[test]
fn insert_bv() {
insert_inner::<Bv>(256);
}

fn shl_inner<B: BitVector>(max_capacity: usize) {
let mut rng = thread_rng();
for capacity in 0..max_capacity {
Expand Down