bitutils2 0.1.5

A package of tools for bit manipulations, including bit indexing, bitfields, and a variation of regular expressions for binary data
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
use std::str::FromStr;

pub use crate::bit_field::BitField;

/// Helper function for initializing [`BitIndex`](crate::BitIndex). Depending on arguments
/// provided, this can be used to initialize a [`BitIndex`](crate::BitIndex) using the bytes,
/// bits, or both. 
///
/// # Examples
///
/// ```rust
/// use bitutils2::{BitIndex, bx};
///
/// // If two integers are provided, then they are interpreted as bytes, bits
/// assert_eq!(bx!(5, 4), BitIndex::new(5, 4));
///
/// // If one integer is provided, then it is interpreted as bytes
/// assert_eq!(bx!(5), BitIndex::new(5, 0));
///
/// // If one integer is provided after a comma, then it is interpreted as bits
/// assert_eq!(bx!(,20), BitIndex::new(2, 4));
/// ```
#[macro_export]
macro_rules! bx {
    ($bytes:expr, $bits:expr) => {
       BitIndex::new($bytes, $bits)
    };
    (, $bits:expr) => {
        BitIndex::bits($bits)
    };
    ($bytes:expr) => {
        BitIndex::bytes($bytes)
    };
}


// #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug)]
// pub struct BitIndex {
//     pub byte_index: usize,
//     pub bit_index: usize
// }

// impl BitIndex {

//     /// Initialize a new [`BitIndex`](crate::BitIndex) that refers to the `bit_index` bit of
//     /// the byte at `byte_index`. `bit_index` should be less than `8`
//     pub fn new(byte_index: usize, bit_index: usize) -> BitIndex {
//         BitIndex {byte_index, bit_index}
//     }

//     /// Returns the bit portion of this [`BitIndex`](crate::BitIndex).
//     pub fn bit(&self) -> usize {
//         self.bit_index
//     }

//     /// Returns the compliment of the bit portion of this [`BitIndex`](crate::BitIndex) (`8 - self.bit()`).
//     pub fn cbit(&self) -> usize {
//         8 - self.bit_index
//     }

//     /// Returns the byte portion of this [`BitIndex`](crate::BitIndex).
//     pub fn byte(&self) -> usize {
//         self.byte_index
//     }

//     /// Sets the bit portion of this [`BitIndex`](crate::BitIndex). `bit` must be less than `8`.
//     pub fn set_bit(&mut self, bit: usize) {
//         self.bit_index = bit;
//     }

//     /// Sets the byte portion of this [`BitIndex`](crate::BitIndex)
//     pub fn set_byte(&mut self, byte: usize) {
//         self.byte_index = byte;
//     }

//     /// Adds `nbits` bits to this [`BitIndex`](crate::BitIndex). The bit and byte portions will
//     /// be adjusted accordingly to ensure that the bit portion is always less than `8`
//     pub fn add_bits(&mut self, nbits: usize) {
//         let bits = self.bit_index + nbits;
//         self.bit_index = bits & 0x07;
//         self.byte_index += bits >> 3;
//     }
// }

// impl std::ops::Add for BitIndex {
//     type Output = Self;

//     fn add(self, other: Self) -> BitIndex {
//         let bits = self.bit() + other.bit();
//         BitIndex {
//             byte_index: self.byte() + other.byte() + (bits >> 3),
//             bit_index: bits & 0x07
//         }
//     }
// }

// impl std::ops::Sub for BitIndex {
//     type Output = Self;

//     fn sub(self, other: Self) -> BitIndex {
//         if self.bit() >= other.bit() {
//             BitIndex {
//                 byte_index: self.byte() - other.byte(),
//                 bit_index: self.bit() - other.bit()
//             }
//         } else {
//             BitIndex {
//                 byte_index: self.byte() - other.byte() - 1,
//                 bit_index: (self.bit() + 8) - other.bit()
//             }
//         }
//     }
// }

use std::ops::Neg;
use std::cmp::Ord;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Sign {
    Negative,
    Positive,
}


impl std::ops::Neg for Sign {
    type Output = Self;

    fn neg(self) -> Self::Output {
        match self {
            Sign::Negative => Sign::Positive,
            Sign::Positive => Sign::Negative,
        }
    }
}

#[derive(Clone, Debug)]
enum BitIndexErrorKind {
    Empty,
    InvalidCharacter(usize),
    Overflow,
    UnitNotPresent
}

#[derive(Clone, Debug)]
pub struct ParseBitIndexError {
    kind: BitIndexErrorKind
}

