uint256 0.1.0

A light-weight implementation of 256-bit unsigned integers type with semantic API.
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
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
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
#![allow(dead_code)]

use std::{ops::{Add, BitOr, Div, Mul, Shl, Shr, Sub}, str::FromStr};
use std::cmp::Ordering;

/// The endianness of the integer.
///
/// Endianness refers to the byte order of the integer.
/// Read more [here](https://dev.to/pancy/what-are-big-and-little-endians-91h).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Endian {
    Little,
    Big,
}

pub(crate) mod utils {

    //// Utility functions for converting between byte arrays and UInt256 values.

    use super::*;

    pub(crate) struct BytesPair {
        /// The low part (LSB) of the byte array.
        pub low: Box<[u8; 16]>,
        /// The high part (MSB) of the byte array.
        pub high: Box<[u8; 16]>,
    }

    //// Pad a byte array to 32 bytes with the given byte value.
    /// The `endian` parameter specifies the "endianness" of the input data, or
    /// basically just deciding whether to prepend or append the padding bytes.
    /// The existing bytes are copied to the padded array in the same order.
    pub(crate) fn pad_bytes(data: &[u8], with: u8, endian: Endian) -> [u8; 32] {
        let mut padded = [with; 32];
        let len = data.len().min(32);
        match endian {
            // Prepend the data to the padded array
            Endian::Big => padded[32 - len..].copy_from_slice(&data[..len]),
            // Append the data to the padded array
            Endian::Little => padded[..len].copy_from_slice(&data[..len]),
        }
        padded
    }

    /// Convert a 32-byte array to a UInt256 value based on the endian type provided.
    pub(crate) fn to_uint256(bytes: &[u8; 32], endian: Endian) -> UInt256 {
        match endian {
            Endian::Little => UInt256::from_le_bytes(bytes),
            Endian::Big => UInt256::from_be_bytes(bytes),
        }
    }

    /// Convert a 32-byte hexadecimal string to a `BytesPair` of 16-byte arrays.
    pub(crate) fn hex_to_bytes_pair(n: &str, endian: Endian) -> Result<BytesPair, String> {

        let a = n.trim().strip_prefix("0x").unwrap();

        match endian {
            Endian::Big => {
                // Take the first 16 bytes (32 chars) as the low part and the last 16 bytes (32 chars) as the high part.
                let low_hex = &a[..32];
                let high_hex = &a[32..];

                let low_num = u128::from_str_radix(low_hex, 16).unwrap();
                let low_data = low_num.to_be_bytes().to_vec();
                let low_bytes = <[u8; 16]>::try_from(low_data.as_slice()).map_err(|e| e.to_string())?;

                let high_num = u128::from_str_radix(high_hex, 16).unwrap();
                let high_data = high_num.to_be_bytes().to_vec();
                let high_bytes = <[u8; 16]>::try_from(high_data.as_slice()).map_err(|e| e.to_string())?;

                return Ok(BytesPair{
                    low: Box::new(low_bytes),
                    high: Box::new(high_bytes),
                });
            },
            Endian::Little => {
                // Take the last 16 bytes (32 chars) as the low part and the first 16 bytes (32 chars) as the high part.
                let low_hex = &a[32..];
                let high_hex = &a[..32];

                let low_num = u128::from_str_radix(low_hex, 16).unwrap();
                let low_data = low_num.to_be_bytes().to_vec()
                    .iter()
                    .rev() // Reverse the order of the bytes
                    .cloned()
                    .collect::<Vec<u8>>();

                let low_bytes = <[u8; 16]>::try_from(low_data.clone().as_slice()).map_err(|e| e.to_string())?;

                let high_num = u128::from_str_radix(high_hex, 16).unwrap();
                let high_data = high_num.to_be_bytes().to_vec()
                    .iter()
                    .rev()// Reverse the order of the bytes
                    .cloned()
                    .collect::<Vec<u8>>();

                let high_bytes = <[u8; 16]>::try_from(high_data.clone().as_slice()).map_err(|e| e.to_string())?;

                // Keeping this dumb first attempt for reference.

                // let low_chars: Vec<char> = base_low.chars().collect();
                // let mut low_pairs = Vec::with_capacity(16);
                // let high_chars: Vec<char> = base_high.chars().collect();
                // let mut high_pairs = Vec::with_capacity(16);
                // let mut i = 0;
                // while i + 1 < low_chars.len() {
                //     let a = low_chars[i];
                //     let b = low_chars[i + 1];
                //     println!("# {} : {}", a, b);
                //     low_pairs.push((a, b));
                //     i += 2;
                // }
                // i = 0;
                // while i + 1 < high_chars.len() {
                //     let a = high_chars[i];
                //     let b = high_chars[i + 1];
                //     println!("# {} : {}", a, b);
                //     high_pairs.push((a, b));
                //     i += 2;
                // }
                // let low_bytes: Vec<u8> = low_pairs
                //     .iter()
                //     .map(|(a, b)| {
                //         let s = format!("{}{}", a, b);
                //         println!("{}", s);
                //         let a = u8::from_str_radix(&s, 16).unwrap();
                //         a
                //     })
                //     .rev()
                //     .collect();
                // let high_bytes: Vec<u8> = high_pairs
                //     .iter()
                //     .map(|(a, b)| {
                //         let s = format!("{}{}", a, b);
                //         println!("{}", s);
                //         let a = u8::from_str_radix(&s, 16).unwrap();
                //         a
                //     })
                //     .rev()
                //     .collect();

                return Ok(BytesPair{
                    low: Box::new(low_bytes),
                    high: Box::new(high_bytes),
                });
            },
        };
    }
}


