bitman 2.0.1

An easy to use bit manipulation library for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
use core::{
    fmt::{self, Debug, Display},
    ops::{Deref, DerefMut},
    slice::SliceIndex,
};
use core::{
    mem::size_of,
    ops::{
        Add, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Index, IndexMut, Mul,
        Not, Shl, Shr,
    },
};
extern crate alloc;
use alloc::borrow::ToOwned;
use alloc::format;
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
use num_traits::{CheckedShl, One, Zero};

use crate::bit::Bit;
use crate::BitMan;

#[cfg(test)]
mod bits_tests;

#[derive(Debug, Default, PartialEq, Eq, Hash, Clone)]
pub struct Bits {
    inner: Vec<Bit>,
}

impl Bits {
    #[inline]
    #[must_use] pub fn new(inner_vector_of_bits: &[Bit]) -> Self {
        return Self {
            inner: inner_vector_of_bits.to_owned(),
        }
    }

    #[inline]
    #[must_use] pub fn to_be_bytes(&self) -> Vec<u8> {
        let mut bytes: Vec<u8> = Vec::new();
        let length = self.len();
        let mut current_length = 0usize;
        loop {
            let mut bits: Vec<Bit> = Vec::new();
            for (count, bit) in self.inner.iter().enumerate() {
                bits.push(*bit);
                if count % 8 == 0 {
                    bytes.push(u8::from(&Self::new(&bits)));
                    current_length += 8;
                }
            }
            if current_length >= length {
                break;
            }
        }
        bytes
    }

    #[inline]
    #[must_use] pub fn to_le_bytes(&self) -> Vec<u8> {
        self.to_be_bytes().into_iter().rev().collect()
    }

    #[inline]
    #[must_use] pub fn to_le_bytes_of_le_bits(&self) -> Vec<u8> {
        let mut vec_u8 = self.to_be_bytes_of_le_bits();
        vec_u8.reverse();
        vec_u8
    }

    #[inline]
    #[must_use] pub fn to_be_bytes_of_le_bits(&self) -> Vec<u8> {
        let mut bytes: Vec<u8> = Vec::new();
        let length = self.len();
        let mut current_length = 0usize;
        loop {
            let mut bits: Vec<Bit> = Vec::new();
            for (count, bit) in self.inner.iter().enumerate() {
                bits.push(*bit);
                if count >= 7 {
                    bits.reverse();
                    break;
                }
            }
            bytes.push(u8::from(&Self::new(&bits)));
            current_length += 8;
            if current_length >= length {
                break;
            }
        }
        bytes
    }

    #[inline]
    #[must_use] pub fn from_be_bytes(slice_of_bytes: &[u8]) -> Self {
        let mut bits = Self::new(&[]);
        for current_u8 in slice_of_bytes {
            bits.append(&mut current_u8.bits().inner);
        }
        bits
    }

    #[inline]
    #[must_use] pub fn from_le_bytes(slice_of_bytes: &[u8]) -> Self {
        let mut vec_of_bytes: Vec<u8> = Vec::from(slice_of_bytes);
        vec_of_bytes.reverse();
        return Self::from_be_bytes(&vec_of_bytes)
    }

    #[inline]
    #[must_use] pub fn from_le_bytes_of_le_bits(slice_of_bytes: &[u8]) -> Self {
        let mut vec_of_bytes: Vec<u8> = Vec::from(slice_of_bytes);
        vec_of_bytes.reverse();
        return Self::from_be_bytes_of_le_bits(&mut vec_of_bytes)
    }

    #[inline]
    pub fn from_be_bytes_of_le_bits(slice_of_bytes: &mut [u8]) -> Self {
        let mut vec_of_bits: Vec<Bit> = Vec::new();
        for current_u8 in slice_of_bytes {
            let mut current_u8_as_bits: Self = Self::new(&Self::from(*current_u8).inner);
            vec_of_bits.append(&mut current_u8_as_bits);
        }
        return Self::new(&Vec::new())
    }
}

impl Deref for Bits {
    type Target = Vec<Bit>;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl DerefMut for Bits {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}

impl Display for Bits {
    #[inline]
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut output = String::new();
        let mut index_counter = 0usize;
        while let Some(bit) = self.get(index_counter) {
            output = format!("{output} {bit:?}");
            index_counter += 1;
        }
        return write!(formatter, "Bits({output})")
    }
}

impl BitAnd for Bits {
    type Output = Self;

