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
//! bit-struct

#![no_std]

use core::fmt::{Debug, Display, Formatter};
use core::marker::PhantomData;
use core::ops::{BitAnd, BitOrAssign, BitXorAssign, Shl, ShlAssign, Shr, ShrAssign};
use num_traits::{Bounded, Num};

/// A struct which allows for getting/setting a given property
pub struct GetSet<'a, P, T, const START: usize, const STOP: usize> {
    /// The referenced bitfield type.
    parent: &'a mut P,
    /// The type in the get/set operations
    _phantom: PhantomData<T>,
}

impl<'a, P, T, const START: usize, const STOP: usize> GetSet<'a, P, T, START, STOP> {
    pub fn start(&self) -> usize {
        START
    }

    pub fn stop(&self) -> usize {
        STOP
    }
}

/// A trait which defines how many bits are needed to store a struct.
///
/// # Safety
/// Define `Num` as `{i,u}{8,16,32,64,128}`.
/// - when calling `core::mem::transmute` on `Self`, only bits [0, COUNT) can be non-zero
/// - TryFrom<Num> produces Some(x) <=> core::mem::transmute(num) produces a valid Self(x)
/// - TryFrom<Num> produces None <=> core::mem::transmute(num) produces an invalid state for Self
pub unsafe trait BitCount {
    const COUNT: usize;
}

macro_rules! bit_counts {
    ($($num: ty = $count: literal),*) => {
        $(
        unsafe impl BitCount for $num {
            const COUNT: usize = $count;
        }
        )*
    };
}

bit_counts!(u8 = 8, u16 = 16, u32 = 32, u64 = 64, u128 = 128, bool = 1);

impl u1 {
    pub const TRUE: u1 = u1(1);
    pub const FALSE: u1 = u1(0);

    pub fn toggle(self) -> Self {
        match self {
            Self::FALSE => u1::TRUE,
            _ => Self::FALSE,
        }
    }
}

macro_rules! new_signed_types {
    (
        $($name: ident($count: literal, $inner: ty, $signed: ty) => [$($into: ty),*]),*
    ) => {
        $(

        #[allow(non_camel_case_types)]
        #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
        pub struct $name($inner);

        impl Debug for $name {
            fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
                f.write_fmt(format_args!("{}", self.0))
            }
        }

        impl Display for $name {
            fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
                f.write_fmt(format_args!("{}", self.0))
            }
        }

        #[macro_export]
        macro_rules! $name {
            ($value: expr) => {
                {
                    const VALUE: $signed = $value;
                    const _: () = assert!(VALUE <= $name::MAX, "The provided value is too large");
                    const _: () = assert!(VALUE >= $name::MIN, "The provided value is too small");
                    let res: $name = unsafe {bit_struct::$name::new_unchecked(VALUE)};
                    res
                }
            };
        }


        unsafe impl BitCount for $name {
            const COUNT: usize = $count;
        }

        impl $name {
            /// Create a new $name from value
            /// # Safety
            /// - value must fit within the number of bits defined in the type
            pub unsafe fn new_unchecked(value: $signed) -> Self {
                let unsigned_value = value as $inner;
                if value >= 0 {
                    Self(unsigned_value)
                } else {
                    // we can do this
                    let value = unsigned_value & Self::MAX_UNSIGNED;
                    Self(value | Self::POLARITY_FLAG)
                }
            }


            /// Create a new $name from value
            /// # Safety
            /// - value must fit within the number of bits defined in the type
            pub fn new(value: $signed) -> Option<Self> {
                if value < Self::MIN || value > Self::MAX {
                    None
                } else {
                    Some(unsafe {Self::new_unchecked(value)})
                }
            }

            pub fn inner_raw(self) -> $inner {
                self.0
            }

            const POLARITY_FLAG: $inner = (1 << ($count - 1));
            const MAX_UNSIGNED: $inner = (1 << ($count-1)) - 1;
            pub const MAX: $signed = Self::MAX_UNSIGNED as $signed;
            pub const MIN: $signed = -(Self::MAX_UNSIGNED as $signed) - 1;

            pub fn signed(self) -> $signed {
                match self.0 >> ($count - 1) {
                    0 => self.0 as $signed,
                    _ => {
                        // 0's out negative
                        let rem = self.0 ^ Self::POLARITY_FLAG;
                        let amount = Self::MAX_UNSIGNED - rem;
                        -(amount as $signed) - 1
                    }
                }
            }
        }

        impl Default for $name {
            fn default() -> Self {
                Self(0)
            }
        }

        $(
            impl From<$name> for $into {
                fn from(name: $name) -> $into {
                    name.0 as $into
                }
            }

            impl TryFrom<$into> for $name {
                type Error = ();

                fn try_from(inner: $into) -> Result<$name, ()>{
                   if inner > (Self::MAX as $into) || inner < (Self::MIN as $into) {
                       Err(())
                   }  else {
                       Ok(unsafe {$name::new_unchecked(inner as $signed)})
                   }
                }
            }
        )*
        )*
    };
}