impl Default for Endian {
    fn default() -> Self {
        DEFAULT_ENDIAN
    }
}

/// A builder for creating `UInt256` values.
///
/// The builder allows setting the endianness and padding for the `UInt256` value
/// in a semantic way.
///
/// ## Examples
///
/// ```rust
/// use uint256::{UInt256Builder, Endian};
///
/// let my_bytes_array = [
///     0xff, 0x45, 0x67, 0x89, 0x0a, 0xbc, 0xde, 0xf1,
///     0x23, 0x45, 0x67, 0x89, 0x0a, 0xc2, 0x03, 0xd5,
///     0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef,
///     0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef,
/// ];
///
/// let num = UInt256Builder::new()
///     .with_endian(Endian::Big)
///     .from_bytes(my_bytes_array)
///     .build();
/// ```
///
#[derive(Debug, Default)]
pub struct UInt256Builder {
    bytes: Box<[u8; 32]>,
    endian: Option<Endian>,
    padding: Option<u8>,
}

impl UInt256Builder {
    pub fn new() -> Self {
        UInt256Builder {
            bytes: Box::new([0u8; 32]),
            endian: None,
            padding: None,
        }
    }

    /// Set the padding byte for the [`UInt256`] value.
    /// The `padding` parameter specifies the byte value to pad the input bytes with to fill up to 32 bytes.
    /// Must be called prior to calling [`Self::from_partial_bytes`].
    pub fn with_padding(&mut self, padding: u8) -> &mut Self {
        self.padding = Some(padding);
        self
    }

    /// Set the endianness of the [`UInt256`] value.
    /// The `endian` parameter specifies the byte order of the integer.
    /// Must be called prior to calling [`Self::from_bytes`] or [`Self::from_partial_bytes`].
    pub fn with_endian(&mut self, endian: Endian) -> &mut Self {
        self.endian = Some(endian);
        self
    }

    /// Set the bytes of the [`UInt256`] value from a partial byte vector.
    /// The `bytes` parameter specifies the input bytes to be padded to 32 bytes.
    /// Must be called after setting the endianness and setting the padding byte.
    pub fn from_partial_bytes(&mut self, bytes: Vec<u8>) -> &mut Self {
        if self.padding.is_none() {
            panic!("Padding is disabled. Call `from_bytes([u8; 32])` instead.");
        }

        if self.endian.is_none() {
            panic!("Endian is not set. Call `with_endian(Endian)` before calling this method.");
        }

        let padded = utils::pad_bytes(&bytes, 0x00, self.endian.unwrap());
        self.bytes = Box::new(padded);
        self
    }

    /// Set the raw bytes of the [`UInt256`] value.
    /// The `bytes` parameter specifies the raw bytes of the integer.
    pub fn from_bytes(&mut self, bytes: [u8; 32]) -> &mut Self {
        if self.padding.is_some() {
            panic!("Padding is enabled, cannot set raw bytes directly. Call `from_partial_bytes(Vec<u8>)` instead.");
        }
        self.bytes = Box::new(bytes);
        self
    }

    pub fn build(&mut self) -> UInt256 {
        utils::to_uint256(self.bytes.as_ref(), self.endian.unwrap())
    }
}

