nostd_bv/adapter/
bit_concat.rs

1use crate::iter::BlockIter;
2use crate::Bits;
3use crate::BlockType;
4
5/// The result of
6/// [`BitsExt::bit_concat`](../trait.BitsExt.html#method.bit_concat).
7///
8/// The resulting bit vector adapter concatenates the bits of the two underlying
9/// bit-vector-likes.
10#[derive(Debug, Clone)]
11pub struct BitConcat<T, U>(T, U);
12
13impl<T, U> BitConcat<T, U> {
14    pub(crate) fn new(bits1: T, bits2: U) -> Self {
15        BitConcat(bits1, bits2)
16    }
17}
18
19impl<T, U> Bits for BitConcat<T, U>
20where
21    T: Bits,
22    U: Bits<Block = T::Block>,
23{
24    type Block = T::Block;
25
26    fn bit_len(&self) -> u64 {
27        self.0.bit_len() + self.1.bit_len()
28    }
29
30    fn get_bit(&self, position: u64) -> bool {
31        let len0 = self.0.bit_len();
32        if position < len0 {
33            self.0.get_bit(position)
34        } else {
35            self.1.get_bit(position - len0)
36        }
37    }
38
39    fn get_block(&self, position: usize) -> Self::Block {
40        let start_bit = Self::Block::mul_nbits(position);
41        let count = Self::Block::block_bits(self.bit_len(), position);
42        let limit_bit = start_bit + count as u64;
43
44        let len0 = self.0.bit_len();
45        if limit_bit <= len0 {
46            self.0.get_block(position)
47        } else if start_bit < len0 {
48            let block1 = self.0.get_raw_block(position);
49            let block2 = self.1.get_raw_block(0);
50            let size1 = (len0 - start_bit) as usize;
51            let size2 = count - size1;
52            block1.get_bits(0, size1) | (block2.get_bits(0, size2) << size1)
53        } else {
54            self.1.get_bits(start_bit - len0, count)
55        }
56    }
57}
58
59impl<T, U, V> PartialEq<V> for BitConcat<T, U>
60where
61    T: Bits,
62    U: Bits<Block = T::Block>,
63    V: Bits<Block = T::Block>,
64{
65    fn eq(&self, other: &V) -> bool {
66        BlockIter::new(self) == BlockIter::new(other)
67    }
68}
69
70impl_index_from_bits! {
71    impl[T: Bits, U: Bits<Block = T::Block>] Index<u64> for BitConcat<T, U>;
72}
73
74impl_bit_sliceable_adapter! {
75    impl[T: Bits, U: Bits<Block = T::Block>] BitSliceable for BitConcat<T, U>;
76    impl['a, T: Bits, U: Bits<Block = T::Block>] BitSliceable for &'a BitConcat<T, U>;
77}