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
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
//mod tests;

use std::cmp::min;
use std::fmt::{Debug, Display};
use std::io::{BufRead, Cursor, Error, ErrorKind, Read, Result, Seek, SeekFrom};
use std::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign};

pub trait Unit:
    BitAnd<Output = Self>
    + BitAndAssign
    + BitOr<Output = Self>
    + BitOrAssign
    + BitXor<Output = Self>
    + BitXorAssign
    + Sized
    + Copy
    + Clone
    + Debug
    + Display
{
    const SIZE: u8;
    fn unitfrom(val: u128) -> Self;
    fn shr(self, rhs: Self) -> Self;
    fn shl(self, rhs: Self) -> Self;
    fn checked_shr(self, rhs: u32) -> Option<Self>;
    fn checked_shl(self, rhs: u32) -> Option<Self>;
    fn read_bit_at(&self, rhs: u8) -> Option<bool>;

    fn into_u8(self) -> u8;
    fn into_u16(self) -> u16;
    fn into_u32(self) -> u32;
    fn into_u64(self) -> u64;
    fn into_u128(self) -> u128;

    fn into_i8(self) -> i8;
    fn into_i16(self) -> i16;
    fn into_i32(self) -> i32;
    fn into_i64(self) -> i64;
    fn into_i128(self) -> i128;
}

macro_rules! impl_unit {
    ( $( $x:ident, $y:expr ),* ) => {
        $(
            impl Unit for $x {
                const SIZE: u8 = $y;

                fn unitfrom(val: u128) -> $x {
                    val as $x
                }
                fn shr(self, rhs: Self) -> Self {
                    self >> rhs
                }
                fn shl(self, rhs: Self) -> Self {
                    self << rhs
                }
                fn checked_shr(self, rhs: u32) -> Option<Self> {
                    self.checked_shr(rhs)
                }
                fn checked_shl(self, rhs: u32) ->  Option<Self> {
                    self.checked_shl(rhs)
                }
                fn read_bit_at(&self, rhs: u8) -> Option<bool> {
                    let bitpos = 1 as $x;
                    if rhs >= Self::SIZE {
                        None
                    } else {
                        Some(*self & bitpos << rhs as $x > 1)
                    }
                }
                fn into_u8(self) -> u8 { self as u8 }
                fn into_u16(self) -> u16 { self as u16 }
                fn into_u32(self) -> u32 { self as u32 }
                fn into_u64(self) -> u64 { self as u64 }
                fn into_u128(self) -> u128 { self as u128 }

                fn into_i8(self) -> i8 { self as i8 }
                fn into_i16(self) -> i16 { self as i16 }
                fn into_i32(self) -> i32 { self as i32 }
                fn into_i64(self) -> i64 { self as i64 }
                fn into_i128(self) -> i128 { self as i128 }
            }
        )*
    };
}
impl_unit!(
    u8, 8, u16, 16, u32, 32, u64, 64, u128, 128, i8, 8, i16, 16, i32, 32, i64, 64, i128, 128
);

impl Unit for bool {
    const SIZE: u8 = 1;

    fn unitfrom(val: u128) -> bool {
        val > 0
    }
    fn shr(self, rhs: Self) -> Self {
        if rhs {
            false
        } else {
            self
        }
    }
    fn shl(self, rhs: Self) -> Self {
        if rhs {
            false
        } else {
            self
        }
    }
    fn checked_shr(self, rhs: u32) -> Option<Self> {
        if rhs > 0 {
            None
        } else {
            Some(self)
        }
    }
    fn checked_shl(self, rhs: u32) -> Option<Self> {
        if rhs > 0 {
            None
        } else {
            Some(self)
        }
    }
    fn read_bit_at(&self, rhs: u8) -> Option<bool> {
        if rhs > 0 {
            None
        } else {
            Some(*self)
        }
    }
    fn into_u8(self) -> u8 {
        self as u8
    }
    fn into_u16(self) -> u16 {
        self as u16
    }
    fn into_u32(self) -> u32 {
        self as u32
    }
    fn into_u64(self) -> u64 {
        self as u64
    }
    fn into_u128(self) -> u128 {
        self as u128
    }

    fn into_i8(self) -> i8 {
        self as i8
    }
    fn into_i16(self) -> i16 {
        self as i16
    }
    fn into_i32(self) -> i32 {
        self as i32
    }
    fn into_i64(self) -> i64 {
        self as i64
    }
    fn into_i128(self) -> i128 {
        self as i128
    }
}

trait SafeSlice<I> {
    fn slice(&self, x: usize, y: usize) -> Result<&[I]>;
}