impl ParseBitIndexError {
    fn new(kind: BitIndexErrorKind) -> ParseBitIndexError {
        ParseBitIndexError {kind}
    }
}

impl std::fmt::Display for ParseBitIndexError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.kind {
            BitIndexErrorKind::Empty => write!(f, "Input is empty"),
            BitIndexErrorKind::InvalidCharacter(i) => write!(f, "Invalid character encountered at position {}", i),
            BitIndexErrorKind::Overflow => write!(f, "Byte or bit value caused overflow"),
            BitIndexErrorKind::UnitNotPresent => write!(f, "No unit indicator (B and/or b) found in input"),
        }
    }    
}

/// Structure for accessing individual bits in any structure that implements [`BitIndexable`](crate::BitIndexable).
///
/// A [`BitIndex`](crate::BitIndex) can be used to address any singular bit in an array of up to `usize` bytes. 
/// This structure uses a `usize` to index the byte portion, and a separate `u8` to index the bit of the
/// selected byte. There is also a sign associated with this structure for arithmetic purposes. Attempting to
/// access a bit at a negative position will cause a panic.
/// 
/// # Examples
///
/// ```rust
/// use bitutils2::{BitIndex, BitIndexable};
///
/// let v = vec![0b01011100, 0b11001100];
/// //                ^               ^
/// //              (0,3)           (1,7)
///
/// let i = BitIndex::new(0, 3);
/// assert_eq!(v.bit_at(&i), 1);
///
/// let i = BitIndex::new(1, 7);
/// assert_eq!(v.bit_at(&i), 0);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BitIndex {
    sign: Sign,
    byte: usize,
    bit: u8
}

impl BitIndex {

    pub const MAX: BitIndex = BitIndex::new(usize::MAX, 7);
    pub const MIN: BitIndex = BitIndex {sign: Sign::Negative, byte: usize::MAX, bit: 7};

    /// Constructs a new [`BitIndex`](crate::BitIndex) with the specified `byte` and `bit` 
    /// values. The sign of the result is positive.
    pub const fn new(byte: usize, bit: u8) -> BitIndex {
        BitIndex {sign: Sign::Positive, byte, bit}
    }

    /// Constructs a new [`BitIndex`](crate::BitIndex) with the specified `byte` value and `bit` 
    /// equal to zero. The sign of the result is positive.
    pub const fn bytes(byte: usize) -> BitIndex {
        BitIndex::new(byte, 0)
    }

    /// Constructs a new [`BitIndex`](crate::BitIndex) with the specified `bit` value and `byte` 
    /// equal to zero. The sign of the result is positive.
    pub const fn bits(bits: usize) -> BitIndex {
        BitIndex::new(bits >> 3, (bits & 0x07) as u8)
    }

    /// Constructs a new [`BitIndex`](crate::BitIndex) with `byte` and `bit` both equal to zero.
    pub const fn zero() -> BitIndex {
        BitIndex::new(0, 0)
    }

    /// Returns true if the byte and bit indices are both zero, regardless of sign.
    pub const fn is_zero(&self) -> bool {
        self.byte == 0 && self.bit == 0
    }

    /// Returns `true` if `self` is positive and `false` if `self` is zero or negative
    pub const fn is_positive(&self) -> bool {
        matches!(self.sign, Sign::Positive) && !self.is_zero()
    }

    /// Returns `true` if `self` is negative and `false` if `self` is zero or positive
    pub const fn is_negative(&self) -> bool {
        matches!(self.sign, Sign::Negative) && !self.is_zero()
    }

    /// Returns `true` if `self` lies on a byte boundary and `false` otherwise. Functionally
    /// equivalent to `self.bit() == 0`
    pub const fn is_byte_boundary(&self) -> bool {
        self.bit == 0
    }

    /// Returns the bit portion of this [`BitIndex`](crate::BitIndex).
    pub const fn byte(&self) -> usize {
        self.byte
    }

    /// Returns the bit portion of this [`BitIndex`](crate::BitIndex).
    pub const fn bit(&self) -> u8 {
        self.bit
    }

    /// Returns the compliment of the bit portion of this [`BitIndex`](crate::BitIndex) (`8 - self.bit()`).
    pub const fn cbit(&self) -> u8 {
        8 - self.bit
    }

    pub const fn total_bits(&self) -> i128 {
        let bits = ((self.byte as i128) << 3) + self.bit as i128;
        match self.sign {
            Sign::Positive => bits,
            Sign::Negative => -bits
        }
    }