    #[inline]
    fn bitand(self, rhs: Self) -> Self {
        let mut new_bits = Self { inner: Vec::new() };
        let mut index_counter = 0usize;
        while let Some(bit_from_self) = self.get(index_counter) {
            if let Some(bit_from_rhs) = rhs.get(index_counter) {
                new_bits.push(*bit_from_self & *bit_from_rhs);
                index_counter += 1;
            } else {
                break;
            }
        }
        new_bits
    }
}

impl BitAndAssign for Bits {
    #[inline]
    fn bitand_assign(&mut self, rhs: Self) {
        let mut index_counter = 0usize;
        let old_self = self.clone();
        while let Some(bit_from_self) = old_self.get(index_counter) {
            if let Some(bit_from_rhs) = rhs.get(index_counter) {
                self.set_bit(&(index_counter as u32), &(*bit_from_self & *bit_from_rhs));
                index_counter += 1;
            } else {
                break;
            }
        }
    }
}

impl BitOr for Bits {
    type Output = Self;

    #[inline]
    fn bitor(self, rhs: Self) -> Self {
        let mut new_bits = Self { inner: Vec::new() };
        let mut index_counter = 0usize;
        while let Some(bit_from_self) = self.get(index_counter) {
            if let Some(bit_from_rhs) = rhs.get(index_counter) {
                new_bits.push(*bit_from_self | *bit_from_rhs);
                index_counter += 1;
            } else {
                break;
            }
        }
        new_bits
    }
}

impl BitOrAssign for Bits {
    #[inline]
    fn bitor_assign(&mut self, rhs: Self) {
        for index in 0..self.len() {
            if let Some(rhs_bit) = rhs.get(index) {
                self.inner[index] |= *rhs_bit;
            }
        }
    }
}

impl BitXor for Bits {
    type Output = Self;

    #[inline]
    fn bitxor(self, rhs: Self) -> Self {
        let mut new_bits = Self { inner: Vec::new() };
        let mut index_counter = 0usize;
        while let Some(bit_from_self) = self.get(index_counter) {
            if let Some(bit_from_rhs) = rhs.get(index_counter) {
                new_bits.push(*bit_from_self ^ *bit_from_rhs);
                index_counter += 1;
            } else {
                break;
            }
        }
        new_bits
    }
}

impl BitXorAssign for Bits {
    #[inline]
    fn bitxor_assign(&mut self, rhs: Self) {
        for index in 0..self.len() {
            if let Some(rhs_bit) = rhs.get(index) {
                self[index] ^= *rhs_bit;
            }
        }
    }
}

impl<Idx> Index<Idx> for Bits
where
    Idx: SliceIndex<[Bit]>,
{
    type Output = Idx::Output;

    #[inline]
    fn index(&self, index: Idx) -> &Self::Output {
        return self.get(index).unwrap()
    }
}

impl<Idx> IndexMut<Idx> for Bits
where
    Idx: SliceIndex<[Bit]>,
{
    #[inline]
    fn index_mut(&mut self, index: Idx) -> &mut Self::Output {
        return self.get_mut(index).unwrap()
    }
}

impl Not for Bits {
    type Output = Self;

    #[inline]
    fn not(self) -> Self::Output {
        let mut new_bits = Self { inner: Vec::new() };
        for index in 0..self.len() {
            if self.get(index).unwrap().0 {
                new_bits.push(Bit(true));
            } else {
                new_bits.push(Bit(false));
            }
        }
        new_bits
    }
}

impl Shl<u32> for &Bits {
    type Output = Bits;

    fn shl(self, rhs: u32) -> Self::Output {
        return self.clone() << rhs
    }
}

impl Shl<usize> for Bits {
    type Output = Self;

    #[inline]
    fn shl(mut self, rhs: usize) -> Self {
        drop(self.drain(..rhs));
        for _ in 0..rhs {
            self.push(Bit(false));
        }
        self
    }
}

impl Shl<u32> for Bits {
    type Output = Self;

    #[inline]
    fn shl(mut self, rhs: u32) -> Self {
        drop(self.drain(..rhs as usize));
        for _ in 0..rhs {
            self.push(Bit(false));
        }
        self
    }
}

impl Shr<usize> for Bits {
    type Output = Self;

    #[inline]
    fn shr(mut self, rhs: usize) -> Self::Output {
        drop(self.inner.drain(..rhs));
        for _ in 0..rhs {
            self.inner.push(Bit(false));
        }
        self
    }
}

impl Shr<u32> for Bits {
    type Output = Self;

    #[inline]
    fn shr(mut self, rhs: u32) -> Self::Output {
        drop(self.inner.drain(..rhs as usize));
        for _ in 0..rhs {
            self.inner.push(Bit(false));
        }
        self
    }
}