/// A 256-bit unsigned integer type.
/// The [`UInt256`] type is a 256-bit unsigned integer type that supports basic arithmetic operations.
/// It is represented as a pair of 128-bit unsigned integers, `high` and `low`.
/// The `endian` field specifies the byte order of the integer.
///
/// - It is immutable and can be compared with other [`UInt256`] values.
/// - It can be created from byte arrays, hexadecimal strings, and other integer types.
/// - It can be converted to byte arrays, hexadecimal strings, and other integer types.
///
/// It is recommended to use the [`UInt256Builder`] to create [`UInt256`] values to avoid
/// [Compiling and Praying to Work<sup>tm</sup>](https://raw.githubusercontent.com/denitdao/o-rly-collection/refs/heads/main/public/book_covers/compile-and-pray.jpeg).
///
/// ## Examples
/// ```rust
/// use std::str::FromStr;
/// use uint256::{UInt256, Endian};
///
/// let a = UInt256::from_str("0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef").unwrap();
/// let b = UInt256::from_str("0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef").unwrap();
/// println!("a + b = {}", a + b);
/// ```
///
#[derive(Debug, Default, Clone, Copy, Eq, Hash)]
pub struct UInt256 {
    /// First 16 bytes (128 bits). High means MSB or the left half.
    high: u128,
    /// Last 16 bytes (128 bits). Low means LSB or right half.
    low: u128,
    /// Endianness (Is it needed here though).
    endian: Endian,
}

impl UInt256 {
    pub const ZERO: Self = Self { high: 0, low: 0, endian: Endian::Big };
    pub const ONE: Self = Self { high: 0, low: 1, endian: Endian::Big };
    /// The maximum value of a 256-bit unsigned integer.
    pub const MAX: Self = Self {
        high: u128::MAX,
        low: u128::MAX,
        endian: Endian::Big,
    };

    pub fn new(high: u128, low: u128, endian: Endian) -> Self {
        UInt256 { high, low, endian }
    }

    pub fn is_zero(&self) -> bool {
        self.high == 0 && self.low == 0
    }

    pub fn endian(&self) -> Endian {
        self.endian
    }

    pub fn as_bytes(&self) -> Box<[u8; 32]> {
        let mut bytes = [0u8; 32];

        // Fill in the high part (first 16 bytes)
        for i in 0..16 {
            bytes[i] = (self.high >> (8 * (15 - i)) & 0xff) as u8;
        }

        // Fill in the low part (last 16 bytes)
        for i in 0..16 {
            bytes[16 + i] = (self.low >> (8 * (15 - i)) & 0xff) as u8;
        }

        Box::new(bytes)
    }

    pub fn as_usize(&self) -> Result<usize, String> {
        let max_usize = Self::from(usize::MAX);
        if self.high != 0 || self.low > max_usize.low {
            return Err("Value too large".to_string());
        }
        Ok(self.low as usize)
    }

    pub(crate) fn from_str_radix(s: &str, radix: u32, endian: Endian) -> Result<Self, &'static str> {
        let s = s.trim();

        if s.len() != 64 {
            return Err("Invalid length");
        }

        let low: u128;
        let high: u128;