impl<'a, I> SafeSlice<I> for &'a [I] {
    fn slice(&self, x: usize, y: usize) -> Result<&[I]> {
        if x > self.len() - 1 {
            return Err(Error::new(
                ErrorKind::InvalidInput,
                format!("slice index starts at {}, but ends at {}", x, self.len()),
            ));
        }
        if y > self.len() {
            Err(Error::new(
                ErrorKind::Other,
                format!(
                    "Out of slice range! y {:?} should be less than {:?}",
                    y,
                    self.len()
                ),
            ))
        } else {
            Ok(&self[x..y])
        }
    }
}

impl<'a, I> SafeSlice<I> for &'a mut [I] {
    fn slice(&self, x: usize, y: usize) -> Result<&[I]> {
        if x > self.len() - 1 {
            return Err(Error::new(
                ErrorKind::InvalidInput,
                format!("slice index starts at {}, but ends at {}", x, self.len()),
            ));
        }
        if y > self.len() {
            Err(Error::new(
                ErrorKind::Other,
                format!(
                    "Out of slice range! y {:?} should be less than {:?}",
                    y,
                    self.len()
                ),
            ))
        } else {
            Ok(&self[x..y])
        }
    }
}

impl<'a, I> SafeSlice<I> for Vec<I> {
    fn slice(&self, x: usize, y: usize) -> Result<&[I]> {
        if x > self.len() - 1 {
            return Err(Error::new(
                ErrorKind::InvalidInput,
                format!("slice index starts at {}, but ends at {}", x, self.len()),
            ));
        }
        if y > self.len() {
            Err(Error::new(
                ErrorKind::Other,
                format!(
                    "Out of slice range! y {:?} should be less than {:?}",
                    y,
                    self.len()
                ),
            ))
        } else {
            Ok(&self[x..y])
        }
    }
}

impl<'a, I> SafeSlice<I> for &'a Vec<I> {
    fn slice(&self, x: usize, y: usize) -> Result<&[I]> {
        if x > self.len() - 1 {
            return Err(Error::new(
                ErrorKind::InvalidInput,
                format!("slice index starts at {}, but ends at {}", x, self.len()),
            ));
        }
        if y > self.len() {
            Err(Error::new(
                ErrorKind::Other,
                format!(
                    "Out of slice range! y {:?} should be less than {:?}",
                    y,
                    self.len()
                ),
            ))
        } else {
            Ok(&self[x..y])
        }
    }
}

impl<'a, I> SafeSlice<I> for &'a mut Vec<I> {
    fn slice(&self, x: usize, y: usize) -> Result<&[I]> {
        if x > self.len() - 1 {
            return Err(Error::new(
                ErrorKind::InvalidInput,
                format!("slice index starts at {}, but ends at {}", x, self.len()),
            ));
        }
        if y > self.len() {
            Err(Error::new(
                ErrorKind::Other,
                format!(
                    "Out of slice range! y {:?} should be less than {:?}",
                    y,
                    self.len()
                ),
            ))
        } else {
            Ok(&self[x..y])
        }
    }
}

trait ForceSlice<I> {
    fn force_slice(&self, x: usize, y: usize) -> Result<&[I]>;
}

impl<'a, I> ForceSlice<I> for &'a [I] {
    fn force_slice(&self, x: usize, y: usize) -> Result<&[I]> {
        if x > self.len() - 1 {
            return Err(Error::new(
                ErrorKind::InvalidInput,
                format!("slice index starts at {}, but ends at {}", x, self.len()),
            ));
        }
        if y > self.len() {
            Ok(&self[x..])
        } else {
            Ok(&self[x..y])
        }
    }
}

impl<'a, I> ForceSlice<I> for &'a mut [I] {
    fn force_slice(&self, x: usize, y: usize) -> Result<&[I]> {
        if x > self.len() - 1 {
            return Err(Error::new(
                ErrorKind::InvalidInput,
                format!("slice index starts at {}, but ends at {}", x, self.len()),
            ));
        }
        if y > self.len() {
            Ok(&self[x..])
        } else {
            Ok(&self[x..y])
        }
    }
}

impl<'a, I> ForceSlice<I> for Vec<I> {
    fn force_slice(&self, x: usize, y: usize) -> Result<&[I]> {
        if x > self.len() - 1 {
            return Err(Error::new(
                ErrorKind::InvalidInput,
                format!("slice index starts at {}, but ends at {}", x, self.len()),
            ));
        }
        if y > self.len() {
            Ok(&self[x..])
        } else {
            Ok(&self[x..y])
        }
    }
}

impl<'a, I> ForceSlice<I> for &'a Vec<I> {
    fn force_slice(&self, x: usize, y: usize) -> Result<&[I]> {
        if x > self.len() - 1 {
            return Err(Error::new(
                ErrorKind::InvalidInput,
                format!("slice index starts at {}, but ends at {}", x, self.len()),
            ));
        }
        if y > self.len() {
            Ok(&self[x..])
        } else {
            Ok(&self[x..y])
        }
    }
}