    /// Returns a new [`BitIndex`](crate::BitIndex) the corresponds to
    /// the nearest byte boundary greater than or equal to `self`. 
    ///
    /// # Example
    ///
    /// ```rust
    /// use bitutils2::BitIndex;
    ///
    /// assert_eq!(BitIndex::new(4, 2).ceil(), BitIndex::new(5, 0));
    ///
    /// assert_eq!(BitIndex::new(4, 0).ceil(), BitIndex::new(4, 0));
    ///
    /// // Negative case
    /// assert_eq!((-BitIndex::new(1, 2)).ceil(), -BitIndex::new(1, 0));
    ///
    /// ```
    pub fn ceil(&self) -> BitIndex {
        if self.is_byte_boundary() {
            self.clone()
        } else {
            match self.sign {
                Sign::Positive => {
                    BitIndex::new(self.byte() + 1, 0)
                },
                Sign::Negative => {
                    -BitIndex::new(self.byte(), 0)
                }
            }
        }
    }

    /// Returns the absolute value of `self`
    pub const fn abs(&self) -> BitIndex {
        BitIndex::new(self.byte(), self.bit())
    }

    /// Sets the bit portion of this [`BitIndex`](crate::BitIndex). `bit` must be less than `8`.
    pub fn set_bit(&mut self, bit: u8) {
        self.bit = bit;
    }

    /// Sets the byte portion of this [`BitIndex`](crate::BitIndex)
    pub fn set_byte(&mut self, byte: usize) {
        self.byte = byte;
    }

    /// Adds `nbits` bits to this [`BitIndex`](crate::BitIndex). The bit and byte portions will
    /// be adjusted accordingly to ensure that the bit portion is always less than `8`
    pub fn add_bits(&mut self, nbits: usize) {
        *self = *self + nbits;
    }

    pub const fn from_i64_bytes(byte: i64) -> BitIndex {
        if byte < 0 {
            BitIndex {
                sign: Sign::Negative,
                byte: byte.abs() as usize,
                bit: 0
            }
        } else {
            BitIndex {
                sign: Sign::Positive,
                byte: byte as usize,
                bit: 0
            }
        }
    }

    /// Calculates the smallest non-negative value `b` such that `self + b = n * rhs` where `n` 
    /// is an integer. 
    pub fn rem_euclid(&self, rhs: &BitIndex) -> BitIndex {
        let mut lhs_total_bits = self.byte as i128 * 8 + self.bit as i128;
        let mut rhs_total_bits = rhs.byte as i128 * 8 + rhs.bit as i128;

        if matches!(self.sign, Sign::Negative) {
            lhs_total_bits *= -1;
        }

        if matches!(rhs.sign, Sign::Negative) {
            rhs_total_bits *= -1;
        }

        let mut total_bits = lhs_total_bits.rem_euclid(rhs_total_bits);
        if total_bits < 0 {
            total_bits *= -1;
            -BitIndex::new((total_bits >> 3) as usize, (total_bits & 0x07) as u8)
        } else {
            BitIndex::new((total_bits >> 3) as usize, (total_bits & 0x07) as u8)
        }

    }
}

impl Default for BitIndex {
    fn default() -> BitIndex {
        BitIndex::zero()
    }
}

impl FromStr for BitIndex {
    type Err = ParseBitIndexError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut char_iter = s.char_indices().peekable();

        let sign = match char_iter.peek() {
            None => return Err(ParseBitIndexError{kind: BitIndexErrorKind::Empty}),
            Some((_, '-')) => {
                char_iter.next();
                Sign::Negative
            },
            Some((_, '+')) => {
                char_iter.next();
                Sign::Positive
            },
            Some(_) => Sign::Positive
        };

        let mut numeral_found = false;
        let mut b_found = false;
        let mut byte: usize = 0;
        let mut bit: usize = 0;
        let mut acc: usize = 0;
        while let Some((i, ch)) = char_iter.next() {
            match ch {
                '0'..='9' => {
                    acc = acc.checked_mul(10).ok_or(ParseBitIndexError{kind: BitIndexErrorKind::Overflow})?;
                    acc = acc.checked_add(ch as usize - 48).ok_or(ParseBitIndexError{kind: BitIndexErrorKind::Overflow})?;
                    numeral_found = true;
                },
                'B' if numeral_found && !b_found => {
                    b_found = true;
                    numeral_found = false;
                    byte = acc;
                    acc = 0;
                },
                'b' if numeral_found => {
                    b_found = true;
                    bit = acc;
                    break;
                },
                _ => {
                    return Err(ParseBitIndexError{kind: BitIndexErrorKind::InvalidCharacter(i)});
                }

            }
        }