macro_rules! new_unsigned_types {
    (
        $($name: ident($count: literal, $inner: ty) => [$($into: ty),*]),*
    ) => {
        $(

        #[allow(non_camel_case_types)]
        #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
        pub struct $name($inner);

        impl Debug for $name {
            fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
                f.write_fmt(format_args!("{}", self.0))
            }
        }

        impl Display for $name {
            fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
                f.write_fmt(format_args!("{}", self.0))
            }
        }

        #[macro_export]
        macro_rules! $name {
            ($value: literal) => {
                {
                    const VALUE: $inner = $value;

                    // this is always valid because we have one more bit than we need in $inner
                    // type
                    const MAX: $inner = (1 << ($count)) - 1;
                    const _: () = assert!(MAX >= VALUE, "The provided value is too large");
                    unsafe {bit_struct::$name::new_unchecked(VALUE)}
                }
            };
        }


        unsafe impl BitCount for $name {
            const COUNT: usize = $count;
        }

        impl $name {
            /// Create a new $name from value
            /// # Safety
            /// - value must fit within the number of bits defined in the type
            pub unsafe fn new_unchecked(value: $inner) -> Self {
                Self(value)
            }

            pub fn inner(self) -> $inner {
                self.0
            }
        }

        impl Default for $name {
            fn default() -> Self {
                Self(0)
            }
        }

        $(
            impl From<$name> for $into {
                fn from(name: $name) -> $into {
                    name.0 as $into
                }
            }

            impl TryFrom<$into> for $name {
                type Error = ();

                fn try_from(inner: $into) -> Result<$name, ()>{
                   if inner >= (1 << $count) {
                       Err(())
                   }  else {
                       Ok($name(inner as $inner))
                   }
                }
            }
        )*
        )*
    };
}