        match endian {
            Endian::Big => {
                low = u128::from_str_radix(&s[32..], radix).map_err(|_| "Invalid hex")?;
                high = u128::from_str_radix(&s[..32], radix).map_err(|_| "Invalid hex")?;
            },
            Endian::Little => {
                let n = &s[..32];
                n.strip_prefix(&['0']).unwrap_or(n);
                low = u128::from_str_radix(&s[..32], radix).map_err(|_| "Invalid hex")?;
                high = u128::from_str_radix(&s[32..], radix).map_err(|_| "Invalid hex")?;
            },
        }
        Ok(UInt256 { high, low, endian })
    }

    pub fn from_le_bytes(bytes: &[u8]) -> Self {
        let mut low = 0;
        let mut high = 0;
        for (i, byte) in bytes.iter().enumerate() {
            if i < 16 {
                low |= (*byte as u128) << (i * 8);
            } else {
                high |= (*byte as u128) << ((i - 16) * 8);
            }
        }
        UInt256 { high, low, endian: Endian::Little }
    }

    pub fn from_be_bytes(bytes: &[u8; 32]) -> Self {
        let mut low = 0;
        let mut high = 0;

       // Ensure the input is treated as a 32-byte array, padded with leading zeros if necessary
       for (i, byte) in bytes.iter().rev().enumerate() {
            if i < 16 {
                low |= (*byte as u128) << (i * 8);
            } else if i < 32 {
                high |= (*byte as u128) << ((i - 16) * 8);
            }
        }

        UInt256 { high, low, endian: Endian::Big }
    }

    pub fn to_le_bytes(&self) -> Vec<u8> {
        let mut bytes = Vec::with_capacity(32);
        for i in 0..32 {
            if i < 16 {
                bytes.push(((self.low >> (i * 8)) & 0xff) as u8);
            } else {
                bytes.push(((self.high >> ((i - 16) * 8)) & 0xff) as u8);
            }
        }
        bytes
    }

    pub fn to_be_bytes(&self) -> Box<[u8; 32]> {
        self.as_bytes()
    }

    /// Returns `true` if the bit at the given index is set; `false` otherwise.
    ///
    /// # Panics
    ///
    /// Panics if `index` is greater than 255.
    pub(crate) fn bit_at(&self, index: usize) -> bool {
        assert!(index < 256, "Bit index out of range");

        if index < 128 {
            // Check bit in the `low` segment
            (self.low & (1 << index)) != 0
        } else {
            // Check bit in the `high` segment
            (self.high & (1 << (index - 128))) != 0
        }
    }

    /// Sets the bit at the given index to 1.
    ///
    /// # Panics
    ///
    /// Panics if `index` is greater than 255.
    pub(crate) fn set_bit(&mut self, index: usize) {
        assert!(index < 256, "Bit index out of range");

        if index < 128 {
            // Set bit in the `low` segment
            self.low |= 1 << index;
        } else {
            // Set bit in the `high` segment
            self.high |= 1 << (index - 128);
        }
    }
}

// Overloading comparison, shift, and subtraction operators
impl PartialEq for UInt256 {
    fn eq(&self, other: &Self) -> bool {
        self.high == other.high && self.low == other.low
    }
}

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

impl Ord for UInt256 {
    fn cmp(&self, other: &Self) -> Ordering {
        match self.high.cmp(&other.high) {
            Ordering::Equal => self.low.cmp(&other.low),
            ord => ord,
        }
    }
}

impl std::fmt::Display for UInt256 {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "0x{:032x}{:032x}", self.high, self.low)
    }
}

impl BitOr for UInt256 {
    type Output = Self;

    fn bitor(self, rhs: Self) -> Self::Output {
        UInt256::new(self.high | rhs.high, self.low | rhs.low, self.endian)
    }
}

fn divide(dividend: UInt256, divisor: UInt256) -> (UInt256, UInt256) {
    if divisor.is_zero() {
        panic!("division by zero");
    }

    if dividend < divisor {
        return (UInt256::ZERO, dividend);
    }

    let mut quotient = UInt256::ZERO;
    let mut remainder = UInt256::ZERO;

    for i in (0..256).rev() {
        remainder = remainder.shl(1);
        remainder.low |= dividend.bit_at(i) as u128;

        if remainder >= divisor {
            remainder = remainder.sub(divisor);
            quotient.set_bit(i);
        }
    }

    (quotient, remainder)
}

impl Div for UInt256 {

    type Output = Self;

    fn div(self, divisor: Self) -> Self {
        let (quotient, _) = divide(self, divisor);
        quotient
    }
}

impl Add for UInt256 {
    type Output = Self;

    fn add(self, rhs: Self) -> Self {
        let (low, carry_low) = self.low.overflowing_add(rhs.low);

        if carry_low {
            let (high, carry_high) = self.high.overflowing_add(rhs.high);
            if carry_high {
                panic!("addition overflow on most significant bits");
            }
            if high == u128::MAX {
                panic!("addition overflow on least significant bits");
            }
            return UInt256 {
                high: high + 1,
                low: self.low,
                endian: self.endian,
            };
        }
        UInt256 {
            high: self.high,
            low,
            endian: self.endian,
        }
    }
}

impl Sub for UInt256 {

    type Output = Self;

    fn sub(self, rhs: Self) -> Self {
        if self < rhs {
            panic!("subtraction overflow");
        }

        let (low, borrow_low) = self.low.overflowing_sub(rhs.low);
        if borrow_low {
            let (high, borrow_high) = self.high.overflowing_sub(rhs.high);
            if borrow_high {
                panic!("subtraction overflow on most significant bits");
            }
            return UInt256 {
                high: high - 1,
                low: self.low,
                endian: self.endian,
            };
        }
        let res = UInt256 {
            high: self.high,
            low,
            endian: self.endian,
        };
        res
    }
}