        if let Some((i, _)) = char_iter.next() {
            Err(ParseBitIndexError{kind: BitIndexErrorKind::InvalidCharacter(i)})
        } else if !b_found {
            Err(ParseBitIndexError{kind: BitIndexErrorKind::UnitNotPresent})
        } else {
            byte = byte.checked_add(bit >> 3).ok_or(ParseBitIndexError{kind: BitIndexErrorKind::Overflow})?;
            let bit = (bit & 0b111) as u8;

            Ok(BitIndex{sign, byte, bit})
        }

    }
}

impl std::fmt::Display for BitIndex {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        let temp_str = format!("{}B{}b", self.byte(), self.bit());
        f.pad_integral(!self.is_negative(), "", &temp_str)
    }
}

impl std::cmp::PartialOrd for BitIndex {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl std::cmp::Ord for BitIndex {
    fn cmp(&self, other: &BitIndex) -> std::cmp::Ordering {
        match (&self.sign, &other.sign) {
            (Sign::Positive, Sign::Positive) => {
                match self.byte.cmp(&other.byte) {
                    std::cmp::Ordering::Equal => {
                        self.bit.cmp(&other.bit)
                    },
                    other_cmp => other_cmp
                }
            },
            (Sign::Positive, Sign::Negative) => {
                std::cmp::Ordering::Greater
            },
            (Sign::Negative, Sign::Negative) => {
                std::cmp::Ordering::Less
            },
            (Sign::Negative, Sign::Positive) => {
                (-self).cmp(&-other).reverse()
            }
        }
    }
}

impl std::ops::Neg for BitIndex {
    type Output = BitIndex;
    fn neg(self) -> Self::Output {
        BitIndex {
            sign: -self.sign, 
            byte: self.byte, 
            bit: self.bit
        }
    }
}

impl std::ops::Neg for &BitIndex {
    type Output = BitIndex;
    fn neg(self) -> Self::Output {
        BitIndex {
            sign: -self.sign.clone(), 
            byte: self.byte, 
            bit: self.bit
        }
    }
}

impl std::ops::Add<BitIndex> for BitIndex {
    type Output = BitIndex;
    fn add(self, rhs: BitIndex) -> Self::Output {
        match (&self.sign, &rhs.sign) {
            (Sign::Positive, Sign::Positive) => {
                let bits = self.bit as usize + rhs.bit as usize;
                BitIndex::new(self.byte + rhs.byte + bits / 8, (bits % 8) as u8)
            },
            (Sign::Positive, Sign::Negative) => {
                // 5B2b - 4B3b
                let bits = self.bit as i64 - rhs.bit as i64;
                let mut lhs_byte = self.byte;
                let mut rhs_byte = rhs.byte;
                if bits >= 0 {
                    lhs_byte += bits as usize / 8;
                } else {
                    rhs_byte += bits.abs() as usize / 8;
                };

                if lhs_byte > rhs_byte {
                    if bits >= 0 {
                        BitIndex::new(lhs_byte - rhs_byte, (bits % 8) as u8)
                    } else {
                        BitIndex::new(lhs_byte - rhs_byte - 1, ((bits + 8) % 8) as u8)
                    }
                    
                } else if lhs_byte < rhs_byte {
                    if bits <= 0 {
                        -BitIndex::new(rhs_byte - lhs_byte, (bits.abs() % 8) as u8)
                    } else {
                        -BitIndex::new(rhs_byte - (lhs_byte + 1), ((bits - 8).abs() % 8) as u8)
                    }
                } else {
                    if bits < 0 {
                        -BitIndex::new(0, (bits.abs() % 8) as u8)
                    } else {
                        BitIndex::new(0, (bits % 8) as u8)
                    }
                }
            },
            (Sign::Negative, Sign::Negative) => {
                (self.neg() + rhs.neg()).neg()
            },
            (Sign::Negative, Sign::Positive) => {
                (self.neg() + rhs.neg()).neg()
            },
        }
        
    }
}

impl std::ops::Sub<BitIndex> for BitIndex {
    type Output = BitIndex;
    fn sub(self, rhs: BitIndex) -> Self::Output {
        self + -rhs
        
    }
}

impl<'a, 'b> std::ops::Add<&'a BitIndex> for &'b BitIndex {
    type Output = BitIndex;
    fn add(self, rhs: &'a BitIndex) -> Self::Output {
        self.clone() + rhs.clone()
        
    }
}

impl<'a, 'b> std::ops::Sub<&'a BitIndex> for &'b BitIndex {
    type Output = BitIndex;
    fn sub(self, rhs: &'a BitIndex) -> Self::Output {
        self.clone() + (-rhs).clone()
        
    }
}

impl std::ops::Add<usize> for BitIndex {
    type Output = Self;