impl<'a, I> ForceSlice<I> for &'a mut Vec<I> {
    fn force_slice(&self, x: usize, y: usize) -> Result<&[I]> {
        if x > self.len() - 1 {
            return Err(Error::new(
                ErrorKind::InvalidInput,
                format!("slice index starts at {}, but ends at {}", x, self.len()),
            ));
        }
        if y > self.len() {
            Ok(&self[x..])
        } else {
            Ok(&self[x..y])
        }
    }
}

/// A 'BitCursor' wraps an in memory buffer and provides it with a [`Seek`] implementation
/// provided that memory buffer impls the Unit trait
///
/// 'BitCursors' are used in memory buffers, any slice with types implementing Unit,
/// to allow it to read/write sizes of whatever unit implementation you pass in,
/// starting from the current bit position
///
/// It has implementations for some standard library traits such as
/// ['Seek']
/// ['Read']
/// ['BufRead']
///
/// # Examples
/// ```no_run
/// use std::io::{Read, Seek, SeekFrom};
/// use BitCursor;
/// fn read_from_bits() {
///     let data = [
///         false, true, true, false, true, false, true, false, true, true, true, true, false,
///         false, false, true, false, true, true, true, false, true, false, false,
///     ];
///     let mut bcurs = BitCursor::new(&data[..]);
///     let _ = bcurs.seek(SeekFrom::Start(13));
///     let mut buf = vec![0, 0, 0, 0];
///     let amt = bcurs.read(&mut buf).unwrap();
///     assert_eq!(2, amt);
///     assert_eq!(vec![46, 128, 0, 0], Vec::from(buf))
/// }
/// ```
#[derive(Debug, Clone)]
pub struct BitCursor<T> {
    bit_pos: u8,
    cursor: Cursor<T>,
}

impl<T> BitCursor<T> {
    /// Creates a new BitCursor wrapping the provided underlying in-memory buffer.
    ///
    /// Initial position for the bitcursor's unit cursor is 0, similarly the bit position will start at 0
    /// Similarly to std::io::Cursor writing to the Bitcursor starts with overwriting vector content, not appending it!
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use BitCursor;
    ///
    /// let buff = BitCursor::new(Vec::new());
    /// # fn force_inference(_: &BitCursor<Vec<u8>>) {}
    /// # force_inference(&buff);
    /// ```
    pub fn new(data: T) -> BitCursor<T> {
        BitCursor {
            bit_pos: 0,
            cursor: Cursor::new(data),
        }
    }

    /// Consumes the BitCursor, returning the underlying value.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use BitCursor;
    ///
    /// let buff = BitCursor::new(Vec::new());
    /// # fn force_inference(_: &BitCursor<Vec<u8>>) {}
    /// # force_inference(&buff);
    /// ```
    pub fn into_inner(self) -> T {
        self.cursor.into_inner()
    }

    /// Get a reference to the underlying value in this BitCursor
    ///
    /// # Examples
    ///
    /// ```
    /// use BitCursor;
    ///
    /// let buff = BitCursor::new(Vec::new());
    /// # fn force_inference(_: &BitCursor<Vec<u8>>) {}
    /// # force_inference(&buff);
    ///
    /// let reference = buff.get_ref();
    /// ```
    pub fn get_ref(&self) -> &T {
        self.cursor.get_ref()
    }

    /// Gets a mutable reference to the underlying value in this BitCursor.
    ///
    /// Care should be taken to avoid modifying the internal I/O state of the
    /// underlying value as it may corrupt this cursor's position.
    ///
    /// # Examples
    ///
    /// ```
    /// use BitCursor;
    ///
    /// let mut buff = BitCursor::new(Vec::new());
    /// # fn force_inference(_: &BitCursor<Vec<u8>>) {}
    /// # force_inference(&buff);
    ///
    /// let reference = buff.get_mut();
    /// ```
    pub fn get_mut(&mut self) -> &mut T {
        self.cursor.get_mut()
    }

    /// Returns the current position of this BitCursor.
    ///
    /// # Examples
    ///
    /// ```
    /// use BitCursor;
    /// use std::io::prelude::*;
    /// use std::io::SeekFrom;
    ///
    /// let mut buff: BitCursor<Vec<u8>> = BitCursor::new(vec![1, 2, 3, 4, 5]);
    ///
    /// assert_eq!(buff.cur_position(), 0);
    ///
    /// buff.seek(SeekFrom::Current(16)).unwrap();
    /// assert_eq!(buff.cur_position(), 2);
    ///
    /// buff.seek(SeekFrom::Current(-1)).unwrap();
    /// assert_eq!(buff.cur_position(), 1);
    /// ```
    pub fn cur_position(&self) -> u64 {
        self.cursor.position()
    }