new_signed_types!(
    i2  (2, u8, i8)   => [u8, u16, u32, u64, u128],
    i3  (3, u8, i8)   => [u8, u16, u32, u64, u128],
    i4  (4, u8, i8)   => [u8, u16, u32, u64, u128],
    i5  (5, u8, i8)   => [u8, u16, u32, u64, u128],
    i6  (6, u8, i8)   => [u8, u16, u32, u64, u128],
    i7  (7, u8, i8)   => [u8, u16, u32, u64, u128],
    i9  (9, u16, i16)  => [u16, u32, u64, u128],
    i10 (10, u16, i16) => [u16, u32, u64, u128],
    i11 (11, u16, i16) => [u16, u32, u64, u128],
    i12 (12, u16, i16) => [u16, u32, u64, u128],
    i13 (13, u16, i16) => [u16, u32, u64, u128],
    i14 (14, u16, i16) => [u16, u32, u64, u128],
    i15 (15, u16, i16) => [u16, u32, u64, u128],
    i17 (17, u32, i32) => [u32, u64, u128],
    i18 (18, u32, i32) => [u32, u64, u128],
    i19 (19, u32, i32) => [u32, u64, u128],
    i20 (20, u32, i32) => [u32, u64, u128],
    i21 (21, u32, i32) => [u32, u64, u128],
    i22 (22, u32, i32) => [u32, u64, u128],
    i23 (23, u32, i32) => [u32, u64, u128],
    i24 (24, u32, i32) => [u32, u64, u128],
    i25 (25, u32, i32) => [u32, u64, u128],
    i26 (26, u32, i32) => [u32, u64, u128],
    i27 (27, u32, i32) => [u32, u64, u128],
    i28 (28, u32, i32) => [u32, u64, u128],
    i29 (29, u32, i32) => [u32, u64, u128],
    i30 (30, u32, i32) => [u32, u64, u128],
    i31 (31, u32, i32) => [u32, u64, u128],
    i33 (33, u64, i64) => [u64, u128],
    i34 (34, u64, i64) => [u64, u128],
    i35 (35, u64, i64) => [u64, u128],
    i36 (36, u64, i64) => [u64, u128],
    i37 (37, u64, i64) => [u64, u128],
    i38 (38, u64, i64) => [u64, u128],
    i39 (39, u64, i64) => [u64, u128],
    i40 (40, u64, i64) => [u64, u128],
    i41 (41, u64, i64) => [u64, u128],
    i42 (42, u64, i64) => [u64, u128],
    i43 (43, u64, i64) => [u64, u128],
    i44 (44, u64, i64) => [u64, u128],
    i45 (45, u64, i64) => [u64, u128],
    i46 (46, u64, i64) => [u64, u128],
    i47 (47, u64, i64) => [u64, u128],
    i48 (48, u64, i64) => [u64, u128],
    i49 (49, u64, i64) => [u64, u128],
    i50 (50, u64, i64) => [u64, u128],
    i51 (51, u64, i64) => [u64, u128],
    i52 (52, u64, i64) => [u64, u128],
    i53 (53, u64, i64) => [u64, u128],
    i54 (54, u64, i64) => [u64, u128],
    i55 (55, u64, i64) => [u64, u128],
    i56 (56, u64, i64) => [u64, u128],
    i57 (57, u64, i64) => [u64, u128],
    i58 (58, u64, i64) => [u64, u128],
    i59 (59, u64, i64) => [u64, u128],
    i60 (60, u64, i64) => [u64, u128],
    i61 (61, u64, i64) => [u64, u128],
    i62 (62, u64, i64) => [u64, u128],
    i63 (63, u64, i64) => [u64, u128]
);