    fn add(self, other: usize) -> BitIndex {
        return self + BitIndex::bits(other as usize)
    }
}

impl std::ops::Add<&usize> for BitIndex {
    type Output = Self;

    fn add(self, other: &usize) -> BitIndex {
        return self + BitIndex::bits(*other as usize)
    }
}

// impl std::ops::Add<usize> for BitIndex {
//     type Output = Self;

//     fn add(self, other: usize) -> BitIndex {
//         let bits = self.bit() + other;
//         BitIndex {
//             byte_index: self.byte() + (bits >> 3),
//             bit_index: bits & 0x07
//         }
//     }
// }

// impl std::ops::Add<&usize> for BitIndex {
//     type Output = Self;

//     fn add(self, other: &usize) -> BitIndex {
//         let bits = self.bit() + other;
//         BitIndex {
//             byte_index: self.byte() + (bits >> 3),
//             bit_index: bits & 0x07
//         }
//     }
// }

impl std::ops::AddAssign<usize> for BitIndex {

    fn add_assign(&mut self, other: usize) {
        *self = *self + other
    }
}

impl std::ops::AddAssign<&usize> for BitIndex {

    fn add_assign(&mut self, other: &usize) {
        *self = *self + other
    }
}

impl std::ops::AddAssign<BitIndex> for BitIndex {

    fn add_assign(&mut self, other: BitIndex) {
        *self = *self + other
    }
}

impl std::ops::AddAssign<&BitIndex> for BitIndex {

    fn add_assign(&mut self, other: &BitIndex) {
        *self = *self + *other
    }
}

// impl std::ops::AddAssign<usize> for BitIndex {

//     fn add_assign(&mut self, other: usize) {
//         let bits = self.bit_index + other;
//         self.bit_index = bits & 0x07;
//         self.byte_index += bits >> 3;
//     }
// }

// impl std::ops::AddAssign<&usize> for BitIndex {

//     fn add_assign(&mut self, other: &usize) {
//         let bits = self.bit_index + other;
//         self.bit_index = bits & 0x07;
//         self.byte_index += bits >> 3;
//     }
// }

impl std::ops::Mul<i128> for BitIndex {
    type Output = Self;

    // Required method
    fn mul(self, rhs: i128) -> Self::Output {
        let total_bits = self.total_bits() * rhs;
        if total_bits < 0 {
            -BitIndex::new((total_bits.abs() >> 3) as usize, (total_bits.abs() & 0x07) as u8)
        } else {
            BitIndex::new((total_bits >> 3) as usize, (total_bits & 0x07) as u8)
        }
        

    }
}


impl std::ops::Div<&BitIndex> for BitIndex {
    type Output = i128;

    /// Performs integer division between `self` and `rhs`. Returns the largest integer
    /// by which `self` can be multiplied such that `self <= rhs`. Output is negative if
    /// exactly one of the inputs is negative. Panics if `rhs` is zero.
    ///
    /// # Example
    ///
    /// ```rust
    /// use bitutils2::BitIndex;
    ///
    /// assert_eq!(BitIndex::new(4, 2) / &BitIndex::new(2, 1), 2);
    /// assert_eq!(BitIndex::new(4, 1) / &BitIndex::new(2, 1), 1);
    /// assert_eq!(BitIndex::new(403, 2) / &BitIndex::new(100, 0), 4);
    ///
    /// // Negative case
    /// assert_eq!(-BitIndex::new(4, 2) / &BitIndex::new(2, 1), -2);
    /// assert_eq!(-BitIndex::new(4, 2) / &-BitIndex::new(2, 1), 2);
    ///
    /// ```
    fn div(self, rhs: &BitIndex) -> Self::Output {

        self.total_bits() / rhs.total_bits()
        
    }
}

pub trait BitIndexable {

    /// Get the bit at the given bit index. Returns a `u8` instead of a `bool` to accommodate 
    /// operations such as bitshifts on the result, but this function should always return either `0` or `1`.
    fn bit_at(&self, index: &BitIndex) -> u8;

    fn bit_slice(&self, start: &BitIndex, end: &BitIndex) -> BitField;

    /// Get the bit index that is equivalent to the length of the structure (accessing at this index 
    /// is out of bounds, but any index below this is allowed)
    fn max_index(&self) -> BitIndex;
}

impl<T: BitIndexable> BitIndexable for &T {
    fn bit_at(&self, index: &BitIndex) -> u8 {
        (*self).bit_at(index)
    }

    fn bit_slice(&self, start: &BitIndex, end: &BitIndex) -> BitField {
        (*self).bit_slice(start, end)
    }