    /// Returns the current bit position of this BitCursor.
    ///
    /// # Examples
    ///
    /// ```
    /// use BitCursor;
    /// use std::io::prelude::*;
    /// use std::io::SeekFrom;
    ///
    /// let mut buff: BitCursor<Vec<u8>> = BitCursor::new(vec![1, 2, 3, 4, 5]);
    ///
    /// assert_eq!(buff.bit_position(), 0);
    ///
    /// buff.seek(SeekFrom::Current(16)).unwrap();
    /// assert_eq!(buff.bit_position(), 0);
    ///
    /// buff.seek(SeekFrom::Current(-1)).unwrap();
    /// assert_eq!(buff.bit_position(), 7);
    /// ```
    pub fn bit_position(&self) -> u8 {
        self.bit_pos
    }

    /// Sets the bit position of this BitCursor.
    /// does not wrap to the size of the Unit type
    /// also allows going over the length of the BitCursor
    /// it's recommended to use std::io::Seek
    ///
    /// # Examples
    ///
    /// ```
    /// use BitCursor;
    ///
    /// let mut buff: BitCursor<Vec<u8>> = BitCursor::new(vec![1, 2, 3, 4, 5]);
    ///
    /// assert_eq!(buff.position(), 0);
    ///
    /// buff.set_bit_pos(2);
    /// assert_eq!(buff.bit_position(), 2);
    ///
    /// buff.set_bit_pos(4);
    /// assert_eq!(buff.bit_position(), 4);
    /// ```
    pub fn set_bit_pos(&mut self, new: u8) {
        self.bit_pos = new;
    }

    /// Sets the position of this BitCursor.
    /// also allows going over the length of the BitCursor
    /// it's recommended to use std::io::Seek
    ///
    /// # Examples
    ///
    /// ```
    /// use BitCursor;
    ///
    /// let mut buff: BitCursor<Vec<u8>> = BitCursor::new(vec![1, 2, 3, 4, 5]);
    ///
    /// assert_eq!(buff.cur_position(), 0);
    ///
    /// buff.set_cur_pos(2);
    /// assert_eq!(buff.cur_position(), 2);
    ///
    /// buff.set_cur_pos(4);
    /// assert_eq!(buff.cur_position(), 4);
    /// ```
    pub fn set_cur_pos(&mut self, new: u64) {
        self.cursor.set_position(new);
    }
}

/// The 'ReadBits' trait allows reading bits of size unit (bool, u8, u32, etc.), at the given bit/cursor position
///
/// Implementors of 'ReadBits' are defined by one required method, ['read_bits'].
/// Each call to ['read_bits'] will attempt to read bits of unit size from the source,
/// given the source has enough bits for the unit size, otherwise it returns an Error value
///
/// Note: If the intended use is to grab each byte (size u8), Using an implementor of 'BufRead' will be more efficient.
///
/// # Examples
///
/// Read a u128 from a list of u8's first from bit position 0, and next and bit position 2, and cursor position 1 (8+2 = 10)
///
/// ```no_run
/// use {BitCursor, ReadBits};
/// use std::io::Seek;
/// use std::io::SeekFrom;
///
/// fn main() -> std::io::Result<()> {
///         let data: [u8; 22] = [
///            0b01101010, 0b11110001, 0b01110100, 0b10100001, 0b11100011, 0b11000000, 0b11110001,
///            0b01110100, 0b10100001, 0b11100011, 0b11000000, 0b01101010, 0b11110001, 0b01110100,
///            0b10100001, 0b11100011, 0b11000000, 0b11110001, 0b01110100, 0b10100001, 0b11100011,
///            0b11000000,
///         ];
///         let mut bcurs = BitCursor::new(&data[..]);
///         let r = bcurs.read_bits::<u128>().unwrap();
///         assert_eq!(
///            0b01101010111100010111010010100001111000111100000011110001011101001010000111100011110000000110101011110001011101001010000111100011 as u128,
///            r
///         );
///         let _ = bcurs.seek(SeekFrom::Start(10));
///         let r = bcurs.read_bits::<u128>().unwrap();
///         assert_eq!(
///            0b11000101110100101000011110001111000000111100010111010010100001111000111100000001101010111100010111010010100001111000111100000011 as u128,
///            r
///         );
///         Ok(())
/// }
/// ```
///
/// Read a u8 from a list of u32's
///
/// ```no_run
/// use {BitCursor, ReadBits};
/// use std::io::Seek;
/// use std::io::SeekFrom;
/// fn main() -> std::io::Result<()> {
///         let data: [u32; 3] = [
///             0b10010010001001011000100001101010,
///             0b10010010001001011000100001101010,
///             0b10010010001001011000100001101010,
///         ];
///         let mut bcurs = BitCursor::new(&data[..]);
///         let r = bcurs.read_bits::<u8>().unwrap();
///         assert_eq!(0b10010010 as u8, r);
///         let _ = bcurs.seek(SeekFrom::Start(10));
///         let r = bcurs.read_bits::<u8>().unwrap();
///         assert_eq!(0b10010110 as u8, r);
/// }
/// ```
pub trait ReadBits<T> {
    /// Read the bits of size <T: Unit> starting from the bit position of the cursor
    ///
    /// # Example
    ///
    /// ```no_run
    /// use {BitCursor, ReadBits};
    /// use std::io::Seek;
    /// use std::io::SeekFrom;
    /// fn main() -> std::io::Result<()> {
    ///         let data: [u32; 3] = [
    ///             0b10010010001001011000100001101010,
    ///             0b10010010001001011000100001101010,
    ///             0b10010010001001011000100001101010,
    ///         ];
    ///         let mut bcurs = BitCursor::new(&data[..]);
    ///         let r = bcurs.read_bits::<u8>().unwrap();
    ///         assert_eq!(0b10010010 as u8, r);
    ///         let _ = bcurs.seek(SeekFrom::Start(10));
    ///         let r = bcurs.read_bits::<u8>().unwrap();
    ///         assert_eq!(0b10010110 as u8, r);
    /// }
    /// ```
    fn read_bits<U: Unit>(&mut self) -> Result<U>;
}