impl Mul for UInt256 {
    type Output = Self;

    fn mul(self, other: Self) -> Self {
        // Split the values into high and low parts for each operand
        let a_low = self.low;
        let a_high = self.high;
        let b_low = other.low;
        let b_high = other.high;

        // Calculate the partial products
        let low_low = a_low as u128 * b_low as u128; // Low * Low part (128-bit)
        let low_high = a_low as u128 * b_high as u128; // Low * High part (128-bit)
        let high_low = a_high as u128 * b_low as u128; // High * Low part (128-bit)
        let high_high = a_high as u128 * b_high as u128; // High * High part (128-bit)

        // Combine the partial products, managing overflow
        let (low, carry1) = low_low.overflowing_add((low_high << 64) as u128);
        let (low, carry2) = low.overflowing_add((high_low << 64) as u128);
        let high = high_high + (low_high >> 64) + (high_low >> 64) + carry1 as u128 + carry2 as u128;

        UInt256 { high, low, endian: self.endian }
    }
}
impl Shr<u32> for UInt256 {
    type Output = Self;

    fn shr(self, shift: u32) -> Self {
        if shift >= 128 {
            UInt256 {
                high: 0,
                low: self.high >> (shift - 128),
                endian: self.endian,
            }
        } else if shift >= 256 {
            UInt256::ZERO
        } else {
            UInt256 {
                high: self.high >> shift,
                low: (self.high << (128 - shift)) | (self.low >> shift),
                endian: self.endian,
            }
        }
    }
}

// Helper implementation for left shift (<<) to handle shifting UInt256 by bit positions
impl Shl<u32> for UInt256 {
    type Output = Self;

    fn shl(self, shift: u32) -> Self {
        if shift >= 128 {
            UInt256 {
                high: self.low << (shift - 128),
                low: 0,
                endian: self.endian,
            }
        } else if shift >= 256 {
            UInt256::ZERO
        } else {
            UInt256 {
                high: (self.high << shift) | (self.low >> (128 - shift)),
                low: self.low << shift,
                endian: self.endian,
            }
        }
    }
}

const DEFAULT_RADIX: u32 = 16;
const DEFAULT_ENDIAN: Endian = Endian::Big;

impl FromStr for UInt256 {
    type Err = &'static str;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let s = s.strip_prefix("0x").unwrap_or(s);
        Self::from_str_radix(s, DEFAULT_RADIX, DEFAULT_ENDIAN)
    }
}

impl From<usize> for UInt256 {
    fn from(value: usize) -> Self {
        UInt256 {
            high: 0,
            low: value as u128,
            endian: Endian::Big,
        }
    }
}

impl TryInto<usize> for UInt256 {
    type Error = String;

    fn try_into(self) -> Result<usize, Self::Error> {
        self.as_usize()
    }
}

#[cfg(test)]
mod tests {

    use super::*;
    use utils::*;

    #[test]
    fn test_pad_bytes() {
        let data = vec![0x01, 0x4a];
        let padded_be = pad_bytes(&data, 0x00, Endian::Big).to_vec();
        let mut expected = vec![
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x4a,
        ];
        assert_eq!(padded_be, expected, "Big-endian padding failed");
        let padded_le = pad_bytes(&data, 0x00, Endian::Little).to_vec();
        expected = vec![
            0x01, 0x4a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        ];
        assert_eq!(padded_le, expected, "Little-endian padding failed");
    }

    #[test]
    fn test_uint256_from_str() {
        let n = "0xff4567890abcdef1234567890ac203d51234567890abcdef1234567890abcdef";

        let a = UInt256::from_str(n).unwrap();
        let expected = UInt256 {
            high: 0xff4567890abcdef1234567890ac203d5,
            low:  0x1234567890abcdef1234567890abcdef,
            endian: Endian::Big,
        };
        assert_eq!(a, expected);
        let n = "0x000000000000000000000000000000000000000000000000000000000000014a";
        let b = UInt256::from_str(n).unwrap();
        let expected = UInt256 {
            high: 0,
            low: 330,
            endian: Endian::Big,
        };
        assert_eq!(b, expected);
        let c = UInt256::MAX;
        let expected = UInt256 {
            high: 0xffffffffffffffffffffffffffffffff,
            low: 0xffffffffffffffffffffffffffffffff,
            endian: Endian::Big,
        };
        assert_eq!(c, expected);
    }