    fn max_index(&self) -> BitIndex {
        (*self).max_index()
    }
}

impl BitIndexable for Vec<u8> {

    fn bit_at(&self, index: &BitIndex) -> u8 {
        if index.is_negative() {
            panic!("Bit index underflow")
        }
        (self[index.byte()] & (0xf0 >> index.bit())) >> (7 - index.bit())
    }

    fn bit_slice(&self, start: &BitIndex, end: &BitIndex) -> BitField {
        if start.is_negative() || end.is_negative() {
            panic!("Bit index underflow")
        }
        // This is the same implementation as the BitField bit_slice method. If you change this, consider changing the other one
        let start_byte = start.byte();
        let start_bit = start.bit();
        let end_byte = end.byte();
        let end_bit = end.bit();

        let mut res = Vec::<u8>::new();

        if start_bit == 0 {
            res = self[start_byte..end_byte].to_vec();
        } else {
            for i in start_byte..end_byte {
                let carry = if i + 1 < self.len() {self[i+1] >> (8 - start_bit)} else {0};
                res.push((self[i] << start_bit) | carry);
            }
        }
        match start_bit.cmp(&end_bit) {
            std::cmp::Ordering::Greater => {
                let res_len = res.len();
                let last = res[res_len - 1];
                res[res_len - 1] = (last >> (start_bit - end_bit)) << (start_bit - end_bit);
            },
            std::cmp::Ordering::Less => {
                res.push((self[end_byte] >> (8 - end_bit)) << (start_bit + 8 - end_bit));
            },
            _ => ()
        }
        BitField::new(res, *end - *start)
    }

    fn max_index(&self) -> BitIndex {
        BitIndex::new(self.len(), 0)
    }
}

#[cfg(test)]
mod bit_index_tests {
    use super::*;

    #[test]
    fn bx_test() {
        assert_eq!(bx!(10, 3), BitIndex::new(10, 3));
        assert_eq!(bx!(10), BitIndex::new(10, 0));
        assert_eq!(bx!(,10), BitIndex::new(1, 2));
    }

    #[test]
    fn display_test() {
        assert_eq!(format!("{}", BitIndex::new(5, 3)), "5B3b");
        assert_eq!(format!("{}", BitIndex::new(185, 7)), "185B7b");
        assert_eq!(format!("{}", -BitIndex::new(5, 3)), "-5B3b");
        assert_eq!(format!("{}", -BitIndex::new(185, 7)), "-185B7b");

        assert_eq!(format!("{:-}", BitIndex::new(5, 3)), "5B3b");
        assert_eq!(format!("{:-}", BitIndex::new(185, 7)), "185B7b");
        assert_eq!(format!("{:-}", -BitIndex::new(5, 3)), "-5B3b");
        assert_eq!(format!("{:-}", -BitIndex::new(185, 7)), "-185B7b");

        assert_eq!(format!("{:+}", BitIndex::new(5, 3)), "+5B3b");
        assert_eq!(format!("{:+}", BitIndex::new(185, 7)), "+185B7b");
        assert_eq!(format!("{:+}", -BitIndex::new(5, 3)), "-5B3b");
        assert_eq!(format!("{:+}", -BitIndex::new(185, 7)), "-185B7b");

        assert_eq!(format!("{:0>8}", BitIndex::new(5, 3)), "00005B3b");
        assert_eq!(format!("{:0>08}", -BitIndex::new(5, 3)), "-0005B3b");
        assert_eq!(format!("{:0>-08}", BitIndex::new(5, 3)), "00005B3b");
        assert_eq!(format!("{:0>-08}", -BitIndex::new(5, 3)), "-0005B3b");
    }

    #[test]
    fn parse_test() {
        assert_eq!(BitIndex::new(15, 4), BitIndex::from_str("15B4b").unwrap());
        assert_eq!(BitIndex::new(1300, 4), BitIndex::from_str("1300B4b").unwrap());
        assert_eq!(BitIndex::new(0, 4), BitIndex::from_str("4b").unwrap());
        assert_eq!(BitIndex::new(5, 5), BitIndex::from_str("45b").unwrap());
        assert_eq!(BitIndex::new(4, 0), BitIndex::from_str("4B").unwrap());
        assert_eq!(BitIndex::new(0, 0), BitIndex::from_str("0B").unwrap());
        assert_eq!(BitIndex::new(15, 3), BitIndex::from_str("10B43b").unwrap());
        assert_eq!(-BitIndex::new(15, 3), BitIndex::from_str("-10B43b").unwrap());
        assert_eq!(BitIndex::new(15, 3), BitIndex::from_str("+10B43b").unwrap());

        let max_case = format!("{}B{}b", usize::MAX, 7);
        assert_eq!(BitIndex::new(usize::MAX, 7), BitIndex::from_str(&max_case).unwrap());
    }