macro_rules! impl_readbits {
    ( $( $x:ty),* ) => {
        $(
impl<'a, T: Unit> ReadBits<T> for BitCursor<$x> {
    fn read_bits<U: Unit>(&mut self) -> Result<U> {
        let cpos = self.cur_position() as usize;
        let bpos = self.bit_position();
        let ref_size = T::SIZE;
        let prc_size = U::SIZE;
        let slice_add = if ref_size == 1 { 0 } else { 1 };
        let overlap = ((bpos + prc_size) / ref_size) as usize;
        if overlap > 0 && ((bpos + prc_size) % 8 != 0) || prc_size > ref_size {
            if ref_size >= prc_size {
                let mut ret = T::unitfrom(0);
                for (enumueration, val) in self
                    .get_ref()
                    .slice(cpos, cpos + overlap + slice_add)?
                    .iter()
                    .enumerate()
                {
                    let shifted = match bpos.checked_sub(ref_size * enumueration as u8) {
                        Some(sub) => val.shl(T::unitfrom(sub as u128)),
                        None => {
                            match val.checked_shr(
                                ((bpos as i128) - ((ref_size * enumueration as u8) as i128))
                                    .wrapping_neg() as u32,
                            ) {
                                Some(v) => v,
                                None => T::unitfrom(0),
                            }
                        }
                    };
                    ret |= shifted;
                }
                let _ = self.seek(SeekFrom::Current(prc_size as i64))?;
                match ref_size.checked_sub(prc_size) {
                    Some(sub) => Ok(U::unitfrom((ret.shr(T::unitfrom(sub as u128))).into_u128())),
                    None => Ok(U::unitfrom(ret.into_u128())),
                }
            } else {
                let mut ret = U::unitfrom(0);
                for (enumueration, val) in self
                    .get_ref()
                    .slice(cpos, cpos + overlap + slice_add)?
                    .iter()
                    .enumerate()
                {
                    let val =
                        U::unitfrom(val.into_u128()).shl(U::unitfrom((prc_size - ref_size) as u128));
                    let shifted = match bpos.checked_sub(ref_size * enumueration as u8) {
                        Some(sub) => val.shl(U::unitfrom(sub as u128)),
                        None => {
                            match val.checked_shr(
                                ((bpos as i128) - ((ref_size * enumueration as u8) as i128))
                                    .wrapping_neg() as u32,
                            ) {
                                Some(v) => v,
                                None => U::unitfrom(0),
                            }
                        }
                    };
                    ret |= U::unitfrom(shifted.into_u128());
                }
                let _ = self.seek(SeekFrom::Current(prc_size as i64))?;
                match ref_size.checked_sub(prc_size) {
                    Some(sub) => Ok(ret.shr(U::unitfrom(sub as u128))),
                    None => Ok(ret),
                }
            }
        } else {
            let ret = U::unitfrom(
                match self.get_ref().get(cpos) {
                    Some(v) => v.shr(T::unitfrom((ref_size - prc_size - bpos) as u128)),
                    None => {
                        return Err(Error::new(
                            ErrorKind::InvalidData,
                            "Cursor position outside of slice range",
                        ))
                    }
                }
                .into_u128(),
            );
            let _ = self.seek(SeekFrom::Current(prc_size as i64))?;
            Ok(ret)
        }
    }
}
        )*
    };
}
impl_readbits!(&'a [T], &'a mut [T], Vec<T>, &'a Vec<T>, &'a mut Vec<T>);