new_unsigned_types!(
    u1  (1, u8)   => [u8, u16, u32, u64, u128],
    u2  (2, u8)   => [u8, u16, u32, u64, u128],
    u3  (3, u8)   => [u8, u16, u32, u64, u128],
    u4  (4, u8)   => [u8, u16, u32, u64, u128],
    u5  (5, u8)   => [u8, u16, u32, u64, u128],
    u6  (6, u8)   => [u8, u16, u32, u64, u128],
    u7  (7, u8)   => [u8, u16, u32, u64, u128],
    u9  (9, u16)  => [u16, u32, u64, u128],
    u10 (10, u16) => [u16, u32, u64, u128],
    u11 (11, u16) => [u16, u32, u64, u128],
    u12 (12, u16) => [u16, u32, u64, u128],
    u13 (13, u16) => [u16, u32, u64, u128],
    u14 (14, u16) => [u16, u32, u64, u128],
    u15 (15, u16) => [u16, u32, u64, u128],
    u17 (17, u32) => [u32, u64, u128],
    u18 (18, u32) => [u32, u64, u128],
    u19 (19, u32) => [u32, u64, u128],
    u20 (20, u32) => [u32, u64, u128],
    u21 (21, u32) => [u32, u64, u128],
    u22 (22, u32) => [u32, u64, u128],
    u23 (23, u32) => [u32, u64, u128],
    u24 (24, u32) => [u32, u64, u128],
    u25 (25, u32) => [u32, u64, u128],
    u26 (26, u32) => [u32, u64, u128],
    u27 (27, u32) => [u32, u64, u128],
    u28 (28, u32) => [u32, u64, u128],
    u29 (29, u32) => [u32, u64, u128],
    u30 (30, u32) => [u32, u64, u128],
    u31 (31, u32) => [u32, u64, u128],
    u33 (33, u64) => [u64, u128],
    u34 (34, u64) => [u64, u128],
    u35 (35, u64) => [u64, u128],
    u36 (36, u64) => [u64, u128],
    u37 (37, u64) => [u64, u128],
    u38 (38, u64) => [u64, u128],
    u39 (39, u64) => [u64, u128],
    u40 (40, u64) => [u64, u128],
    u41 (41, u64) => [u64, u128],
    u42 (42, u64) => [u64, u128],
    u43 (43, u64) => [u64, u128],
    u44 (44, u64) => [u64, u128],
    u45 (45, u64) => [u64, u128],
    u46 (46, u64) => [u64, u128],
    u47 (47, u64) => [u64, u128],
    u48 (48, u64) => [u64, u128],
    u49 (49, u64) => [u64, u128],
    u50 (50, u64) => [u64, u128],
    u51 (51, u64) => [u64, u128],
    u52 (52, u64) => [u64, u128],
    u53 (53, u64) => [u64, u128],
    u54 (54, u64) => [u64, u128],
    u55 (55, u64) => [u64, u128],
    u56 (56, u64) => [u64, u128],
    u57 (57, u64) => [u64, u128],
    u58 (58, u64) => [u64, u128],
    u59 (59, u64) => [u64, u128],
    u60 (60, u64) => [u64, u128],
    u61 (61, u64) => [u64, u128],
    u62 (62, u64) => [u64, u128],
    u63 (63, u64) => [u64, u128]
);

impl<
        'a,
        P: Num + Bounded + ShlAssign<usize> + ShrAssign<usize>,
        T,
        const START: usize,
        const STOP: usize,
    > GetSet<'a, P, T, START, STOP>
{
    /// Create a new [GetSet]. This should be called from methods generated by the [bit_struct]
    /// macro
    pub fn new(parent: &'a mut P) -> Self {
        Self {
            parent,
            _phantom: PhantomData::default(),
        }
    }

    /// Get a mask of STOP-START + 1 length. This doesn't use the shift left and subtract one
    /// trick because of the special case where (0b1 << (STOP - START + 1)) - 1 will cause an
    /// overflow
    fn mask(&self) -> P {
        let num_bits = core::mem::size_of::<P>() * 8;
        let mut max_value = P::max_value();
        let keep_bits = STOP - START + 1;

        max_value >>= num_bits - keep_bits;
        max_value
    }
}

impl<
        'a,
        P: Num
            + Shl<usize, Output = P>
            + Shr<usize, Output = P>
            + ShlAssign<usize>
            + ShrAssign<usize>
            + Bounded
            + BitAnd<Output = P>
            + Copy,
        T: TryFrom<P>,
        const START: usize,
        const STOP: usize,
    > GetSet<'a, P, T, START, STOP>
{
    /// Get the property. Returns an error it does not exist.
    pub fn get(&self) -> T {
        let section = self.get_raw();
        unsafe { core::mem::transmute_copy(&section) }
    }

    pub fn is_valid(&self) -> bool {
        let section = self.get_raw();
        T::try_from(section).is_ok()
    }

    pub fn get_raw(&self) -> P {
        let parent = *self.parent;
        let mask = self.mask();
        (parent >> START) & mask
    }
}