    #[test]
    fn parse_errors_test() {
        // Empty input
        let err_kind = BitIndex::from_str("").unwrap_err().kind;
        assert!(matches!(err_kind, BitIndexErrorKind::Empty));

        // Input without units
        let err_kind = BitIndex::from_str("23").unwrap_err().kind;
        assert!(matches!(err_kind, BitIndexErrorKind::UnitNotPresent));

        // Overflow in byte value
        let overflow_1 = format!("{}B{}b", usize::MAX as u128 + 1, 0);
        let err_kind = BitIndex::from_str(&overflow_1).unwrap_err().kind;
        assert!(matches!(err_kind, BitIndexErrorKind::Overflow));

        // Overflow in bit value
        let overflow_2 = format!("{}B{}b", 0, usize::MAX as u128 * 8 + 1);
        let err_kind = BitIndex::from_str(&overflow_2).unwrap_err().kind;
        assert!(matches!(err_kind, BitIndexErrorKind::Overflow));

        // Overflow in byte value after carrying bits
        let overflow_3 = format!("{}B{}b", usize::MAX, 8);
        let err_kind = BitIndex::from_str(&overflow_3).unwrap_err().kind;
        assert!(matches!(err_kind, BitIndexErrorKind::Overflow));

        // Invalid character in various locations
        let err_kind = BitIndex::from_str("1xB43b").unwrap_err().kind;
        assert!(matches!(err_kind, BitIndexErrorKind::InvalidCharacter(1)));
        let err_kind = BitIndex::from_str("10BB43b").unwrap_err().kind;
        assert!(matches!(err_kind, BitIndexErrorKind::InvalidCharacter(3)));
        let err_kind = BitIndex::from_str("10B4x3b").unwrap_err().kind;
        assert!(matches!(err_kind, BitIndexErrorKind::InvalidCharacter(4)));
        let err_kind = BitIndex::from_str("10B43b_").unwrap_err().kind;
        assert!(matches!(err_kind, BitIndexErrorKind::InvalidCharacter(6)));
        let err_kind = BitIndex::from_str("10B43B").unwrap_err().kind;
        assert!(matches!(err_kind, BitIndexErrorKind::InvalidCharacter(5)));
        let err_kind = BitIndex::from_str("10b43B").unwrap_err().kind;
        assert!(matches!(err_kind, BitIndexErrorKind::InvalidCharacter(3)));
        let err_kind = BitIndex::from_str("B43b").unwrap_err().kind;
        assert!(matches!(err_kind, BitIndexErrorKind::InvalidCharacter(0)));
        let err_kind = BitIndex::from_str("b").unwrap_err().kind;
        assert!(matches!(err_kind, BitIndexErrorKind::InvalidCharacter(0)));
        let err_kind = BitIndex::from_str("10Bb").unwrap_err().kind;
        assert!(matches!(err_kind, BitIndexErrorKind::InvalidCharacter(3)));
    }

    #[test]
    fn total_bits_test() {
        assert_eq!(BitIndex::new(3, 6).total_bits(), 30);
        assert_eq!((-BitIndex::new(3, 6)).total_bits(), -30);
    }

    #[test]
    fn add_test() {
        assert_eq!(BitIndex::new(2, 3) + BitIndex::new(1, 3), BitIndex::new(3, 6));
        assert_eq!(BitIndex::new(0, 3) + BitIndex::new(4, 5), BitIndex::new(5, 0));
        assert_eq!(BitIndex::new(0, 6) + BitIndex::new(4, 5), BitIndex::new(5, 3));
        assert_eq!(BitIndex::new(5, 1) + BitIndex::new(3, 2), BitIndex::new(8, 3));
        assert_eq!(BitIndex::new(5, 1) + BitIndex::new(3, 7), BitIndex::new(9, 0));
        assert_eq!(BitIndex::new(5, 3) + BitIndex::new(3, 7), BitIndex::new(9, 2));
    }