impl<'a, T: Unit> ReadBits<T> for BitCursor<T> {
    fn read_bits<U: Unit>(&mut self) -> Result<U> {
        let cpos = self.cur_position();
        let bpos = self.bit_position();
        let ref_size = T::SIZE;
        let prc_size = U::SIZE;
        if cpos > 0 {
            return Err(Error::new(
                ErrorKind::InvalidInput,
                "Cursor position is out of range",
            ));
        } else {
            if prc_size + bpos > ref_size {
                return Err(Error::new(
                    ErrorKind::InvalidInput,
                    format!("Not enough bits in type u{}", ref_size),
                ));
            } else {
                let ret = U::unitfrom(
                    self.get_ref()
                        .shr(T::unitfrom((ref_size - prc_size - bpos) as u128))
                        .into_u128(),
                );
                let _ = self.seek(SeekFrom::Current(prc_size as i64))?;
                Ok(ret)
            }
        }
    }
}

/// The 'ForceReadBits' trait allows reading bits of size unit (bool, u8, u32, etc.), at the given bit/cursor position
///
/// Implementors of 'ForceReadBits' are defined by one required method, ['force_read_bits'].
/// Each call to ['force_read_bits'] will attempt to read bits of unit size from the source,
/// if the source is on the last cursor position but doesn't have enough bits to finish the size of the return value
/// it will push the bits it can fit to the front and return trailing zeros of to fill the unit, if it doesn't have
/// any more units in the list, it will return an error value
///
/// Note: If the intended use is to grab each byte (size u8), Using an implementor of 'BufRead' will be more efficient.
///
/// # Examples
///
/// Read a u8 from a list of bit's first from bit position 0, and next and bit position 0, and cursor position 10
///
/// ```no_run
/// use {BitCursor, ForceReadBits};
/// use std::io::Seek;
/// use std::io::SeekFrom;
///
/// fn main() -> std::io::Result<()> {
///     let data: [bool; 24] = [
///         false, true, true, false, true, false, true, false, true, true, true, true, false,
///         false, false, true, false, true, true, true, false, true, false, false,
///     ];
///     let mut bcurs = BitCursor::new(&data[..]);
///     let r = bcurs.force_read_bits::<u8>().unwrap();
///     assert_eq!(0b01101010 as u8, r);
///     let _ = bcurs.seek(SeekFrom::Start(10));
///     let r = bcurs.force_read_bits::<u8>().unwrap();
///     assert_eq!(0b11000101 as u8, r);
///     Ok(())
/// }
/// ```
///
/// Read a u16 from a list of u128's without enough bits to finish
///
/// ```no_run
/// use {BitCursor, ForceReadBits};
/// use std::io::Seek;
/// use std::io::SeekFrom;
/// fn main() -> std::io::Result<()> {
///     let data: [u128; 3] = [
///         0b10010010001001011000100001101011100100100010010110001000011010101001001000100101100010000110101110010010001001011000100001101010,
///         0b10010010001001011000100001101011100100100010010110001000011010101001001000100101100010000110101010010010001001011000100001101010,
///         0b10010010001001011000100001101011100100100010010110001000011010101001001000100101100010000110101010010010001001011000100001101010,
///     ];
///     let mut bcurs = BitCursor::new(&data[..]);
///     let _ = bcurs.seek(SeekFrom::Start(((3 * 128) as i32 - 15) as u64));
///     let r = bcurs.force_read_bits::<u16>().unwrap();
///     assert_eq!(0b0001000011010100 as u16, r);
///     Ok(())
/// }
/// ```
pub trait ForceReadBits<T> {
    /// Read the bits of size <T: Unit> starting from the bit position of the cursor
    ///
    /// # Example
    ///
    /// Read a u32 from bit's without enough to fill a u32
    ///
    /// ```no_run
    /// use {BitCursor, ForceReadBits};
    /// use std::io::Seek;
    /// use std::io::SeekFrom;
    /// fn main() -> Result<()> {
    ///     let data: [bool; 12] = [
    ///         false, true, true, false, true, false, true, false, true, true, true, true,
    ///     ];
    ///     let mut bcurs = BitCursor::new(&data[..]);
    ///     let _ = bcurs.seek(SeekFrom::Start(10));
    ///     let r = bcurs.force_read_bits::<u32>().unwrap();
    ///     assert_eq!(0b11000000000000000000000000000000 as u32, r);
    ///     Ok(())
    /// }
    /// ```
    fn force_read_bits<U: Unit>(&mut self) -> Result<U>;
}