    #[test]
    fn test_hex_to_bytes() {
        let n = "0x000000000000000000000000000000000000000000000000000000000000014a";
        let utils::BytesPair{low, high} = utils::hex_to_bytes_pair(n, Endian::Little).unwrap();
        let expected_low = vec![
            0x4a, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        ];
        let expected_high = vec![
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        ];

        assert_eq!(low.as_ref().to_vec(), expected_low);
        assert_eq!(high.as_ref().to_vec(), expected_high);

        let utils::BytesPair{low, high} = utils::hex_to_bytes_pair(n, Endian::Big).unwrap();

        let expected_low = vec![
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        ];

        let expected_high = vec![
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x4a,
        ];
        assert_eq!(low.as_ref().to_vec(), expected_low);
        assert_eq!(high.as_ref().to_vec(), expected_high);

        let n = "0xff4567890abcdef1234567890ac203d51234567890abcdef1234567890abcdef";

        let utils::BytesPair{low, high} = utils::hex_to_bytes_pair(n, Endian::Big).unwrap();
        let expected_low = vec![
            0xff, 0x45, 0x67, 0x89, 0x0a, 0xbc, 0xde, 0xf1,
            0x23, 0x45, 0x67, 0x89, 0x0a, 0xc2, 0x03, 0xd5
        ];
        let expected_high = [
            0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef,
            0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef
        ];

        assert_eq!(low.as_ref().to_vec(), expected_low);
        assert_eq!(high.as_ref().to_vec(), expected_high);

        let utils::BytesPair{low, high} = utils::hex_to_bytes_pair(n, Endian::Little).unwrap();

        let expected_high: Vec<u8> = vec![
            0xff, 0x45, 0x67, 0x89, 0x0a, 0xbc, 0xde, 0xf1,
            0x23, 0x45, 0x67, 0x89, 0x0a, 0xc2, 0x03, 0xd5
        ].iter().rev().cloned().collect();
        let expected_low: Vec<u8> = [
            0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef,
            0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef
        ].iter().rev().cloned().collect();

        assert_eq!(low.as_ref().to_vec(), expected_low);
        assert_eq!(high.as_ref().to_vec(), expected_high);
    }

    #[test]
    fn test_uint256_from_str_radix_be() {
        let n = "0xff4567890abcdef1234567890ac203d51234567890abcdef1234567890abcdef";
        let a = n.strip_prefix("0x").unwrap();

        let a = UInt256::from_str_radix(a, 16, Endian::Big).unwrap();
        let expected = UInt256 {
            high: 0xff4567890abcdef1234567890ac203d5,
            low:  0x1234567890abcdef1234567890abcdef,
            endian: Endian::Big,
        };
        assert_eq!(a, expected);
        let n = "0x000000000000000000000000000000000000000000000000000000000000014a";
        let b = n.strip_prefix("0x").unwrap();
        let b = UInt256::from_str_radix(b, 16, Endian::Big).unwrap();
        let expected = UInt256 {
            high: 0,
            low: 330,
            endian: Endian::Big,
        };
        assert_eq!(b, expected);
    }

    #[test]
    fn test_uint256_from_str_radix_le() {
        let n = "0x000000000000000000000000000000000000000000000000000000000000014a";
        let b = n.strip_prefix("0x").unwrap();
        let b = UInt256::from_str_radix(b, 16, Endian::Little).unwrap();
        let expected = UInt256 {
            high: 330,
            low: 0,
            endian: Endian::Little,
        };
        assert_eq!(b, expected);
    }

    #[test]
    fn test_shl() {
        let a = UInt256::from(100) << 1;
        assert_eq!(
            a.as_usize().expect("a usize"),
            200,
        );
        let b = UInt256::from(100) << 2;
        assert_eq!(
            b.as_usize().expect("a usize"),
            400,
        );
    }

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

        #[test]
        fn test_uint256_shl() {
            let a = UInt256::from(100) << 1;
            assert_eq!(
                a.as_usize().expect("a usize"),
                200,
            );
            let b = UInt256::from(100) << 2;
            assert_eq!(
                b.as_usize().expect("a usize"),
                400,
            );
        }

        #[test]
        #[should_panic(expected = "Value too large")]
        fn test_uint256_shl_overflow() {
            let a = UInt256::MAX << 1;
            assert_eq!(
                a.as_usize().expect("a usize"),
                0,
            );
        }