    #[test]
    fn sub_test() {
        assert_eq!(BitIndex::new(3, 6) - BitIndex::new(1, 3), BitIndex::new(2, 3));
        assert_eq!(BitIndex::new(6, 3) - BitIndex::new(2, 3), BitIndex::new(4, 0));
        assert_eq!(BitIndex::new(3, 2) - BitIndex::new(1, 5), BitIndex::new(1, 5));
        assert_eq!(BitIndex::new(2, 2) - BitIndex::new(1, 6), BitIndex::new(0, 4));
        assert_eq!(BitIndex::new(5, 1) - BitIndex::new(3, 2), BitIndex::new(1, 7));
        assert_eq!(BitIndex::new(5, 5) - BitIndex::new(5, 2), BitIndex::new(0, 3));
        assert_eq!(BitIndex::new(5, 2) - BitIndex::new(5, 5), -BitIndex::new(0, 3));
        assert_eq!(BitIndex::new(3, 2) - BitIndex::new(5, 5), -BitIndex::new(2, 3));
        assert_eq!(BitIndex::new(3, 5) - BitIndex::new(5, 3), -BitIndex::new(1, 6));
    }

    #[test]
    fn mul_test() {
        assert_eq!(BitIndex::new(3, 6) * 15, BitIndex::new(56, 2));
        assert_eq!(BitIndex::new(0, 0) * 1000, BitIndex::new(0, 0));
        assert_eq!(BitIndex::new(15, 1) * 1000, BitIndex::new(15125, 0));
        assert_eq!(BitIndex::new(15, 1) * -1000, -BitIndex::new(15125, 0));
        assert_eq!((-BitIndex::new(15, 1)) * 1000, -BitIndex::new(15125, 0));
        assert_eq!((-BitIndex::new(15, 1)) * -1000, BitIndex::new(15125, 0));
    }

    #[test]
    fn rem_euclid_test() {
        assert_eq!(BitIndex::new(3, 6).rem_euclid(&BitIndex::new(1, 3)), BitIndex::new(1, 0));
        assert_eq!(BitIndex::new(6, 3).rem_euclid(&BitIndex::new(2, 3)), BitIndex::new(1, 5));
        assert_eq!(BitIndex::new(3, 2).rem_euclid(&BitIndex::new(1, 5)), BitIndex::zero());
        assert_eq!(BitIndex::new(2, 2).rem_euclid(&BitIndex::new(1, 6)), BitIndex::new(0, 4));
        assert_eq!((-BitIndex::new(3, 6)).rem_euclid(&BitIndex::new(1, 3)), BitIndex::new(0, 3));
        assert_eq!((-BitIndex::new(6, 3)).rem_euclid(&BitIndex::new(2, 3)), BitIndex::new(0, 6));
        assert_eq!((-BitIndex::new(3, 2)).rem_euclid(&BitIndex::new(1, 5)), BitIndex::zero());
        assert_eq!((-BitIndex::new(2, 2)).rem_euclid(&BitIndex::new(1, 6)), BitIndex::new(1, 2));
    }

    #[test]
    fn comparisons() {
        assert!(BitIndex::new(5, 4) == BitIndex::new(5, 4));
        assert!(BitIndex::new(5, 4) <= BitIndex::new(5, 4));
        assert!(BitIndex::new(5, 4) >= BitIndex::new(5, 4));
        assert!(BitIndex::new(5, 4) != BitIndex::new(6, 3));
        assert!(BitIndex::new(6, 4) != BitIndex::new(6, 3));
        assert!(BitIndex::new(5, 4) < BitIndex::new(6, 3));
        assert!(BitIndex::new(5, 4) <= BitIndex::new(6, 3));
        assert!(BitIndex::new(5, 4) < BitIndex::new(6, 3));
        assert!(BitIndex::new(6, 4) > BitIndex::new(6, 3));
        assert!(BitIndex::new(6, 4) >= BitIndex::new(6, 3));

        assert!(BitIndex::new(6, 4) + 1 == BitIndex::new(6, 5));
        assert!(BitIndex::new(6, 4) + 12 == BitIndex::new(8, 0));
        assert!(BitIndex::new(6, 4) + BitIndex::new(0, 4) == BitIndex::new(7, 0));
        assert!(BitIndex::new(6, 4) + BitIndex::new(2, 7) == BitIndex::new(9, 3));
    }

    #[test]
    fn indexing_u8() {
        let v = vec![0b01010101, 0b00110011, 0b00001111];
        let mut index = BitIndex::new(0, 0);
        assert_eq!(v.bit_at(&index), 0);
        index += 1;
        assert_eq!(v.bit_at(&index), 1);
        index += 1;
        assert_eq!(v.bit_at(&index), 0);
        index += 5;
        assert_eq!(v.bit_at(&index), 1);
        index += 4;
        assert_eq!(v.bit_at(&index), 1);
        index += 1;
        assert_eq!(v.bit_at(&index), 0);
        index += 9;
        assert_eq!(v.bit_at(&index), 1);
        index += 1;
        assert_eq!(v.bit_at(&index), 1);
    }
}