macro_rules! impl_forcereadbits {
    ( $( $x:ty),* ) => {
        $(
impl<'a, T: Unit> ForceReadBits<T> for BitCursor<$x> {
    fn force_read_bits<U: Unit>(&mut self) -> Result<U> {
        let cpos = self.cur_position() as usize;
        let bpos = self.bit_position();
        let ref_size = T::SIZE;
        let prc_size = U::SIZE;
        let slice_add = if ref_size == 1 { 0 } else { 1 };
        let overlap = ((bpos + prc_size) / ref_size) as usize;
        if overlap > 0 && ((bpos + prc_size) % 8 != 0) || prc_size > ref_size {
            if ref_size >= prc_size {
                let mut ret = T::unitfrom(0);
                for (enumueration, val) in self
                    .get_ref()
                    .force_slice(cpos, cpos + overlap + slice_add)?
                    .iter()
                    .enumerate()
                {
                    let shifted = match bpos.checked_sub(ref_size * enumueration as u8) {
                        Some(sub) => val.shl(T::unitfrom(sub as u128)),
                        None => {
                            match val.checked_shr(
                                ((bpos as i128) - ((ref_size * enumueration as u8) as i128))
                                    .wrapping_neg() as u32,
                            ) {
                                Some(v) => v,
                                None => T::unitfrom(0),
                            }
                        }
                    };
                    ret |= shifted;
                }
                let _ = self.seek(SeekFrom::Current(prc_size as i64))?;
                match ref_size.checked_sub(prc_size) {
                    Some(sub) => Ok(U::unitfrom(ret.shr(T::unitfrom(sub as u128)).into_u128())),
                    None => Ok(U::unitfrom(ret.into_u128())),
                }
            } else {
                let mut ret = U::unitfrom(0);
                for (enumueration, val) in self
                    .get_ref()
                    .force_slice(cpos, cpos + overlap + slice_add)?
                    .iter()
                    .enumerate()
                {
                    let val =
                        U::unitfrom(val.into_u128()).shl(U::unitfrom((prc_size - ref_size) as u128));
                    let shifted = match bpos.checked_sub(ref_size * enumueration as u8) {
                        Some(sub) => val.shl(U::unitfrom(sub as u128)),
                        None => {
                            match val.checked_shr(
                                ((bpos as i128) - ((ref_size * enumueration as u8) as i128))
                                    .wrapping_neg() as u32,
                            ) {
                                Some(v) => v,
                                None => U::unitfrom(0),
                            }
                        }
                    };
                    ret |= U::unitfrom(shifted.into_u128());
                }
                let _ = self.seek(SeekFrom::Current(prc_size as i64))?;
                match ref_size.checked_sub(prc_size) {
                    Some(sub) => Ok(ret.shr(U::unitfrom(sub as u128))),
                    None => Ok(ret),
                }
            }
        } else {
            let ret = U::unitfrom(
                match self.get_ref().get(cpos) {
                    Some(v) => v.shr(T::unitfrom((ref_size - prc_size - bpos) as u128)),
                    None => {
                        return Err(Error::new(
                            ErrorKind::InvalidData,
                            "Cursor position outside of slice range",
                        ))
                    }
                }
                .into_u128(),
            );
            let _ = self.seek(SeekFrom::Current(prc_size as i64))?;
            Ok(ret)
        }
    }
}
        )*
    };
}
impl_forcereadbits!(&'a [T], &'a mut [T], Vec<T>, &'a Vec<T>, &'a mut Vec<T>);

impl<'a, T: Unit> ForceReadBits<T> for BitCursor<T> {
    fn force_read_bits<U: Unit>(&mut self) -> Result<U> {
        let cpos = self.cur_position();
        let bpos = self.bit_position();
        let ref_size = T::SIZE;
        let prc_size = U::SIZE;
        if cpos > 0 {
            return Err(Error::new(
                ErrorKind::InvalidInput,
                "Cursor position is out of range",
            ));
        } else {
            if prc_size + bpos >= ref_size {
                if ref_size >= prc_size {
                    let mut ret = T::unitfrom(0);
                    {
                        let val = self.get_ref();
                        let shifted = val.shl(T::unitfrom(bpos as u128));
                        ret |= shifted;
                    }
                    let _ = self.seek(SeekFrom::Current(prc_size as i64))?;
                    match ref_size.checked_sub(prc_size) {
                        Some(sub) => Ok(U::unitfrom(ret.shr(T::unitfrom(sub as u128)).into_u128())),
                        None => Ok(U::unitfrom(ret.into_u128())),
                    }
                } else {
                    let mut ret = U::unitfrom(0);
                    {
                        let val = U::unitfrom(self.get_ref().into_u128())
                            .shl(U::unitfrom((prc_size - ref_size) as u128));
                        let shifted = val.shl(U::unitfrom(bpos as u128));
                        ret |= U::unitfrom(shifted.into_u128());
                    }
                    let _ = self.seek(SeekFrom::Current(prc_size as i64))?;
                    match ref_size.checked_sub(prc_size) {
                        Some(sub) => Ok(ret.shr(U::unitfrom(sub as u128))),
                        None => Ok(ret),
                    }
                }
            } else {
                let ret = U::unitfrom(
                    self.get_ref()
                        .shr(T::unitfrom((ref_size - prc_size - bpos) as u128))
                        .into_u128(),
                );
                let _ = self.seek(SeekFrom::Current(prc_size as i64))?;
                Ok(ret)
            }
        }
    }
}