impl<
        'a,
        P: Num
            + Shl<usize, Output = P>
            + Copy
            + BitOrAssign
            + BitXorAssign
            + BitAnd<Output = P>
            + ShlAssign<usize>
            + ShrAssign<usize>
            + PartialOrd
            + Bounded
            + Sized,
        T: Into<P> + Sized,
        const START: usize,
        const STOP: usize,
    > GetSet<'a, P, T, START, STOP>
{
    /// Set the property with a core::mem::transmute_copy
    pub fn set(&mut self, value: T) {
        let value = unsafe { core::mem::transmute_copy(&value) };
        unsafe { self.set_raw(value) }
    }

    /// Set the field to a raw value.
    /// # Safety
    /// value must be a valid representation of the field. i.e., `core::mem::transmute` between
    /// P and T must be defined.
    pub unsafe fn set_raw(&mut self, value: P) {
        let mask = self.mask();
        let mask_shifted = mask << START;

        // zero out parent
        *self.parent |= mask_shifted;
        *self.parent ^= mask_shifted;

        let to_set = value & mask;
        *self.parent |= to_set << START;
    }
}

#[macro_export]
macro_rules! impl_fields {

    ($on: expr, $kind: ty =>
    [$($first_field_doc: expr),*], $head_field: ident, $head_actual: ty $(, [$($field_doc: expr),*], $field: ident, $actual: ty)*) => {
        $(#[doc=$first_field_doc])*
        pub fn $head_field(&mut self) -> bit_struct::GetSet<'_, $kind, $head_actual, {$on - <$head_actual as bit_struct::BitCount>::COUNT}, {$on - 1}> {
            bit_struct::GetSet::new(&mut self.0)
        }

        bit_struct::impl_fields!($on - <$head_actual as bit_struct::BitCount>::COUNT, $kind => $([$($field_doc),*], $field, $actual),*);
    };
    ($on: expr, $kind: ty =>) => {};
}