        #[test]
        fn test_uint256_shr() {
            let a = UInt256::from(100) >> 1;
            assert_eq!(
                a.as_usize().expect("a usize"),
                50,
            );
            let b = UInt256::from(100) >> 2;
            assert_eq!(
                b.as_usize().expect("a usize"),
                25,
            );
        }
    }

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

        #[test]
        #[should_panic(expected = "addition overflow on least significant bits")]
        fn test_uint256_add_overflow() {
            let a = UInt256::MAX;
            let b = UInt256::ONE;
            let _ = a + b;
        }

        #[test]
        fn test_uint256_add_basic() {
            let a = UInt256::from(1000_000_000);
            let b = UInt256::from(999_999_999);
            let c = a + b;
            assert_eq!(c, UInt256::from(1999_999_999));
        }

        #[test]
        fn test_uint256_zero_property() {
            let c = UInt256::MAX + UInt256::ZERO;
            assert_eq!(c, UInt256::MAX);
        }

        #[test]
        fn test_uint256_add_big() {
            let a = UInt256::MAX - UInt256::ONE;
            let b = UInt256::ONE;
            let c = a + b;
            assert_eq!(c, UInt256::MAX);
        }
    }

    #[cfg(test)]
    mod test_subtraction {

        use super::*;

        #[test]
        #[should_panic(expected = "subtraction overflow")]
        fn test_uint256_subtract_overflow() {
            let a = UInt256::ONE;
            let b = UInt256::MAX;
            let _ = a - b;
        }

        #[test]
        #[should_panic(expected = "subtraction overflow")]
        fn test_uint256_subtract_overflow_1() {
            let a = UInt256::from(100_000_000);
            let b = UInt256::from(150_000_000_000);
            let _ = a - b;
        }

        #[test]
        fn test_uint256_sub() {
            let v1 = UInt256::from(1000_000_000);
            let v2 = UInt256::from(999_999_999);
            let v3 = v1 - v2;
            assert_eq!(v3, UInt256::ONE);
            let v4 = UInt256::from(801_002);
            let v5 = v1 - v4;
            assert_eq!(v5, UInt256::from(999_198_998));
        }
    }

    #[cfg(test)]
    mod test_multiplication {

        use super::*;

        #[test]
        fn test_uint256_mul_communitative() {
            let a = UInt256::from(1000_000_000);
            let b = UInt256::from(200_000_000);
            assert_eq!(a * b, b * a);
        }

        #[test]
        fn test_uint256_mul_identity() {
            let a = UInt256::from(1000_000_000);
            let b = UInt256::from(1);
            let c = a * b;
            assert_eq!(c, a);
        }

        #[test]
        fn test_uint256_mul_zero_property() {
            let a = UInt256::from(1000_000_000);
            let b = UInt256::ZERO;
            let c = a * b;
            assert_eq!(c, UInt256::ZERO);
        }

        #[test]
        fn test_uint256_mul_basic() {
            let u256_value1 = UInt256::from(1000_000_000);
            let u256_value2 = UInt256::from(999_999_999);
            let u256_value3 = u256_value1 * u256_value2;
            assert_eq!(u256_value3, UInt256::from(999_999_999_000_000_000));
        }

        #[test]
        #[should_panic(expected = "attempt to multiply with overflow")]
        fn test_uint256_mul_overflow() {
            let a = UInt256::MAX;
            let b = UInt256::from(2);
            let _ = a * b;
        }
    }

    #[cfg(test)]
    mod test_division {

        use super::*;

        #[test]
        fn test_uint256_div_basic() {
            let a = UInt256::from(10_000_000);
            let b = UInt256::from(2);
            let c = a / b;
            let expected = UInt256::from(5_000_000);
            assert_eq!(c, expected);
        }

        #[test]
        #[should_panic(expected = "division by zero")]
        fn test_uint256_div_by_zero() {
            let _ = UInt256::from(100000) / UInt256::ZERO;
        }

        #[test]
        fn test_uint256_zero_dividend() {
            let a = UInt256::ZERO / UInt256::from(3_000_000);
            assert_eq!(a, UInt256::ZERO);
        }

        #[test]
        fn test_uint256_smaller_dividend() {
            let a = UInt256::from(1_000_000);
            let b = UInt256::from(1_000_000_000);
            let c = a / b;
            assert_eq!(c, UInt256::ZERO);
        }
    }

    #[cfg(test)]
    mod test_endianness {

        use super::*;

        #[test]
        fn test_endian_conversions() {
            let bytes = [
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
                0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10
            ];

            let u256_value = UInt256::from_be_bytes(&bytes);
            let be_bytes = u256_value.to_be_bytes();
            assert_eq!(bytes, *be_bytes.as_ref());
        }

        #[test]
        fn test_big_endianness() {
            let data = [
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x4a,
            ];

            let uint256_value = UInt256::from_be_bytes(&data);
            assert_eq!(UInt256{ high: 0, low: 330, endian: Endian::Big }, uint256_value);
            let b = uint256_value.as_bytes();
            let result = b.as_ref();
            assert_eq!(*result, data);
        }

        #[test]
        fn test_integer_bytes_conversion() {
            let n = UInt256::from(330);
            let a = n.as_bytes();
            let b = a.as_ref();
            // We expect the bytes to be in big-endian format in 32-bytes
            let expected: [u8; 32] = [
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x4a,
            ];
            assert_eq!(b, &expected);
        }

        #[test]
        fn test_endian_from() {
            let bytes = [
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x4a,
            ];
            let a = UInt256::from_le_bytes(&bytes);
            assert_eq!(format!("{}", a), "0x4a01000000000000000000000000000000000000000000000000000000000000");
            assert_eq!(a.endian(), Endian::Little);
            // assert_eq!(a, UInt256::from(18945));
        }

        #[test]
        fn test_to_uint256() {
            let data_be: Vec<u8> = vec![0x01, 0x04a];
            let mut bytes_32 = pad_bytes(&data_be, 0x00, Endian::Big);
            let a = to_uint256(&bytes_32, Endian::Big);
            assert_eq!(a, UInt256::from(330));

            let data_le = vec![0x4a, 0x01];
            bytes_32 = pad_bytes(&data_le, 0x00, Endian::Little);

            let b = to_uint256(&bytes_32, Endian::Little);
            assert_eq!(b, UInt256::from(330));
        }
    }

    #[cfg(test)]
    mod div_tests {
        use super::*;
        #[test]
        fn test_div_basic() {
            // Test division of two simple numbers
            let a = UInt256 { high: 0, low: 10, endian: Endian::Big };
            let b = UInt256 { high: 0, low: 2, endian: Endian::Big };
            let result = a / b;
            let quotient = UInt256 { high: 0, low: 5, endian: Endian::Big };
            assert_eq!(result, quotient);
        }

        #[test]
        fn test_div_by_one() {
            // Test division by one (should return the original number)
            let a = UInt256 { high: 12345, low: 67890, endian: Endian::Big };
            let b = UInt256 { high: 0, low: 1, endian: Endian::Big };
            let result = a / b;
            assert_eq!(result, a);
        }

        #[test]
        fn test_div_large_divisor() {
            // Test division where the divisor is greater than the dividend (should return zero)
            let a = UInt256 { high: 0, low: 5, endian: Endian::Big };
            let b = UInt256 { high: 0, low: 10, endian: Endian::Big };
            let result = a / b;
            let quotient = UInt256 { high: 0, low: 0, endian: Endian::Big };
            assert_eq!(result, quotient);
        }

        #[test]
        fn test_div_self() {
            // Test division of a number by itself (should return one)
            let a = UInt256 { high: 12345, low: 67890, endian: Endian::Big };
            let result = a / a;
            let quotient = UInt256 { high: 0, low: 1, endian: Endian::Big };
            assert_eq!(result, quotient);
        }

        #[test]
        #[should_panic(expected = "division by zero")]
        fn test_div_by_zero() {
            // Test division by zero (should panic)
            let a = UInt256 { high: 1, low: 0, endian: Endian::Big };
            let b = UInt256 { high: 0, low: 0, endian: Endian::Big };
            let _ = a / b; // This should panic
        }

        #[test]
        // #[ignore = "This test hangs"]
        fn test_div_large_numbers() {
            // Test division with large numbers
            let a = UInt256 {
                high: 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF,
                low: 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF,
                endian: Endian::Big,
            };
            let b = UInt256 { high: 0, low: 2, endian: Endian::Big };
            let result = a / b;
            let quotient = UInt256 {
                high: 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF,
                low: 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF,
                endian: Endian::Big,
            };
            assert_eq!(result, quotient);
        }
    }
}