macro_rules! impl_seek {
    ( $( $x:ty),* ) => {
        $(
impl<'a, T: Unit> Seek for BitCursor<$x> {
    fn seek(&mut self, pos: SeekFrom) -> Result<u64> {
        // size will always be a byte since we can only do this for Cursor with type &[u8]
        let (base_pos, offset) = match pos {
            SeekFrom::Start(v) => {
                let unitsize = T::SIZE as u64;
                self.bit_pos = (v % unitsize) as u8;
                let seek_to = ((unitsize - self.bit_pos as u64) + v) / unitsize - 1;
                self.set_cur_pos(seek_to);
                return Ok(seek_to);
            }
            SeekFrom::Current(v) => {
                let unitsize = T::SIZE as i128;
                let bits = (self.bit_position() as i128)
                    + (self.cur_position() as i128 * unitsize)
                    + v as i128;
                self.bit_pos = (bits % unitsize) as u8;
                let seek_to = bits / unitsize;
                (self.cur_position(), seek_to - self.cur_position() as i128)
            }
            SeekFrom::End(v) => {
                let unitsize = T::SIZE as i128;
                let bits = (self.bit_position() as i128)
                    + (self.get_ref().len() as i128 * unitsize)
                    + v as i128;
                self.bit_pos = (bits % unitsize) as u8;
                let seek_to = bits / unitsize;
                (
                    self.get_ref().len() as u64,
                    seek_to - self.get_ref().len() as i128,
                )
            }
        };
        let new_pos = if offset >= 0 {
            base_pos.checked_add(offset as u64)
        } else {
            base_pos.checked_sub((offset.wrapping_neg()) as u64)
        };
        match new_pos {
            Some(n) => {
                self.set_cur_pos(n);
                Ok(n)
            }
            None => Err(Error::new(
                ErrorKind::InvalidInput,
                "invalid seek to a negative or overflowing position",
            )),
        }
    }
}
        )*
    };
}
impl_seek!(&'a [T], &'a mut [T], Vec<T>, &'a Vec<T>, &'a mut Vec<T>);

impl<'a, T: Unit> Seek for BitCursor<T> {
    fn seek(&mut self, pos: SeekFrom) -> Result<u64> {
        // size will always be a byte since we can only do this for Cursor with type &[u8]
        let (base_pos, offset) = match pos {
            SeekFrom::Start(v) => {
                let unitsize = T::SIZE as u64;
                self.bit_pos = (v % unitsize) as u8;
                let seek_to = ((unitsize - self.bit_pos as u64) + v) / unitsize - 1;
                self.set_cur_pos(seek_to);
                return Ok(seek_to);
            }
            SeekFrom::Current(v) => {
                let unitsize = T::SIZE as i128;
                let bits = (self.bit_position() as i128)
                    + (self.cur_position() as i128 * unitsize)
                    + v as i128;
                self.bit_pos = (bits % unitsize) as u8;
                let seek_to = bits / unitsize;
                (self.cur_position(), seek_to - self.cur_position() as i128)
            }
            SeekFrom::End(v) => {
                let unitsize = T::SIZE as i128;
                let bits = (self.bit_position() as i128) + (1 as i128 * unitsize) + v as i128;
                self.bit_pos = (bits % unitsize) as u8;
                let seek_to = bits / unitsize;
                (1 as u64, seek_to - 1 as i128)
            }
        };
        let new_pos = if offset >= 0 {
            base_pos.checked_add(offset as u64)
        } else {
            base_pos.checked_sub((offset.wrapping_neg()) as u64)
        };
        match new_pos {
            Some(n) => {
                self.set_cur_pos(n);
                Ok(n)
            }
            None => Err(Error::new(
                ErrorKind::InvalidInput,
                "invalid seek to a negative or overflowing position",
            )),
        }
    }
}

macro_rules! impl_read {
    ( $( $x:ty),* ) => {
        $(
impl<'a, T: Unit> Read for BitCursor<$x> {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
        for i in 0..buf.len() {
            buf[i] = match self.read_bits::<u8>() {
                Ok(val) => val,
                Err(_) => match self.force_read_bits::<u8>() {
                    Ok(val) => val,
                    Err(_) => return Ok(i),
                },
            }
        }
        Ok(buf.len())
    }
}
        )*
    };
}
impl_read!(&'a [T], &'a mut [T], Vec<T>, &'a Vec<T>, &'a mut Vec<T>, T);

macro_rules! impl_bufread {
    ( $( $x:ty),* ) => {
        $(
impl<'a> BufRead for BitCursor<$x>  {
    fn fill_buf(&mut self) -> Result<&[u8]> {
        let amt = min(self.cur_position(), self.get_ref().len() as u64);
        Ok(&self.get_ref()[(amt as usize)..])
    }
    fn consume(&mut self, amt: usize) {
        self.set_cur_pos(amt as u64);
    }
}
        )*
    };
}
impl_bufread!(
    &'a [u8],
    &'a mut [u8],
    Vec<u8>,
    &'a Vec<u8>,
    &'a mut Vec<u8>
);