bitman/
bits.rs

1use core::{
2    fmt::{self, Debug, Display},
3    ops::{Deref, DerefMut},
4    slice::SliceIndex,
5};
6use core::{
7    mem::size_of,
8    ops::{
9        Add, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Index, IndexMut, Mul,
10        Not, Shl, Shr,
11    },
12};
13extern crate alloc;
14use alloc::borrow::ToOwned;
15use alloc::format;
16use alloc::string::String;
17use alloc::vec;
18use alloc::vec::Vec;
19use num_traits::{CheckedShl, One, Zero};
20
21use crate::bit::Bit;
22use crate::BitMan;
23
24#[cfg(test)]
25mod bits_tests;
26
27#[derive(Debug, Default, PartialEq, Eq, Hash, Clone)]
28pub struct Bits {
29    inner: Vec<Bit>,
30}
31
32impl Bits {
33    #[inline]
34    #[must_use] pub fn new(inner_vector_of_bits: &[Bit]) -> Self {
35        return Self {
36            inner: inner_vector_of_bits.to_owned(),
37        }
38    }
39
40    #[inline]
41    #[must_use] pub fn to_be_bytes(&self) -> Vec<u8> {
42        let mut bytes: Vec<u8> = Vec::new();
43        let length = self.len();
44        let mut current_length = 0usize;
45        loop {
46            let mut bits: Vec<Bit> = Vec::new();
47            for (count, bit) in self.inner.iter().enumerate() {
48                bits.push(*bit);
49                if count % 8 == 0 {
50                    bytes.push(u8::from(&Self::new(&bits)));
51                    current_length += 8;
52                }
53            }
54            if current_length >= length {
55                break;
56            }
57        }
58        bytes
59    }
60
61    #[inline]
62    #[must_use] pub fn to_le_bytes(&self) -> Vec<u8> {
63        self.to_be_bytes().into_iter().rev().collect()
64    }
65
66    #[inline]
67    #[must_use] pub fn to_le_bytes_of_le_bits(&self) -> Vec<u8> {
68        let mut vec_u8 = self.to_be_bytes_of_le_bits();
69        vec_u8.reverse();
70        vec_u8
71    }
72
73    #[inline]
74    #[must_use] pub fn to_be_bytes_of_le_bits(&self) -> Vec<u8> {
75        let mut bytes: Vec<u8> = Vec::new();
76        let length = self.len();
77        let mut current_length = 0usize;
78        loop {
79            let mut bits: Vec<Bit> = Vec::new();
80            for (count, bit) in self.inner.iter().enumerate() {
81                bits.push(*bit);
82                if count >= 7 {
83                    bits.reverse();
84                    break;
85                }
86            }
87            bytes.push(u8::from(&Self::new(&bits)));
88            current_length += 8;
89            if current_length >= length {
90                break;
91            }
92        }
93        bytes
94    }
95
96    #[inline]
97    #[must_use] pub fn from_be_bytes(slice_of_bytes: &[u8]) -> Self {
98        let mut bits = Self::new(&[]);
99        for current_u8 in slice_of_bytes {
100            bits.append(&mut current_u8.bits().inner);
101        }
102        bits
103    }
104
105    #[inline]
106    #[must_use] pub fn from_le_bytes(slice_of_bytes: &[u8]) -> Self {
107        let mut vec_of_bytes: Vec<u8> = Vec::from(slice_of_bytes);
108        vec_of_bytes.reverse();
109        return Self::from_be_bytes(&vec_of_bytes)
110    }
111
112    #[inline]
113    #[must_use] pub fn from_le_bytes_of_le_bits(slice_of_bytes: &[u8]) -> Self {
114        let mut vec_of_bytes: Vec<u8> = Vec::from(slice_of_bytes);
115        vec_of_bytes.reverse();
116        return Self::from_be_bytes_of_le_bits(&mut vec_of_bytes)
117    }
118
119    #[inline]
120    pub fn from_be_bytes_of_le_bits(slice_of_bytes: &mut [u8]) -> Self {
121        let mut vec_of_bits: Vec<Bit> = Vec::new();
122        for current_u8 in slice_of_bytes {
123            let mut current_u8_as_bits: Self = Self::new(&Self::from(*current_u8).inner);
124            vec_of_bits.append(&mut current_u8_as_bits);
125        }
126        return Self::new(&Vec::new())
127    }
128}
129
130impl Deref for Bits {
131    type Target = Vec<Bit>;
132
133    #[inline]
134    fn deref(&self) -> &Self::Target {
135        &self.inner
136    }
137}
138
139impl DerefMut for Bits {
140    #[inline]
141    fn deref_mut(&mut self) -> &mut Self::Target {
142        &mut self.inner
143    }
144}
145
146impl Display for Bits {
147    #[inline]
148    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
149        let mut output = String::new();
150        let mut index_counter = 0usize;
151        while let Some(bit) = self.get(index_counter) {
152            output = format!("{output} {bit:?}");
153            index_counter += 1;
154        }
155        return write!(formatter, "Bits({output})")
156    }
157}
158
159impl BitAnd for Bits {
160    type Output = Self;
161
162    #[inline]
163    fn bitand(self, rhs: Self) -> Self {
164        let mut new_bits = Self { inner: Vec::new() };
165        let mut index_counter = 0usize;
166        while let Some(bit_from_self) = self.get(index_counter) {
167            if let Some(bit_from_rhs) = rhs.get(index_counter) {
168                new_bits.push(*bit_from_self & *bit_from_rhs);
169                index_counter += 1;
170            } else {
171                break;
172            }
173        }
174        new_bits
175    }
176}
177
178impl BitAndAssign for Bits {
179    #[inline]
180    fn bitand_assign(&mut self, rhs: Self) {
181        let mut index_counter = 0usize;
182        let old_self = self.clone();
183        while let Some(bit_from_self) = old_self.get(index_counter) {
184            if let Some(bit_from_rhs) = rhs.get(index_counter) {
185                self.set_bit(&(index_counter as u32), &(*bit_from_self & *bit_from_rhs));
186                index_counter += 1;
187            } else {
188                break;
189            }
190        }
191    }
192}
193
194impl BitOr for Bits {
195    type Output = Self;
196
197    #[inline]
198    fn bitor(self, rhs: Self) -> Self {
199        let mut new_bits = Self { inner: Vec::new() };
200        let mut index_counter = 0usize;
201        while let Some(bit_from_self) = self.get(index_counter) {
202            if let Some(bit_from_rhs) = rhs.get(index_counter) {
203                new_bits.push(*bit_from_self | *bit_from_rhs);
204                index_counter += 1;
205            } else {
206                break;
207            }
208        }
209        new_bits
210    }
211}
212
213impl BitOrAssign for Bits {
214    #[inline]
215    fn bitor_assign(&mut self, rhs: Self) {
216        for index in 0..self.len() {
217            if let Some(rhs_bit) = rhs.get(index) {
218                self.inner[index] |= *rhs_bit;
219            }
220        }
221    }
222}
223
224impl BitXor for Bits {
225    type Output = Self;
226
227    #[inline]
228    fn bitxor(self, rhs: Self) -> Self {
229        let mut new_bits = Self { inner: Vec::new() };
230        let mut index_counter = 0usize;
231        while let Some(bit_from_self) = self.get(index_counter) {
232            if let Some(bit_from_rhs) = rhs.get(index_counter) {
233                new_bits.push(*bit_from_self ^ *bit_from_rhs);
234                index_counter += 1;
235            } else {
236                break;
237            }
238        }
239        new_bits
240    }
241}
242
243impl BitXorAssign for Bits {
244    #[inline]
245    fn bitxor_assign(&mut self, rhs: Self) {
246        for index in 0..self.len() {
247            if let Some(rhs_bit) = rhs.get(index) {
248                self[index] ^= *rhs_bit;
249            }
250        }
251    }
252}
253
254impl<Idx> Index<Idx> for Bits
255where
256    Idx: SliceIndex<[Bit]>,
257{
258    type Output = Idx::Output;
259
260    #[inline]
261    fn index(&self, index: Idx) -> &Self::Output {
262        return self.get(index).unwrap()
263    }
264}
265
266impl<Idx> IndexMut<Idx> for Bits
267where
268    Idx: SliceIndex<[Bit]>,
269{
270    #[inline]
271    fn index_mut(&mut self, index: Idx) -> &mut Self::Output {
272        return self.get_mut(index).unwrap()
273    }
274}
275
276impl Not for Bits {
277    type Output = Self;
278
279    #[inline]
280    fn not(self) -> Self::Output {
281        let mut new_bits = Self { inner: Vec::new() };
282        for index in 0..self.len() {
283            if self.get(index).unwrap().0 {
284                new_bits.push(Bit(true));
285            } else {
286                new_bits.push(Bit(false));
287            }
288        }
289        new_bits
290    }
291}
292
293impl Shl<u32> for &Bits {
294    type Output = Bits;
295
296    fn shl(self, rhs: u32) -> Self::Output {
297        return self.clone() << rhs
298    }
299}
300
301impl Shl<usize> for Bits {
302    type Output = Self;
303
304    #[inline]
305    fn shl(mut self, rhs: usize) -> Self {
306        drop(self.drain(..rhs));
307        for _ in 0..rhs {
308            self.push(Bit(false));
309        }
310        self
311    }
312}
313
314impl Shl<u32> for Bits {
315    type Output = Self;
316
317    #[inline]
318    fn shl(mut self, rhs: u32) -> Self {
319        drop(self.drain(..rhs as usize));
320        for _ in 0..rhs {
321            self.push(Bit(false));
322        }
323        self
324    }
325}
326
327impl Shr<usize> for Bits {
328    type Output = Self;
329
330    #[inline]
331    fn shr(mut self, rhs: usize) -> Self::Output {
332        drop(self.inner.drain(..rhs));
333        for _ in 0..rhs {
334            self.inner.push(Bit(false));
335        }
336        self
337    }
338}
339
340impl Shr<u32> for Bits {
341    type Output = Self;
342
343    #[inline]
344    fn shr(mut self, rhs: u32) -> Self::Output {
345        drop(self.inner.drain(..rhs as usize));
346        for _ in 0..rhs {
347            self.inner.push(Bit(false));
348        }
349        self
350    }
351}
352
353impl CheckedShl for Bits {
354    #[inline]
355    fn checked_shl(&self, rhs: u32) -> Option<Self> {
356        if rhs > self.bit_len() as u32 {
357            None
358        } else {
359            Some(self << rhs)
360        }
361    }
362}
363
364impl Zero for Bits {
365    #[inline]
366    fn zero() -> Self {
367        return Self::new(&vec![Bit(false); size_of::<Self>() * 8])
368    }
369
370    #[inline]
371    fn is_zero(&self) -> bool {
372        self.inner.iter().all(|&x| !x.0)
373    }
374}
375
376impl One for Bits {
377    #[inline]
378    fn one() -> Self {
379        let mut output = Self::new(&vec![Bit(false); size_of::<Self>() * 8]);
380        output.set_bit(&((size_of::<Self>()) as u32 * 7), &Bit(true));
381        output
382    }
383
384    #[inline]
385    fn is_one(&self) -> bool
386    where
387        Self: PartialEq,
388    {
389        (self
390            .get(0..self.inner.len() - 1)
391            .unwrap()
392            .iter()
393            .all(|&x| !x.0)
394            || self.inner.len() == 1)
395            && self.get(self.inner.len()).unwrap().0
396    }
397}
398
399impl Mul for Bits {
400    type Output = Self;
401
402    #[inline]
403    fn mul(self, rhs: Self) -> Self::Output {
404        let output_as_u128: u128 = u128::from(&self) * u128::from(&rhs);
405        Self::Output::from(output_as_u128)
406    }
407}
408
409impl BitMan for Bits {
410    #[inline]
411    fn bit_len(&self) -> usize {
412        (*self).len()
413    }
414
415    #[inline]
416    fn bit(&self, index: &u32) -> Bit {
417        self[*index as usize]
418    }
419
420    #[inline]
421    default fn set_bit(&mut self, index: &u32, bit: &Bit) {
422        self[*index as usize] = *bit;
423    }
424
425    #[inline]
426    default fn bits(&self) -> Bits {
427        self.clone()
428    }
429
430    #[inline]
431    default fn set_bits(&mut self, mut index: u32, bits: &Bits) {
432        for bit in bits.iter() {
433            self[index as usize] = *bit;
434            index += 1;
435        }
436    }
437}
438
439impl Iterator for Bits {
440    type Item = Bit;
441    fn next(&mut self) -> Option<Self::Item> {
442        self.inner.pop()
443    }
444}
445
446#[macro_export]
447macro_rules! impl_to_and_from_bits {
448    ($($new_type:ty$(,)?)*) => {$(
449        impl From<&Bits> for $new_type {
450            #[inline]
451            fn from(bits_to_convert: &Bits) -> $new_type {
452                #[allow(clippy::manual_bits)] if bits_to_convert.bit_len() > size_of::<$new_type>() * 8 {
453                    let shortened_bits: Bits = Bits{
454                        inner: bits_to_convert.get((bits_to_convert.inner.len() - size_of::<$new_type>())..bits_to_convert.inner.len()).unwrap()
455                            .to_vec()
456                    };
457                    <$new_type>::from(&shortened_bits)
458                } else {
459                    let mut new_value: $new_type = Default::default();
460                    for (index, current_bit) in bits_to_convert.iter().enumerate() {
461                        new_value.set_bit(&(index as u32), &current_bit);
462                    }
463                    if bits_to_convert.inner.len() < size_of::<$new_type>() {
464                        new_value >>= size_of::<$new_type>() - bits_to_convert.inner.len();
465                    }
466                    new_value
467                }
468            }
469        }
470        impl From<$new_type> for Bits {
471            #[inline]
472            fn from<'a>(value_to_convert: $new_type) -> Bits {
473                let mut output_value: Bits = Default::default();
474                for index in 0..size_of::<$new_type>() {
475                    output_value.inner.push(value_to_convert.bit(&(index as u32)));
476                }
477                output_value
478            }
479        })*
480    }
481}
482
483impl_to_and_from_bits!(u8, u16, u32, u64, u128, usize, Bit);
484
485impl Add for Bits {
486    type Output = Self;
487
488    #[inline]
489    fn add(self, rhs: Self) -> Self::Output {
490        let mut output_value: Self::Output = Default::default();
491        let mut carry = false;
492        for index in self.inner.len()..0 {
493            if !self.get(index).unwrap().0 {
494                if carry {
495                    if !rhs.get(index).unwrap().0 {
496                        carry = false;
497                    }
498                    output_value.inner.push(Bit(true));
499                } else {
500                    output_value.inner.push(*rhs.get(index).unwrap());
501                }
502            } else {
503                if rhs.get(index).unwrap().0 {
504                    carry = true;
505                }
506                output_value.inner.push(!*rhs.get(index).unwrap());
507            }
508        }
509        output_value.inner.reverse();
510        output_value
511    }
512}