/// Helper macro
#[macro_export]
macro_rules! bit_struct_impl {
    (
        $(#[doc = $struct_doc:expr])*
        #[derive(Default)]
        $struct_vis: vis struct $name: ident ($kind: ty) {
        $(
            $(#[doc = $field_doc:expr])*
            $field: ident: $actual: ty
        ),* $(,)?
        }
    ) => {

        bit_struct::bit_struct_impl!(
        $(#[doc = $struct_doc])*
        $struct_vis struct $name ($kind) {
        $(
            $(#[doc = $field_doc])*
            $field: $actual
        ),*
        }

        );

        impl Default for $name {
            fn default() -> Self {
                Self::of_defaults()
            }
        }

    };

    (
        $(#[doc = $struct_doc:expr])*
        $struct_vis: vis struct $name: ident ($kind: ty) {
        $(
            $(#[doc = $field_doc:expr])*
            $field: ident: $actual: ty
        ),* $(,)?
        }
    ) => {

        impl $name {

            /// Returns a valid representation for the bit_struct, where all values are
            /// the defaults. This is different than Self::default(), because the actual
            /// default implementation might not be composed of only the defaults of the
            /// given fields
            pub fn of_defaults() -> Self {
                let mut res = unsafe { Self::from_unchecked(0) };
                $(
                    res.$field().set(Default::default());
                )*
                res
            }
        }

        impl ::core::fmt::Debug for $name {
            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> core::fmt::Result {
                let mut copied = *self;
                f.debug_struct(stringify!($name))
                    $(
                        .field(stringify!($field), &copied.$field().get())
                    )*
                    .finish()
            }
        }
    };
}

// the main is actually needed

#[allow(clippy::needless_doctest_main)]
/// Create a bit struct.
///
///
/// This macro can only be used once for each module.
/// This is because the macro creates sub-module to limit access to certain
/// unsafe access. In the macro, bit-structs can be defined just like a struct outside of the
/// the macro. The catch is a **base type** must be specified. Valid base types are
/// u{8,16,32,64,128}. The elements stored in the struct are statically guaranteed to not
/// exceed the number of bits in the base type. This means we cannot store a `u16` in a `u8`, but
/// it also means we cannot store 9 `u1`s in a u8.
///
/// Elements start at the top of the number (for a u16 this would be the 15th bit) and progress
/// down.
///
/// # Example
/// ```
/// bit_struct::enums! {
///     /// The default value for each enum is always the first
///     pub ThreeVariants { Zero, One, Two }
///
///     /// This is syntax to set the default value to Cat
///     pub Animal(Cat) { Cow, Bird, Cat, Dog }
///
///     pub Color { Orange, Red, Blue, Yellow, Green }
/// }
///
/// bit_struct::bit_struct! {
///     /// We can write documentation for the struct here. Here BitStruct1
///     /// derives default values from the above enums macro
///     #[derive(Default)]
///     struct BitStruct1 (u16){
///         /// a 1 bit element. This is stored in u16[15]
///         a: bit_struct::u1,
///
///         /// This is calculated to take up 2 bits. This is stored in u16[13..=14]
///         variant: ThreeVariants,
///
///         /// This also takes 2 bits. This is stored in u16[11..=12]
///         animal: Animal,
///
///         /// This takes up 3 bits. This is stored u16[8..=10]
///         color: Color,
///     }
///
///     struct BitStruct2(u32) {
///         /// We could implement for this too. Note, this does not have a default
///         a_color: Color,
///         b: bit_struct::u3,
///     }
/// }
///
/// fn main() {
///     use std::convert::TryFrom;
///     let mut bit_struct: BitStruct1 = BitStruct1::default();
///
///     assert_eq!(bit_struct.a().start(), 15);
///     assert_eq!(bit_struct.a().stop(), 15);
///
///     assert_eq!(bit_struct.color().start(), 8);
///     assert_eq!(bit_struct.color().stop(), 10);
///
///     assert_eq!(format!("{:?}", bit_struct), "BitStruct1 { a: 0, variant: Zero, animal: Cat, color: Orange }");
///     assert_eq!(bit_struct.raw(), 4096);
///
///     let reverse_bit_struct = BitStruct1::try_from(4096);
///     assert_eq!(format!("{:?}", reverse_bit_struct), "Ok(BitStruct1 { a: 0, variant: Zero, animal: Cat, color: Orange })");
///
///
///     // u3! macro provides a static assert that the number is not too large
///     let mut other_struct = BitStruct2::new(Color::Green, bit_struct::u3!(0b101));
///     assert_eq!(format!("{:?}", other_struct), "BitStruct2 { a_color: Green, b: 5 }");
///
///     assert_eq!(other_struct.a_color().get(), Color::Green);
///
///     other_struct.a_color().set(Color::Red);
///
///     assert_eq!(other_struct.a_color().get(), Color::Red);
/// }
/// ```
///
#[macro_export]
macro_rules! bit_struct {
    (
        $(
        $(#[doc = $struct_doc:expr])*
        $(#[derive($($struct_der: ident),+)])?
        $struct_vis: vis struct $name: ident ($kind: ty) {
        $(
            $(#[doc = $field_doc:expr])*
            $field: ident: $actual: ty
        ),* $(,)?
        }
        )*
    ) => {

        mod bit_struct_private_impl {
            use super::*;

            $(
            $(#[doc = $struct_doc])*
            #[derive(Copy, Clone, PartialOrd, PartialEq, Eq, Ord, Hash)]
            pub struct $name($kind);

            impl TryFrom<$kind> for $name {
                type Error = ();
                fn try_from(elem: $kind) -> Result<$name, ()> {
                    let mut res = Self(elem);
                    $(
                        if !res.$field().is_valid() {
                            return Err(());
                        }
                    )*
                    Ok(res)
                }
            }

            impl $name {

                pub unsafe fn from_unchecked(inner: $kind) -> Self {
                   Self(inner)
                }

                #[allow(clippy::too_many_arguments)]
                pub fn new($($field: $actual),*) -> Self {
                    let mut res = Self(0);
                    $(
                        res.$field().set($field);
                    )*
                    res
                }

                pub fn raw(self) -> $kind {
                    self.0
                }

                bit_struct::impl_fields!(<$kind as bit_struct::BitCount>::COUNT, $kind => $([$($field_doc),*], $field, $actual),*);
            }

            )*
        }

        $(
        pub use bit_struct_private_impl::$name;
        )*


        $(
        bit_struct::bit_struct_impl!(
        $(#[doc = $struct_doc])*
        $(#[derive($($struct_der),+)])?
        $struct_vis struct $name ($kind) {
        $(
            $(#[doc = $field_doc])*
            $field: $actual
        ),*
        }

        );
        )*
    };
}

#[macro_export]
macro_rules! count_idents {
    ($on: expr, [$head: ident $(,$xs: ident)*]) => {
        bit_struct::count_idents!($on + 1, [$($xs),*])
    };
    ($on: expr, []) => {
        $on
    }
}

pub const fn bits(num: usize) -> usize {
    const fn helper(count: usize, on: usize) -> usize {
        // 0b11 = 3  log2_ceil(0b11) = 2 .. 2^2
        // 0b10 = 2 log2_ceil = 2 .. 2^1
        if on > 0 {
            helper(count + 1, on >> 1)
        } else {
            count
        }
    }

    helper(0, num)
}

/// Not meant to be directly used
#[macro_export]
macro_rules! enum_impl {
    (
        $(#[doc = $struct_doc:expr])*
        $(#[derive($($struct_der:ident),+)])?
        $enum_vis: vis $name: ident($default: ident){
            $(#[doc = $fst_field_doc:expr])*
            $fst_field: ident
            $(,
                $(#[doc = $field_doc:expr])*
                $field: ident
            )* $(,)?
        }
    ) => {

        #[repr(u8)]
        $(#[doc = $struct_doc])*
        $(#[derive($($struct_der),+)])?
        #[derive(Copy, Clone, Debug, PartialOrd, PartialEq)]
        $enum_vis enum $name {
            $(#[doc = $fst_field_doc])*
            $fst_field,
            $(
                $(#[doc = $field_doc])*
                $field
            ),*
        }

        unsafe impl bit_struct::BitCount for $name {
            const COUNT: usize = bit_struct::bits(bit_struct::count_idents!(0, [$($field),*]));
        }

        impl Default for $name {
            fn default() -> Self {
                $name::$default
            }
        }

        impl TryFrom<u8> for $name {

            type Error = ();

            fn try_from(value: u8) -> Result<$name, Self::Error> {
                let variants = [$name::$fst_field, $($name::$field),*];
                if (value as usize) < variants.len() {
                    Ok(variants[value as usize])
                } else {
                    Err(())
                }
            }
        }

        impl TryFrom<u16> for $name {

            type Error = ();

            fn try_from(value: u16) -> Result<$name, Self::Error> {
                $name::try_from(value as u8)
            }
        }

        impl TryFrom<u32> for $name {

            type Error = ();

            fn try_from(value: u32) -> Result<$name, Self::Error> {
                $name::try_from(value as u8)
            }
        }

        impl TryFrom<u64> for $name {

            type Error = ();

            fn try_from(value: u64) -> Result<$name, Self::Error> {
                $name::try_from(value as u8)
            }
        }

        impl TryFrom<u128> for $name {

            type Error = ();

            fn try_from(value: u128) -> Result<$name, Self::Error> {
                $name::try_from(value as u8)
            }
        }

        impl From<$name> for u8 {
            fn from(value: $name) -> u8 {
                value as u8
            }
        }

        impl From<$name> for u16 {
            fn from(value: $name) -> u16 {
                (value as u8) as u16
            }
        }

        impl From<$name> for u32 {
            fn from(value: $name) -> u32 {
                (value as u8) as u32
            }
        }
        impl From<$name> for u64 {
            fn from(value: $name) -> u64 {
                (value as u8) as u64
            }
        }

        impl From<$name> for u128 {
            fn from(value: $name) -> u128 {
                (value as u8) as u128
            }
        }


    };


    (
        $(#[doc = $struct_doc:expr])*
        $(#[derive($($struct_der:ident),+)])?
        $enum_vis: vis $name: ident {
            $(#[doc = $fst_field_doc:expr])*
            $fst_field: ident
            $(,
                $(#[doc = $field_doc:expr])*
                $field: ident
            )* $(,)?
        }
    ) => {
        #[repr(u8)]
        $(#[doc = $struct_doc])*
        $(#[derive($($struct_der),+)])?
        #[derive(Copy, Clone, Debug, PartialOrd, PartialEq)]
        $enum_vis enum $name {
            $(#[doc = $fst_field_doc])*
            $fst_field,
            $(
                $(#[doc = $field_doc])*
                $field
            ),*
        }

        impl Default for $name {
            fn default() -> Self {
                $name::$fst_field
            }
        }

        unsafe impl bit_struct::BitCount for $name {
            const COUNT: usize = bit_struct::bits(bit_struct::count_idents!(0, [$($field),*]));
        }


        impl TryFrom<u8> for $name {

            type Error = ();

            fn try_from(value: u8) -> Result<$name, Self::Error> {
                let variants = [$name::$fst_field, $($name::$field),*];
                if (value as usize) < variants.len() {
                    Ok(variants[value as usize])
                } else {
                    Err(())
                }
            }
        }

        impl TryFrom<u16> for $name {

            type Error = ();

            fn try_from(value: u16) -> Result<$name, Self::Error> {
                $name::try_from(value as u8)
            }
        }

        impl TryFrom<u32> for $name {

            type Error = ();

            fn try_from(value: u32) -> Result<$name, Self::Error> {
                $name::try_from(value as u8)
            }
        }

        impl TryFrom<u64> for $name {

            type Error = ();

            fn try_from(value: u64) -> Result<$name, Self::Error> {
                $name::try_from(value as u8)
            }
        }

        impl TryFrom<u128> for $name {

            type Error = ();

            fn try_from(value: u128) -> Result<$name, Self::Error> {
                $name::try_from(value as u8)
            }
        }

        impl From<$name> for u8 {
            fn from(value: $name) -> u8 {
                value as u8
            }
        }

        impl From<$name> for u16 {
            fn from(value: $name) -> u16 {
                (value as u8) as u16
            }
        }

        impl From<$name> for u32 {
            fn from(value: $name) -> u32 {
                (value as u8) as u32
            }
        }
        impl From<$name> for u64 {
            fn from(value: $name) -> u64 {
                (value as u8) as u64
            }
        }

        impl From<$name> for u128 {
            fn from(value: $name) -> u128 {
                (value as u8) as u128
            }
        }
    };
}

/// Create enums which have convenient TryFrom/From implementations. This makes using them with
/// the [bit_struct] macro much easier.
#[macro_export]
macro_rules! enums {
    (
        $(
        $(#[doc = $struct_doc:expr])*
        $(#[derive($($struct_der:ident),+)])?
        $enum_vis: vis $name: ident $(($enum_default: ident))? {
            $(#[doc = $fst_field_doc:expr])*
            $fst_field: ident
            $(,
                $(#[doc = $field_doc:expr])*
                $field: ident
            )* $(,)?
        }
        )+
    ) => {
        $(
        bit_struct::enum_impl!(
        $(#[doc = $struct_doc])*
        $(#[derive($($struct_der),+)])?
        $enum_vis $name $(($enum_default))?{
            $(#[doc = $fst_field_doc])*
            $fst_field
            $(,
                $(#[doc = $field_doc])*
                $field
            )*
        }
        );
        )+
    }
}