impl CheckedShl for Bits {
    #[inline]
    fn checked_shl(&self, rhs: u32) -> Option<Self> {
        if rhs > self.bit_len() as u32 {
            None
        } else {
            Some(self << rhs)
        }
    }
}

impl Zero for Bits {
    #[inline]
    fn zero() -> Self {
        return Self::new(&vec![Bit(false); size_of::<Self>() * 8])
    }

    #[inline]
    fn is_zero(&self) -> bool {
        self.inner.iter().all(|&x| !x.0)
    }
}

impl One for Bits {
    #[inline]
    fn one() -> Self {
        let mut output = Self::new(&vec![Bit(false); size_of::<Self>() * 8]);
        output.set_bit(&((size_of::<Self>()) as u32 * 7), &Bit(true));
        output
    }

    #[inline]
    fn is_one(&self) -> bool
    where
        Self: PartialEq,
    {
        (self
            .get(0..self.inner.len() - 1)
            .unwrap()
            .iter()
            .all(|&x| !x.0)
            || self.inner.len() == 1)
            && self.get(self.inner.len()).unwrap().0
    }
}

impl Mul for Bits {
    type Output = Self;

    #[inline]
    fn mul(self, rhs: Self) -> Self::Output {
        let output_as_u128: u128 = u128::from(&self) * u128::from(&rhs);
        Self::Output::from(output_as_u128)
    }
}

impl BitMan for Bits {
    #[inline]
    fn bit_len(&self) -> usize {
        (*self).len()
    }

    #[inline]
    fn bit(&self, index: &u32) -> Bit {
        self[*index as usize]
    }

    #[inline]
    default fn set_bit(&mut self, index: &u32, bit: &Bit) {
        self[*index as usize] = *bit;
    }

    #[inline]
    default fn bits(&self) -> Bits {
        self.clone()
    }

    #[inline]
    default fn set_bits(&mut self, mut index: u32, bits: &Bits) {
        for bit in bits.iter() {
            self[index as usize] = *bit;
            index += 1;
        }
    }
}

impl Iterator for Bits {
    type Item = Bit;
    fn next(&mut self) -> Option<Self::Item> {
        self.inner.pop()
    }
}

#[macro_export]
macro_rules! impl_to_and_from_bits {
    ($($new_type:ty$(,)?)*) => {$(
        impl From<&Bits> for $new_type {
            #[inline]
            fn from(bits_to_convert: &Bits) -> $new_type {
                #[allow(clippy::manual_bits)] if bits_to_convert.bit_len() > size_of::<$new_type>() * 8 {
                    let shortened_bits: Bits = Bits{
                        inner: bits_to_convert.get((bits_to_convert.inner.len() - size_of::<$new_type>())..bits_to_convert.inner.len()).unwrap()
                            .to_vec()
                    };
                    <$new_type>::from(&shortened_bits)
                } else {
                    let mut new_value: $new_type = Default::default();
                    for (index, current_bit) in bits_to_convert.iter().enumerate() {
                        new_value.set_bit(&(index as u32), &current_bit);
                    }
                    if bits_to_convert.inner.len() < size_of::<$new_type>() {
                        new_value >>= size_of::<$new_type>() - bits_to_convert.inner.len();
                    }
                    new_value
                }
            }
        }
        impl From<$new_type> for Bits {
            #[inline]
            fn from<'a>(value_to_convert: $new_type) -> Bits {
                let mut output_value: Bits = Default::default();
                for index in 0..size_of::<$new_type>() {
                    output_value.inner.push(value_to_convert.bit(&(index as u32)));
                }
                output_value
            }
        })*
    }
}

impl_to_and_from_bits!(u8, u16, u32, u64, u128, usize, Bit);

impl Add for Bits {
    type Output = Self;

    #[inline]
    fn add(self, rhs: Self) -> Self::Output {
        let mut output_value: Self::Output = Default::default();
        let mut carry = false;
        for index in self.inner.len()..0 {
            if !self.get(index).unwrap().0 {
                if carry {
                    if !rhs.get(index).unwrap().0 {
                        carry = false;
                    }
                    output_value.inner.push(Bit(true));
                } else {
                    output_value.inner.push(*rhs.get(index).unwrap());
                }
            } else {
                if rhs.get(index).unwrap().0 {
                    carry = true;
                }
                output_value.inner.push(!*rhs.get(index).unwrap());
            }
        }
        output_value.inner.reverse();
        output_value
    }
}