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
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
// Rust language amplification library providing multiple generic trait
// implementations, type wrappers, derive macros and other language enhancements
//
// Written in 2014 by
//     Andrew Poelstra <apoelstra@wpsoftware.net>
// Refactored & fixed in 2021-2024 by
//     Dr. Maxim Orlovsky <orlovsky@ubideco.org>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the MIT License
// along with this software.
// If not, see <https://opensource.org/licenses/MIT>.

use crate::error::{DivError, ParseLengthError};

macro_rules! construct_bigint {
    ($name:ident, $n_words:expr) => {
        /// Large integer type
        ///
        /// The type is composed of little-endian ordered 64-bit words, which represents
        /// its inner representation.
        #[allow(non_camel_case_types)]
        #[derive(Copy, Clone, PartialEq, Eq, Hash, Default)]
        pub struct $name([u64; $n_words]);

        impl $name {
            #[inline]
            /// Converts the object to a raw pointer
            pub fn as_ptr(&self) -> *const u64 {
                let &$name(ref dat) = self;
                dat.as_ptr()
            }

            #[inline]
            /// Converts the object to a mutable raw pointer
            pub fn as_mut_ptr(&mut self) -> *mut u64 {
                let &mut $name(ref mut dat) = self;
                dat.as_mut_ptr()
            }

            #[inline]
            /// Returns the underlying array of words constituting large integer
            pub const fn as_inner(&self) -> &[u64; $n_words] { &self.0 }

            #[inline]
            /// Returns the underlying array of words constituting large integer
            pub const fn into_inner(self) -> [u64; $n_words] { self.0 }

            #[inline]
            /// Constructs integer type from the underlying array of words.
            pub const fn from_inner(array: [u64; $n_words]) -> Self { Self(array) }
        }

        impl $name {
            /// Zero value
            pub const ZERO: $name = $name([0u64; $n_words]);

            /// Value for `1`
            pub const ONE: $name = $name({
                let mut one = [0u64; $n_words];
                one[0] = 1u64;
                one
            });

            /// Bit dimension
            pub const BITS: u32 = $n_words * 64;

            /// Length of the integer in bytes
            pub const BYTES: u8 = $n_words * 8;

            /// Length of the inner representation in 64-bit words
            pub const INNER_LEN: u8 = $n_words;

            /// Returns whether specific bit number is set to `1` or not
            #[inline]
            pub const fn bit(&self, index: usize) -> bool {
                let &$name(ref arr) = self;
                arr[index / 64] & (1 << (index % 64)) != 0
            }

            /// Returns lower 32 bits of the number as `u32`
            #[inline]
            pub const fn low_u32(&self) -> u32 {
                let &$name(ref arr) = self;
                (arr[0] & ::core::u32::MAX as u64) as u32
            }

            /// Returns lower 64 bits of the number as `u32`
            #[inline]
            pub const fn low_u64(&self) -> u64 {
                let &$name(ref arr) = self;
                arr[0] as u64
            }

            /// Returns the number of leading ones in the binary representation of
            /// `self`.
            #[inline]
            pub fn leading_ones(&self) -> u32 {
                for i in 0..$n_words {
                    let leading_ones = (!self[$n_words - i - 1]).leading_zeros();
                    if leading_ones != 64 {
                        return 64 * i as u32 + leading_ones;
                    }
                }
                64 * $n_words
            }

            /// Returns the number of leading zeros in the binary representation of
            /// `self`.
            #[inline]
            pub fn leading_zeros(&self) -> u32 {
                for i in 0..$n_words {
                    let leading_zeros = self[$n_words - i - 1].leading_zeros();
                    if leading_zeros != 64 {
                        return 64 * i as u32 + leading_zeros;
                    }
                }
                64 * $n_words
            }

            /// Returns the number of trailing ones in the binary representation of
            /// `self`.
            #[inline]
            pub fn trailing_ones(&self) -> u32 {
                for i in 0..$n_words {
                    let trailing_ones = (!self[i]).trailing_zeros();
                    if trailing_ones != 64 {
                        return 64 * i as u32 + trailing_ones;
                    }
                }
                64 * $n_words
            }

            /// Returns the number of trailing zeros in the binary representation of
            /// `self`.
            #[inline]
            pub fn trailing_zeros(&self) -> u32 {
                for i in 0..$n_words {
                    let trailing_zeros = self[i].trailing_zeros();
                    if trailing_zeros != 64 {
                        return 64 * i as u32 + trailing_zeros;
                    }
                }
                64 * $n_words
            }

            #[inline]
            pub fn is_zero(&self) -> bool { self[..] == [0; $n_words] }

            #[inline]
            pub fn is_positive(&self) -> bool { !self.is_negative() && !self.is_zero() }

            #[inline]
            pub fn abs(self) -> $name {
                if !self.is_negative() {
                    return self;
                }
                (!self).wrapping_add($name::ONE)
            }

            /// Creates the integer value from a byte array using big-endian
            /// encoding
            pub fn from_be_bytes(bytes: [u8; $n_words * 8]) -> $name {
                Self::_from_be_slice(&bytes)
            }

            /// Creates the integer value from a byte slice using big-endian
            /// encoding
            pub fn from_be_slice(bytes: &[u8]) -> Result<$name, ParseLengthError> {
                if bytes.len() != $n_words * 8 {
                    Err(ParseLengthError {
                        actual: bytes.len(),
                        expected: $n_words * 8,
                    })
                } else {
                    Ok(Self::_from_be_slice(bytes))
                }
            }

            /// Creates the integer value from a byte array using little-endian
            /// encoding
            pub fn from_le_bytes(bytes: [u8; $n_words * 8]) -> $name {
                Self::_from_le_slice(&bytes)
            }

            /// Creates the integer value from a byte slice using little-endian
            /// encoding
            pub fn from_le_slice(bytes: &[u8]) -> Result<$name, ParseLengthError> {
                if bytes.len() != $n_words * 8 {
                    Err(ParseLengthError {
                        actual: bytes.len(),
                        expected: $n_words * 8,
                    })
                } else {
                    Ok(Self::_from_le_slice(bytes))
                }
            }

            fn _from_be_slice(bytes: &[u8]) -> $name {
                let mut slice = [0u64; $n_words];
                slice
                    .iter_mut()
                    .rev()
                    .zip(bytes.chunks(8).into_iter().map(|s| {
                        let mut b = [0u8; 8];
                        b.copy_from_slice(s);
                        b
                    }))
                    .for_each(|(word, bytes)| *word = u64::from_be_bytes(bytes));
                $name(slice)
            }

            fn _from_le_slice(bytes: &[u8]) -> $name {
                let mut slice = [0u64; $n_words];
                slice
                    .iter_mut()
                    .zip(bytes.chunks(8).into_iter().map(|s| {
                        let mut b = [0u8; 8];
                        b.copy_from_slice(s);
                        b
                    }))
                    .for_each(|(word, bytes)| *word = u64::from_le_bytes(bytes));
                $name(slice)
            }

            /// Convert the integer into a byte array using big-endian encoding
            pub fn to_be_bytes(self) -> [u8; $n_words * 8] {
                let mut res = [0; $n_words * 8];
                for i in 0..$n_words {
                    let start = i * 8;
                    res[start..start + 8]
                        .copy_from_slice(&self.0[$n_words - (i + 1)].to_be_bytes());
                }
                res
            }

            /// Convert a integer into a byte array using little-endian encoding
            pub fn to_le_bytes(self) -> [u8; $n_words * 8] {
                let mut res = [0; $n_words * 8];
                for i in 0..$n_words {
                    let start = i * 8;
                    res[start..start + 8].copy_from_slice(&self.0[i].to_le_bytes());
                }
                res
            }

            // divmod like operation, returns (quotient, remainder)
            #[inline]
            fn div_rem(self, other: Self) -> Result<(Self, Self), DivError> {
                // Check for division by 0
                if other.is_zero() {
                    return Err(DivError::ZeroDiv);
                }
                if other.is_negative() && self == Self::MIN && other == Self::ONE.wrapping_neg() {
                    return Err(DivError::Overflow);
                }
                let mut me = self.abs();
                let mut you = other.abs();
                let mut ret = [0u64; $n_words];
                if self.is_negative() == other.is_negative() && me < you {
                    return Ok(($name(ret), self));
                }

                let shift = me.bits_required() - you.bits_required();
                you <<= shift;
                for i in (0..=shift).rev() {
                    if me >= you {
                        ret[i / 64] |= 1 << (i % 64);
                        me -= you;
                    }
                    you >>= 1;
                }

                Ok((
                    if self.is_negative() == other.is_negative() {
                        Self(ret)
                    } else {
                        -Self(ret)
                    },
                    if self.is_negative() { -me } else { me },
                ))
            }

            #[inline]
            fn div_rem_euclid(self, other: Self) -> Result<(Self, Self), DivError> {
                self.div_rem(other).map(|(q, r)| {
                    (
                        match (r.is_negative(), other.is_positive()) {
                            (true, true) => q.wrapping_sub(Self::ONE),
                            (true, false) => q.wrapping_add(Self::ONE),
                            _ => q,
                        },
                        match (r.is_negative(), other.is_positive()) {
                            (true, true) => r.wrapping_add(other),
                            (true, false) => r.wrapping_sub(other),
                            _ => r,
                        },
                    )
                })
            }
        }

        impl From<bool> for $name {
            fn from(init: bool) -> $name {
                let mut ret = [0; $n_words];
                if init {
                    ret[0] = 1;
                }
                $name(ret)
            }
        }

        impl From<u8> for $name {
            fn from(init: u8) -> $name {
                let mut ret = [0; $n_words];
                ret[0] = init as u64;
                $name(ret)
            }
        }

        impl From<u16> for $name {
            fn from(init: u16) -> $name {
                let mut ret = [0; $n_words];
                ret[0] = init as u64;
                $name(ret)
            }
        }

        impl From<u32> for $name {
            fn from(init: u32) -> $name {
                let mut ret = [0; $n_words];
                ret[0] = init as u64;
                $name(ret)
            }
        }

        impl From<u64> for $name {
            fn from(init: u64) -> $name {
                let mut ret = [0; $n_words];
                ret[0] = init;
                $name(ret)
            }
        }

        impl From<u128> for $name {
            fn from(init: u128) -> $name {
                let mut ret = [0; $n_words * 8];
                for (pos, byte) in init.to_le_bytes().iter().enumerate() {
                    ret[pos] = *byte;
                }
                $name::from_le_bytes(ret)
            }
        }

        impl<'a> ::core::convert::TryFrom<&'a [u64]> for $name {
            type Error = $crate::error::ParseLengthError;
            fn try_from(data: &'a [u64]) -> Result<$name, Self::Error> {
                if data.len() != $n_words {
                    Err($crate::error::ParseLengthError {
                        actual: data.len(),
                        expected: $n_words,
                    })
                } else {
                    let mut bytes = [0u64; $n_words];
                    bytes.copy_from_slice(data);
                    Ok(Self::from_inner(bytes))
                }
            }
        }
        impl ::core::ops::Index<usize> for $name {
            type Output = u64;

            #[inline]
            fn index(&self, index: usize) -> &u64 { &self.0[index] }
        }

        impl ::core::ops::Index<::core::ops::Range<usize>> for $name {
            type Output = [u64];

            #[inline]
            fn index(&self, index: ::core::ops::Range<usize>) -> &[u64] { &self.0[index] }
        }

        impl ::core::ops::Index<::core::ops::RangeTo<usize>> for $name {
            type Output = [u64];

            #[inline]
            fn index(&self, index: ::core::ops::RangeTo<usize>) -> &[u64] { &self.0[index] }
        }

        impl ::core::ops::Index<::core::ops::RangeFrom<usize>> for $name {
            type Output = [u64];

            #[inline]
            fn index(&self, index: ::core::ops::RangeFrom<usize>) -> &[u64] { &self.0[index] }
        }

        impl ::core::ops::Index<::core::ops::RangeFull> for $name {
            type Output = [u64];

            #[inline]
            fn index(&self, _: ::core::ops::RangeFull) -> &[u64] { &self.0[..] }
        }

        impl PartialOrd for $name {
            #[inline]
            fn partial_cmp(&self, other: &$name) -> Option<::core::cmp::Ordering> {
                Some(self.cmp(&other))
            }
        }

        impl Ord for $name {
            #[inline]
            fn cmp(&self, other: &$name) -> ::core::cmp::Ordering {
                // We need to manually implement ordering because the words in our array
                // are in little-endian order, i.e. the most significant word is last in
                // the array, and the auto derive for array Ord compares the elements
                // from first to last.
                for i in 0..$n_words {
                    let self_word = self[$n_words - 1 - i];
                    let other_word = other[$n_words - 1 - i];

                    // If this is a signed type, start with signed comparison on the
                    // most-significant word, then continue with unsigned comparisons on
                    // the rest of the words.
                    let res = if i == 0 && Self::IS_SIGNED_TYPE {
                        (self_word as i64).cmp(&(other_word as i64))
                    } else {
                        self_word.cmp(&other_word)
                    };

                    if res != ::core::cmp::Ordering::Equal {
                        return res;
                    }
                }
                ::core::cmp::Ordering::Equal
            }
        }

        impl ::core::ops::Neg for $name {
            type Output = Self;
            fn neg(self) -> Self::Output {
                assert!(
                    $name::MIN != $name([::core::u64::MAX; $n_words]),
                    "attempt to negate unsigned number"
                );
                assert!(
                    self != $name::MIN,
                    "attempt to negate the minimum value, which would overflow"
                );
                (!self).wrapping_add($name::ONE)
            }
        }

        impl $name {
            /// Checked integer addition. Computes `self + rhs`, returning `None` if
            /// overflow occurred.
            pub fn checked_add<T>(self, other: T) -> Option<$name>
            where T: Into<$name> {
                let (res, flag) = self.overflowing_add(other);
                if flag { None } else { Some(res) }
            }

            /// Saturating integer addition. Computes `self + rhs`, saturating at the
            /// numeric bounds instead of overflowing.
            pub fn saturating_add<T>(self, other: T) -> $name
            where T: Into<$name> {
                let (res, flag) = self.overflowing_add(other);
                if flag { Self::MAX } else { res }
            }

            /// Calculates `self + rhs`
            ///
            /// Returns a tuple of the addition along with a boolean indicating whether
            /// an arithmetic overflow would occur. If an overflow would have occurred
            /// then the wrapped value is returned.
            pub fn overflowing_add<T>(self, other: T) -> ($name, bool)
            where T: Into<$name> {
                let $name(ref me) = self;
                let other = other.into();
                let $name(ref you) = other;
                let mut ret = [0u64; $n_words];
                let mut carry = 0u64;
                for i in 0..$n_words {
                    let (res, flag) = me[i].overflowing_add(carry);
                    carry = flag as u64;
                    let (res, flag) = res.overflowing_add(you[i]);
                    carry += flag as u64;
                    ret[i] = res;
                }
                let ret = Self(ret);
                let overflow = if !Self::IS_SIGNED_TYPE {
                    carry > 0
                } else {
                    self != Self::MIN &&
                        other != Self::MIN &&
                        (self.is_negative() == other.is_negative()) &&
                        (self.is_negative() != ret.is_negative())
                };
                (ret, overflow)
            }

            /// Wrapping (modular) addition. Computes `self + rhs`, wrapping around at
            /// the boundary of the type.
            pub fn wrapping_add<T>(self, other: T) -> $name
            where T: Into<$name> {
                self.overflowing_add(other).0
            }

            /// Checked integer subtraction. Computes `self - rhs`, returning `None` if
            /// overflow occurred.
            pub fn checked_sub<T>(self, other: T) -> Option<$name>
            where T: Into<$name> {
                let (res, flag) = self.overflowing_sub(other);
                if flag { None } else { Some(res) }
            }

            /// Saturating integer subtraction. Computes `self - rhs`, saturating at the
            /// numeric bounds instead of overflowing.
            pub fn saturating_sub<T>(self, other: T) -> $name
            where T: Into<$name> {
                let (res, flag) = self.overflowing_sub(other);
                if flag { Self::MAX } else { res }
            }

            /// Calculates `self - rhs`
            ///
            /// Returns a tuple of the subtraction along with a boolean indicating
            /// whether an arithmetic overflow would occur. If an overflow would
            /// have occurred then the wrapped value is returned.
            pub fn overflowing_sub<T>(self, other: T) -> ($name, bool)
            where T: Into<$name> {
                let other = other.into();
                if !Self::IS_SIGNED_TYPE {
                    (self.wrapping_add(!other).wrapping_add($name::ONE), self < other)
                } else {
                    self.overflowing_add((!other).wrapping_add($name::ONE))
                }
            }

            /// Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around
            /// at the boundary of the type.
            pub fn wrapping_sub<T>(self, other: T) -> $name
            where T: Into<$name> {
                self.overflowing_sub(other).0
            }

            /// Checked integer multiplication. Computes `self * rhs`, returning `None`
            /// if overflow occurred.
            pub fn checked_mul<T>(self, other: T) -> Option<$name>
            where T: Into<$name> {
                let (res, flag) = self.overflowing_mul(other);
                if flag { None } else { Some(res) }
            }

            /// Saturating integer multiplication. Computes `self * rhs`, saturating at
            /// the numeric bounds instead of overflowing.
            pub fn saturating_mul<T>(self, other: T) -> $name
            where T: Into<$name> {
                let (res, flag) = self.overflowing_mul(other);
                if flag { Self::MAX } else { res }
            }

            /// Wrapping (modular) multiplication. Computes `self * rhs`, wrapping
            /// around at the boundary of the type.
            pub fn wrapping_mul<T>(self, other: T) -> $name
            where T: Into<$name> {
                self.overflowing_mul(other).0
            }

            /// Calculates `self / rhs`
            ///
            /// Returns a tuple of the divisor along with a boolean indicating
            /// whether an arithmetic overflow would occur. If an overflow would
            /// have occurred then the wrapped value is returned.
            pub fn overflowing_div<T>(self, other: T) -> ($name, bool)
            where T: Into<$name> {
                let rhs = other.into();
                match self.div_rem(rhs) {
                    Err(DivError::Overflow) => (Self::MIN, true),
                    res => (res.expect("Error occurred during bigint division").0, false),
                }
            }

            /// Wrapping (modular) division. Calculates `self / rhs`,
            /// wrapping around at the boundary of the type.
            ///
            /// The only case where such wrapping can occur is when one divides
            /// `MIN / -1` on a signed type (where MIN is the negative minimal value for
            /// the type); this is equivalent to -MIN, a positive value that is
            /// too large to represent in the type.
            /// In such a case, this function returns MIN itself.
            pub fn wrapping_div<T>(self, other: T) -> $name
            where T: Into<$name> {
                self.overflowing_div(other.into()).0
            }

            /// Checked integer division. Computes `self / rhs`,
            /// returning None if `rhs == 0` or the division results in overflow.
            pub fn checked_div<T>(self, other: T) -> Option<$name>
            where T: Into<$name> {
                self.div_rem(other.into()).ok().map(|(q, _)| q)
            }

            /// Saturating integer division. Computes `self / rhs`,
            /// saturating at the numeric bounds instead of overflowing.
            pub fn saturating_div<T>(self, other: T) -> $name
            where T: Into<$name> {
                let rhs = other.into();
                match self.div_rem(rhs) {
                    Err(DivError::Overflow) => Self::MAX,
                    res => res.expect("Error occurred during bigint division").0,
                }
            }

            /// Calculates the remainder when `self` is divided by `rhs`.
            ///
            /// Returns a tuple of the remainder after dividing along with a boolean
            /// indicating whether an arithmetic overflow would occur.
            /// If an overflow would occur then 0 is returned.
            pub fn overflowing_rem<T>(self, other: T) -> ($name, bool)
            where T: Into<$name> {
                let rhs = other.into();
                match self.div_rem(rhs) {
                    Err(DivError::Overflow) => (Self::ZERO, true),
                    res => (res.expect("Error occurred during bigint division").1, false),
                }
            }

            /// Wrapping (modular) remainder.
            /// Computes self % rhs, wrapping around at the boundary of the type.
            ///
            /// Such wrap-around never actually occurs mathematically;
            /// implementation artifacts make x % y invalid for MIN / -1
            /// on a signed type (where MIN is the negative minimal value).
            /// In such a case, this function returns 0.
            pub fn wrapping_rem<T>(self, other: T) -> $name
            where T: Into<$name> {
                self.overflowing_rem(other.into()).0
            }

            /// Checked integer remainder. Computes `self % rhs`,
            /// returning None if `rhs == 0` or the division results in overflow.
            pub fn checked_rem<T>(self, other: T) -> Option<$name>
            where T: Into<$name> {
                self.div_rem(other.into()).ok().map(|(_, r)| r)
            }

            /// Calculates the quotient of Euclidean division of `self` by `rhs`.
            ///
            /// This computes the integer `q` such that `self = q * rhs + r`,
            /// with `r = self.rem_euclid(rhs)` and `0 <= r < abs(rhs)`.
            ///
            /// In other words, the result is `self / rhs` rounded to the integer `q`
            /// such that `self >= q * rhs`. If `self > 0`,
            /// this is equal to round towards zero (the default in Rust);
            /// if `self < 0`, this is equal to round towards +/- infinity.
            pub fn div_euclid<T>(self, other: T) -> $name
            where T: Into<$name> {
                self.div_rem_euclid(other.into())
                    .expect("Error occurred during bigint division")
                    .0
            }

            /// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
            ///
            /// Returns a tuple of the divisor along with a boolean indicating
            /// whether an arithmetic overflow would occur.
            /// If an overflow would occur then `self` is returned.
            pub fn overflowing_div_euclid<T>(self, other: T) -> ($name, bool)
            where T: Into<$name> {
                match self.div_rem_euclid(other.into()) {
                    Err(DivError::Overflow) => (Self::MIN, true),
                    res => (res.expect("Error occurred during bigint division").0, false),
                }
            }

            /// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`,
            /// wrapping around at the boundary of the type.
            ///
            /// Wrapping will only occur in `MIN / -1` on a signed type
            /// (where MIN is the negative minimal value for the type).
            /// This is equivalent to `-MIN`, a positive value
            /// that is too large to represent in the type.
            /// In this case, this method returns `MIN` itself.
            pub fn wrapping_div_euclid<T>(self, other: T) -> $name
            where T: Into<$name> {
                self.overflowing_div_euclid(other.into()).0
            }

            /// Checked Euclidean division. Computes `self.div_euclid(rhs)`,
            /// returning None if `rhs == 0` or the division results in overflow.
            pub fn checked_div_euclid<T>(self, other: T) -> Option<$name>
            where T: Into<$name> {
                self.div_rem_euclid(other.into()).ok().map(|(q, _)| q)
            }

            /// Calculates the least nonnegative remainder of `self (mod rhs)`.
            ///
            /// This is done as if by the Euclidean division algorithm –
            /// given `r = self.rem_euclid(rhs)`, `self = rhs * self.div_euclid(rhs) +
            /// r`, and `0 <= r < abs(rhs)`.
            pub fn rem_euclid<T>(self, other: T) -> $name
            where T: Into<$name> {
                self.div_rem_euclid(other.into())
                    .expect("Error occurred during bigint division")
                    .1
            }

            /// Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`.
            ///
            /// Returns a tuple of the remainder after dividing along with a boolean
            /// indicating whether an arithmetic overflow would occur.
            /// If an overflow would occur then 0 is returned.
            pub fn overflowing_rem_euclid<T>(self, other: T) -> ($name, bool)
            where T: Into<$name> {
                match self.div_rem_euclid(other.into()) {
                    Err(DivError::Overflow) => (Self::ZERO, true),
                    res => (res.expect("Error occurred during bigint division").1, false),
                }
            }

            /// Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`,
            /// wrapping around at the boundary of the type.
            ///
            /// Wrapping will only occur in `MIN % -1` on a signed type
            /// (where `MIN` is the negative minimal value for the type).
            /// In this case, this method returns 0.
            pub fn wrapping_rem_euclid<T>(self, other: T) -> $name
            where T: Into<$name> {
                self.overflowing_rem_euclid(other.into()).0
            }

            /// Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`,
            /// returning None if `rhs == 0` or the division results in overflow.
            pub fn checked_rem_euclid<T>(self, other: T) -> Option<$name>
            where T: Into<$name> {
                self.div_rem_euclid(other.into()).ok().map(|(_, r)| r)
            }

            /// Checked shift left. Computes self << rhs,
            /// returning None if rhs is larger than or equal to the number of bits in
            /// self.
            pub fn checked_shl(self, rhs: u32) -> Option<$name> {
                match rhs < Self::BITS {
                    true => Some(self << (rhs as usize)),
                    false => None,
                }
            }

            /// Checked shift right. Computes self >> rhs,
            /// returning None if rhs is larger than or equal to the number of bits in
            /// self.
            pub fn checked_shr(self, rhs: u32) -> Option<$name> {
                match rhs < Self::BITS {
                    true => Some(self >> (rhs as usize)),
                    false => None,
                }
            }

            /// Wrapping (modular) negation. Computes -self,
            /// wrapping around at the boundary of the type.
            /// Since unsigned types do not have negative equivalents
            /// all applications of this function will wrap (except for -0).
            /// For values smaller than the corresponding signed type's maximum
            /// the result is the same as casting the corresponding signed value.
            /// Any larger values are equivalent to MAX + 1 - (val - MAX - 1)
            /// where MAX is the corresponding signed type's maximum.
            pub fn wrapping_neg(self) -> $name { (!self).wrapping_add(Self::ONE) }
        }

        impl<T> ::core::ops::Add<T> for $name
        where T: Into<$name>
        {
            type Output = $name;

            fn add(self, other: T) -> $name {
                let (res, flag) = self.overflowing_add(other);
                assert!(!flag, "attempt to add with overflow");
                res
            }
        }
        impl<T> ::core::ops::AddAssign<T> for $name
        where T: Into<$name>
        {
            #[inline]
            fn add_assign(&mut self, rhs: T) { self.0 = (*self + rhs).0 }
        }

        impl<T> ::core::ops::Sub<T> for $name
        where T: Into<$name>
        {
            type Output = $name;

            #[inline]
            fn sub(self, other: T) -> $name {
                let (res, flag) = self.overflowing_sub(other);
                assert!(!flag, "attempt to subtract with overflow");
                res
            }
        }
        impl<T> ::core::ops::SubAssign<T> for $name
        where T: Into<$name>
        {
            #[inline]
            fn sub_assign(&mut self, rhs: T) { self.0 = (*self - rhs).0 }
        }

        impl<T> ::core::ops::Mul<T> for $name
        where T: Into<$name>
        {
            type Output = $name;

            fn mul(self, other: T) -> $name {
                let (res, flag) = self.overflowing_mul(other);
                assert!(!flag, "attempt to mul with overflow");
                res
            }
        }
        impl<T> ::core::ops::MulAssign<T> for $name
        where T: Into<$name>
        {
            #[inline]
            fn mul_assign(&mut self, rhs: T) { self.0 = (*self * rhs).0 }
        }

        impl<T> ::core::ops::Div<T> for $name
        where T: Into<$name>
        {
            type Output = $name;

            fn div(self, other: T) -> $name {
                self.div_rem(other.into())
                    .expect("Error occurred during bigint division")
                    .0
            }
        }
        impl<T> ::core::ops::DivAssign<T> for $name
        where T: Into<$name>
        {
            #[inline]
            fn div_assign(&mut self, rhs: T) { self.0 = (*self / rhs).0 }
        }

        impl<T> ::core::ops::Rem<T> for $name
        where T: Into<$name>
        {
            type Output = $name;

            fn rem(self, other: T) -> $name {
                self.div_rem(other.into())
                    .expect("Error occurred during bigint division")
                    .1
            }
        }
        impl<T> ::core::ops::RemAssign<T> for $name
        where T: Into<$name>
        {
            #[inline]
            fn rem_assign(&mut self, rhs: T) { self.0 = (*self % rhs).0 }
        }

        impl<T> ::core::ops::BitAnd<T> for $name
        where T: Into<$name>
        {
            type Output = $name;

            #[inline]
            fn bitand(self, other: T) -> $name {
                let $name(ref arr1) = self;
                let $name(ref arr2) = other.into();
                let mut ret = [0u64; $n_words];
                for i in 0..$n_words {
                    ret[i] = arr1[i] & arr2[i];
                }
                $name(ret)
            }
        }
        impl<T> ::core::ops::BitAndAssign<T> for $name
        where T: Into<$name>
        {
            #[inline]
            fn bitand_assign(&mut self, rhs: T) { self.0 = (*self & rhs).0 }
        }

        impl<T> ::core::ops::BitXor<T> for $name
        where T: Into<$name>
        {
            type Output = $name;

            #[inline]
            fn bitxor(self, other: T) -> $name {
                let $name(ref arr1) = self;
                let $name(ref arr2) = other.into();
                let mut ret = [0u64; $n_words];
                for i in 0..$n_words {
                    ret[i] = arr1[i] ^ arr2[i];
                }
                $name(ret)
            }
        }
        impl<T> ::core::ops::BitXorAssign<T> for $name
        where T: Into<$name>
        {
            #[inline]
            fn bitxor_assign(&mut self, rhs: T) { self.0 = (*self ^ rhs).0 }
        }

        impl<T> ::core::ops::BitOr<T> for $name
        where T: Into<$name>
        {
            type Output = $name;

            #[inline]
            fn bitor(self, other: T) -> $name {
                let $name(ref arr1) = self;
                let $name(ref arr2) = other.into();
                let mut ret = [0u64; $n_words];
                for i in 0..$n_words {
                    ret[i] = arr1[i] | arr2[i];
                }
                $name(ret)
            }
        }
        impl<T> ::core::ops::BitOrAssign<T> for $name
        where T: Into<$name>
        {
            #[inline]
            fn bitor_assign(&mut self, rhs: T) { self.0 = (*self | rhs).0 }
        }

        impl ::core::ops::Shl<usize> for $name {
            type Output = $name;

            fn shl(self, shift: usize) -> $name {
                let $name(ref original) = self;
                let mut ret = [0u64; $n_words];
                let word_shift = shift / 64;
                let bit_shift = shift % 64;
                for i in 0..$n_words {
                    // Shift
                    if bit_shift < 64 && i + word_shift < $n_words {
                        ret[i + word_shift] += original[i] << bit_shift;
                    }
                    // Carry
                    if bit_shift > 0 && i + word_shift + 1 < $n_words {
                        ret[i + word_shift + 1] += original[i] >> (64 - bit_shift);
                    }
                }
                $name(ret)
            }
        }
        impl ::core::ops::ShlAssign<usize> for $name {
            #[inline]
            fn shl_assign(&mut self, rhs: usize) { self.0 = (*self << rhs).0 }
        }

        impl ::core::ops::Shr<usize> for $name {
            type Output = $name;

            fn shr(self, shift: usize) -> $name {
                let $name(ref original) = self;
                let mut ret = [0u64; $n_words];
                let word_shift = shift / 64;
                let bit_shift = shift % 64;
                for i in word_shift..$n_words {
                    // Shift
                    ret[i - word_shift] += original[i] >> bit_shift;
                    // Carry
                    if bit_shift > 0 && i < $n_words - 1 {
                        ret[i - word_shift] += original[i + 1] << (64 - bit_shift);
                    }
                }
                if self.is_negative() {
                    ret[$n_words - 1] |= 0x8000_0000_0000_0000
                }
                $name(ret)
            }
        }

        impl ::core::ops::ShrAssign<usize> for $name {
            #[inline]
            fn shr_assign(&mut self, rhs: usize) { self.0 = (*self >> rhs).0 }
        }

        impl ::core::ops::Not for $name {
            type Output = $name;

            #[inline]
            fn not(self) -> $name {
                let $name(ref arr) = self;
                let mut ret = [0u64; $n_words];
                for i in 0..$n_words {
                    ret[i] = !arr[i];
                }
                $name(ret)
            }
        }

        impl ::core::fmt::Debug for $name {
            fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
                let &$name(ref data) = self;
                write!(f, "0x")?;
                for ch in data.iter().rev() {
                    write!(f, "{:016x}", ch)?;
                }
                Ok(())
            }
        }

        impl ::core::fmt::Display for $name {
            fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
                ::core::fmt::Debug::fmt(self, f)
            }
        }

        #[cfg(feature = "alloc")]
        impl ::core::fmt::UpperHex for $name {
            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> Result<(), ::core::fmt::Error> {
                use alloc::format;
                use alloc::string::String;

                let mut hex = String::new();
                for chunk in self.0.iter().rev().skip_while(|x| **x == 0) {
                    if hex.is_empty() {
                        hex.push_str(&format!("{:X}", chunk));
                    } else {
                        hex.push_str(&format!("{:0>16X}", chunk));
                    }
                }
                if hex.is_empty() {
                    hex.push_str("0");
                }

                let mut prefix = if f.alternate() {
                    String::from("0x")
                } else {
                    String::new()
                };
                if let Some(width) = f.width() {
                    if f.sign_aware_zero_pad() {
                        let missing_width =
                            width.saturating_sub(prefix.len()).saturating_sub(hex.len());
                        prefix.push_str(&"0".repeat(missing_width));
                    }
                }

                prefix.push_str(&hex);
                f.pad(&prefix)
            }
        }

        #[cfg(feature = "alloc")]
        impl ::core::fmt::LowerHex for $name {
            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> Result<(), ::core::fmt::Error> {
                use alloc::format;
                use alloc::string::String;

                let mut hex = String::new();
                for chunk in self.0.iter().rev().skip_while(|x| **x == 0) {
                    if hex.is_empty() {
                        hex.push_str(&format!("{:x}", chunk));
                    } else {
                        hex.push_str(&format!("{:0>16x}", chunk));
                    }
                }
                if hex.is_empty() {
                    hex.push_str("0");
                }

                let mut prefix = if f.alternate() {
                    String::from("0x")
                } else {
                    String::new()
                };
                if let Some(width) = f.width() {
                    if f.sign_aware_zero_pad() {
                        let missing_width =
                            width.saturating_sub(prefix.len()).saturating_sub(hex.len());
                        prefix.push_str(&"0".repeat(missing_width));
                    }
                }

                prefix.push_str(&hex);
                f.pad(&prefix)
            }
        }

        #[cfg(feature = "alloc")]
        impl ::core::fmt::Octal for $name {
            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> Result<(), ::core::fmt::Error> {
                use alloc::format;
                use alloc::string::String;

                let mut octal = String::new();
                for chunk in self.0.iter().rev().skip_while(|x| **x == 0) {
                    if octal.is_empty() {
                        octal.push_str(&format!("{:o}", chunk));
                    } else {
                        octal.push_str(&format!("{:0>22o}", chunk));
                    }
                }
                if octal.is_empty() {
                    octal.push_str("0");
                }

                let mut prefix = if f.alternate() {
                    String::from("0o")
                } else {
                    String::new()
                };
                if let Some(width) = f.width() {
                    if f.sign_aware_zero_pad() {
                        let missing_width = width
                            .saturating_sub(prefix.len())
                            .saturating_sub(octal.len());
                        prefix.push_str(&"0".repeat(missing_width));
                    }
                }

                prefix.push_str(&octal);
                f.pad(&prefix)
            }
        }

        #[cfg(feature = "alloc")]
        impl ::core::fmt::Binary for $name {
            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> Result<(), ::core::fmt::Error> {
                use alloc::format;
                use alloc::string::String;

                let mut binary = String::new();
                for chunk in self.0.iter().rev().skip_while(|x| **x == 0) {
                    if binary.is_empty() {
                        binary.push_str(&format!("{:b}", chunk));
                    } else {
                        binary.push_str(&format!("{:0>64b}", chunk));
                    }
                }
                if binary.is_empty() {
                    binary.push_str("0");
                }

                let mut prefix = if f.alternate() {
                    String::from("0b")
                } else {
                    String::new()
                };
                if let Some(width) = f.width() {
                    if f.sign_aware_zero_pad() {
                        let missing_width = width
                            .saturating_sub(prefix.len())
                            .saturating_sub(binary.len());
                        prefix.push_str(&"0".repeat(missing_width));
                    }
                }

                prefix.push_str(&binary);
                f.pad(&prefix)
            }
        }

        #[cfg(feature = "serde")]
        impl $crate::serde::Serialize for $name {
            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
            where S: $crate::serde::Serializer {
                use $crate::hex::ToHex;
                let bytes = self.to_be_bytes();
                if serializer.is_human_readable() {
                    serializer.serialize_str(&bytes.to_hex())
                } else {
                    serializer.serialize_bytes(&bytes)
                }
            }
        }

        #[cfg(feature = "serde")]
        impl<'de> $crate::serde::Deserialize<'de> for $name {
            fn deserialize<D: $crate::serde::Deserializer<'de>>(
                deserializer: D,
            ) -> Result<Self, D::Error> {
                use ::std::fmt;
                use $crate::hex::FromHex;
                use $crate::serde::de;
                struct Visitor;
                impl<'de> de::Visitor<'de> for Visitor {
                    type Value = $name;

                    fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                        write!(
                            f,
                            "{} bytes or a hex string with {} characters",
                            $n_words * 8,
                            $n_words * 8 * 2
                        )
                    }

                    fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
                    where E: de::Error {
                        let bytes = Vec::from_hex(s)
                            .map_err(|_| de::Error::invalid_value(de::Unexpected::Str(s), &self))?;
                        $name::from_be_slice(&bytes)
                            .map_err(|_| de::Error::invalid_length(bytes.len() * 2, &self))
                    }

                    fn visit_bytes<E>(self, bytes: &[u8]) -> Result<Self::Value, E>
                    where E: de::Error {
                        $name::from_be_slice(bytes)
                            .map_err(|_| de::Error::invalid_length(bytes.len(), &self))
                    }
                }

                if deserializer.is_human_readable() {
                    deserializer.deserialize_str(Visitor)
                } else {
                    deserializer.deserialize_bytes(Visitor)
                }
            }
        }
    };
}

macro_rules! construct_signed_bigint_methods {
    ($name:ident, $n_words:expr) => {
        impl From<i8> for $name {
            fn from(init: i8) -> $name {
                let bytes = init.to_le_bytes();
                let mut ret = [if init.is_negative() {
                    ::core::u8::MAX
                } else {
                    0
                }; $n_words * 8];
                for i in 0..bytes.len() {
                    ret[i] = bytes[i]
                }
                $name::from_le_bytes(ret)
            }
        }

        impl From<i16> for $name {
            fn from(init: i16) -> $name {
                let bytes = init.to_le_bytes();
                let mut ret = [if init.is_negative() {
                    ::core::u8::MAX
                } else {
                    0
                }; $n_words * 8];
                for i in 0..bytes.len() {
                    ret[i] = bytes[i]
                }
                $name::from_le_bytes(ret)
            }
        }

        impl From<i32> for $name {
            fn from(init: i32) -> $name {
                let bytes = init.to_le_bytes();
                let mut ret = [if init.is_negative() {
                    ::core::u8::MAX
                } else {
                    0
                }; $n_words * 8];
                for i in 0..bytes.len() {
                    ret[i] = bytes[i]
                }
                $name::from_le_bytes(ret)
            }
        }

        impl From<i64> for $name {
            fn from(init: i64) -> $name {
                let bytes = init.to_le_bytes();
                let mut ret = [if init.is_negative() {
                    ::core::u8::MAX
                } else {
                    0
                }; $n_words * 8];
                for i in 0..bytes.len() {
                    ret[i] = bytes[i]
                }
                $name::from_le_bytes(ret)
            }
        }

        impl From<i128> for $name {
            fn from(init: i128) -> $name {
                let bytes = init.to_le_bytes();
                let mut ret = [if init.is_negative() {
                    ::core::u8::MAX
                } else {
                    0
                }; $n_words * 8];
                for i in 0..bytes.len() {
                    ret[i] = bytes[i]
                }
                $name::from_le_bytes(ret)
            }
        }

        impl $name {
            const IS_SIGNED_TYPE: bool = true;

            /// Minimum value
            pub const MIN: $name = {
                let mut min = [0u64; $n_words];
                min[$n_words - 1] = 0x8000_0000_0000_0000;
                $name(min)
            };

            /// Maximum value
            pub const MAX: $name = {
                let mut max = [::core::u64::MAX; $n_words];
                max[$n_words - 1] = ::core::u64::MAX >> 1;
                $name(max)
            };

            #[inline]
            pub fn is_negative(&self) -> bool {
                self[($name::INNER_LEN - 1) as usize] & 0x8000_0000_0000_0000 != 0
            }

            /// Return the least number of bits needed to represent the number
            #[inline]
            pub fn bits_required(&self) -> usize {
                let &$name(ref arr) = self;
                let iter = arr.iter().rev().take($n_words - 1);
                if self.is_negative() {
                    let ctr = iter.take_while(|&&b| b == ::core::u64::MAX).count();
                    (0x40 * ($n_words - ctr)) + 1 -
                        (!arr[$n_words - ctr - 1]).leading_zeros() as usize
                } else {
                    let ctr = iter.take_while(|&&b| b == ::core::u64::MIN).count();
                    (0x40 * ($n_words - ctr)) + 1 - arr[$n_words - ctr - 1].leading_zeros() as usize
                }
            }

            /// Calculates `self * rhs`
            ///
            /// Returns a tuple of the multiplication along with a boolean indicating
            /// whether an arithmetic overflow would occur. If an overflow would
            /// have occurred then the wrapped value is returned.
            pub fn overflowing_mul<T>(self, other: T) -> ($name, bool)
            where T: Into<$name> {
                let sub = if self != $name::MIN { -self } else { self };
                let mut p_high = $name::ZERO;
                let mut p_low = other.into();
                let mut prev = false;
                for _i in 0..$name::BITS {
                    let p_low_trailing_bit = (p_low[0] & 1) != 0;
                    p_high = match (p_low_trailing_bit, prev) {
                        (false, true) => p_high.wrapping_add(self),
                        (true, false) => p_high.wrapping_add(sub),
                        _ => p_high,
                    };
                    prev = p_low_trailing_bit;
                    p_low >>= 1;
                    p_low = match p_high[0] & 1 {
                        0 => p_low & $name::MAX,
                        _ => p_low | $name::MIN,
                    };
                    p_high >>= 1;
                }
                let negative_overflow =
                    p_low.is_negative() && p_high != $name([::core::u64::MAX; $n_words]);
                let positive_overflow = !p_low.is_negative() && p_high != $name::ZERO;
                (p_low, negative_overflow || positive_overflow)
            }
        }
    };
}

macro_rules! construct_unsigned_bigint_methods {
    ($name:ident, $n_words:expr) => {
        impl $name {
            const IS_SIGNED_TYPE: bool = false;

            /// Minimum value
            pub const MIN: $name = $name([0u64; $n_words]);

            /// Maximum value
            pub const MAX: $name = $name([::core::u64::MAX; $n_words]);

            #[inline]
            pub const fn is_negative(&self) -> bool { false }

            /// Return the least number of bits needed to represent the number
            #[inline]
            pub fn bits_required(&self) -> usize {
                let &$name(ref arr) = self;
                let iter = arr.iter().rev().take($n_words - 1);
                let ctr = iter.take_while(|&&b| b == ::core::u64::MIN).count();
                (0x40 * ($n_words - ctr)) - arr[$n_words - ctr - 1].leading_zeros() as usize
            }

            /// Calculates `self * rhs`
            ///
            /// Returns a tuple of the multiplication along with a boolean indicating
            /// whether an arithmetic overflow would occur. If an overflow would
            /// have occurred then the wrapped value is returned.
            pub fn overflowing_mul<T>(self, other: T) -> ($name, bool)
            where T: Into<$name> {
                let $name(ref me) = self;
                let $name(ref you) = other.into();
                let mut ret = [0u64; $n_words];
                let mut overflow = false;
                for i in 0..$n_words {
                    let mut carry = 0u64;
                    for j in 0..$n_words {
                        if i + j >= $n_words {
                            if me[i] > 0 && you[j] > 0 {
                                overflow = true
                            }
                            continue;
                        }
                        let prev_carry = carry;
                        let res = me[i] as u128 * you[j] as u128;
                        carry = (res >> 64) as u64;
                        let mul = (res & ::core::u64::MAX as u128) as u64;
                        let (res, flag) = ret[i + j].overflowing_add(mul);
                        carry += flag as u64;
                        ret[i + j] = res;
                        let (res, flag) = ret[i + j].overflowing_add(prev_carry);
                        carry += flag as u64;
                        ret[i + j] = res;
                    }
                    if carry > 0 {
                        overflow = true
                    }
                }
                (Self(ret), overflow)
            }
        }
    };
}

macro_rules! impl_from {
    ($from:ident, $n_words_from:expr, $to:ident, $n_words_to:expr) => {
        impl From<$from> for $to {
            fn from(init: $from) -> $to {
                let mut ret = [0u64; $n_words_to];
                for i in 0..$n_words_from {
                    ret[i] = init.0[i]
                }
                $to(ret)
            }
        }
    };
}

construct_bigint!(i256, 4);
construct_bigint!(i512, 8);
construct_bigint!(i1024, 16);
construct_bigint!(u256, 4);
construct_bigint!(u512, 8);
construct_bigint!(u1024, 16);

construct_unsigned_bigint_methods!(u256, 4);
construct_unsigned_bigint_methods!(u512, 8);
construct_unsigned_bigint_methods!(u1024, 16);
construct_signed_bigint_methods!(i256, 4);
construct_signed_bigint_methods!(i512, 8);
construct_signed_bigint_methods!(i1024, 16);

impl_from!(u256, 4, u512, 8);
impl_from!(u256, 4, u1024, 16);
impl_from!(u512, 8, u1024, 16);

#[cfg(test)]
mod tests {
    #![allow(unused)]

    use super::*;

    construct_bigint!(Uint128, 2);
    construct_unsigned_bigint_methods!(Uint128, 2);

    #[test]
    fn u256_bits_test() {
        assert_eq!(u256::from(255u64).bits_required(), 8);
        assert_eq!(u256::from(256u64).bits_required(), 9);
        assert_eq!(u256::from(300u64).bits_required(), 9);
        assert_eq!(u256::from(60000u64).bits_required(), 16);
        assert_eq!(u256::from(70000u64).bits_required(), 17);

        // Try to read the following lines out loud quickly
        let mut shl = u256::from(70000u64);
        shl <<= 100;
        assert_eq!(shl.bits_required(), 117);
        shl <<= 100;
        assert_eq!(shl.bits_required(), 217);
        shl <<= 100;
        assert_eq!(shl.bits_required(), 0);

        // Bit set check
        assert!(!u256::from(10u64).bit(0));
        assert!(u256::from(10u64).bit(1));
        assert!(!u256::from(10u64).bit(2));
        assert!(u256::from(10u64).bit(3));
        assert!(!u256::from(10u64).bit(4));
    }

    #[test]
    fn u256_display_test() {
        assert_eq!(
            format!("{}", u256::from(0xDEADBEEFu64)),
            "0x00000000000000000000000000000000000000000000000000000000deadbeef"
        );
        assert_eq!(
            format!("{}", u256::from(::core::u64::MAX)),
            "0x000000000000000000000000000000000000000000000000ffffffffffffffff"
        );

        let max_val =
            u256([0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF]);
        assert_eq!(
            format!("{}", max_val),
            "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
        );
    }

    #[cfg(feature = "alloc")]
    #[test]
    fn fmt_hex() {
        let one = u256::ONE;
        let u_256 =
            u256([0x0000000000000000, 0xAAAAAAAABBBBBBBB, 0x0000000111122222, 0x0000000000000000]);

        // UpperHex
        assert_eq!(format!("{:X}", u_256), "111122222AAAAAAAABBBBBBBB0000000000000000");
        assert_eq!(format!("{:#X}", u_256), "0x111122222AAAAAAAABBBBBBBB0000000000000000");
        assert_eq!(format!("{:X}", u256::ZERO), "0");
        assert_eq!(format!("{:05X}", one), "00001");
        assert_eq!(format!("{:#05X}", one), "0x001");
        assert_eq!(format!("{:5X}", one), "1    ");
        assert_eq!(format!("{:#5X}", one), "0x1  ");
        assert_eq!(format!("{:w^#7X}", one), "ww0x1ww");

        // LowerHex
        assert_eq!(format!("{:x}", u_256), "111122222aaaaaaaabbbbbbbb0000000000000000");
        assert_eq!(format!("{:#x}", u_256), "0x111122222aaaaaaaabbbbbbbb0000000000000000");
        assert_eq!(format!("{:x}", u256::ZERO), "0");
        assert_eq!(format!("{:05x}", one), "00001");
        assert_eq!(format!("{:#05x}", one), "0x001");
        assert_eq!(format!("{:5x}", one), "1    ");
        assert_eq!(format!("{:#5x}", one), "0x1  ");
        assert_eq!(format!("{:w^#7x}", one), "ww0x1ww");
    }

    #[cfg(feature = "alloc")]
    #[test]
    fn fmt_octal() {
        let one = u256::ONE;
        let u_256 = u256([
            0o0000000000000000000000,
            0o0011222222222222222222,
            0o0000000001111111111111,
            0o0000000000000000000000,
        ]);

        assert_eq!(
            format!("{:o}", u_256),
            "111111111111100112222222222222222220000000000000000000000"
        );
        assert_eq!(
            format!("{:#o}", u_256),
            "0o111111111111100112222222222222222220000000000000000000000"
        );
        assert_eq!(format!("{:o}", u256::ZERO), "0");
        assert_eq!(format!("{:05o}", one), "00001");
        assert_eq!(format!("{:#05o}", one), "0o001");
        assert_eq!(format!("{:5o}", one), "1    ");
        assert_eq!(format!("{:#5o}", one), "0o1  ");
        assert_eq!(format!("{:w^#7o}", one), "ww0o1ww");
    }

    #[cfg(feature = "alloc")]
    #[test]
    fn fmt_binary() {
        let one = u256::ONE;
        let u_256 = u256([
            0b0000000000000000000000000000000000000000000000000000000000000000,
            0b0001111000011110001111000011110001111000011110001111000011110000,
            0b0000000000000000000000000000001111111111111111111111111111111111,
            0b0000000000000000000000000000000000000000000000000000000000000000,
        ]);

        assert_eq!(
            format!("{:b}", u_256),
            "111111111111111111111111111111111100011110000111100011110000111100011110000111100011110000111100000000000000000000000000000000000000000000000000000000000000000000"
        );
        assert_eq!(
            format!("{:#b}", u_256),
            "0b111111111111111111111111111111111100011110000111100011110000111100011110000111100011110000111100000000000000000000000000000000000000000000000000000000000000000000"
        );
        assert_eq!(format!("{:b}", u256::ZERO), "0");
        assert_eq!(format!("{:05b}", one), "00001");
        assert_eq!(format!("{:#05b}", one), "0b001");
        assert_eq!(format!("{:5b}", one), "1    ");
        assert_eq!(format!("{:#5b}", one), "0b1  ");
        assert_eq!(format!("{:w^#7b}", one), "ww0b1ww");
    }

    #[test]
    fn u256_comp_test() {
        let small = u256([10u64, 0, 0, 0]);
        let big = u256([0x8C8C3EE70C644118u64, 0x0209E7378231E632, 0, 0]);
        let bigger = u256([0x9C8C3EE70C644118u64, 0x0209E7378231E632, 0, 0]);
        let biggest = u256([0x5C8C3EE70C644118u64, 0x0209E7378231E632, 0, 1]);

        assert!(small < big);
        assert!(big < bigger);
        assert!(bigger < biggest);
        assert!(bigger <= biggest);
        assert!(biggest <= biggest);
        assert!(bigger >= big);
        assert!(bigger >= small);
        assert!(small <= small);
    }

    #[test]
    fn uint_from_be_bytes() {
        assert_eq!(
            Uint128::from_be_bytes([
                0x1b, 0xad, 0xca, 0xfe, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xaf, 0xba, 0xbe, 0x2b, 0xed,
                0xfe, 0xed
            ]),
            Uint128([0xdeafbabe2bedfeed, 0x1badcafedeadbeef])
        );

        assert_eq!(
            u256::from_be_bytes([
                0x1b, 0xad, 0xca, 0xfe, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xaf, 0xba, 0xbe, 0x2b, 0xed,
                0xfe, 0xed, 0xba, 0xad, 0xf0, 0x0d, 0xde, 0xfa, 0xce, 0xda, 0x11, 0xfe, 0xd2, 0xba,
                0xd1, 0xc0, 0xff, 0xe0
            ]),
            u256([0x11fed2bad1c0ffe0, 0xbaadf00ddefaceda, 0xdeafbabe2bedfeed, 0x1badcafedeadbeef])
        );
    }

    #[test]
    fn uint_from_le_bytes() {
        let mut be = [
            0x1b, 0xad, 0xca, 0xfe, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xaf, 0xba, 0xbe, 0x2b, 0xed,
            0xfe, 0xed,
        ];
        be.reverse();
        assert_eq!(Uint128::from_le_bytes(be), Uint128([0xdeafbabe2bedfeed, 0x1badcafedeadbeef]));

        let mut be = [
            0x1b, 0xad, 0xca, 0xfe, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xaf, 0xba, 0xbe, 0x2b, 0xed,
            0xfe, 0xed, 0xba, 0xad, 0xf0, 0x0d, 0xde, 0xfa, 0xce, 0xda, 0x11, 0xfe, 0xd2, 0xba,
            0xd1, 0xc0, 0xff, 0xe0,
        ];
        be.reverse();
        assert_eq!(
            u256::from_le_bytes(be),
            u256([0x11fed2bad1c0ffe0, 0xbaadf00ddefaceda, 0xdeafbabe2bedfeed, 0x1badcafedeadbeef])
        );
    }

    #[test]
    fn uint_to_be_bytes() {
        assert_eq!(Uint128([0xdeafbabe2bedfeed, 0x1badcafedeadbeef]).to_be_bytes(), [
            0x1b, 0xad, 0xca, 0xfe, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xaf, 0xba, 0xbe, 0x2b, 0xed,
            0xfe, 0xed
        ]);

        assert_eq!(
            u256([0x11fed2bad1c0ffe0, 0xbaadf00ddefaceda, 0xdeafbabe2bedfeed, 0x1badcafedeadbeef])
                .to_be_bytes(),
            [
                0x1b, 0xad, 0xca, 0xfe, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xaf, 0xba, 0xbe, 0x2b, 0xed,
                0xfe, 0xed, 0xba, 0xad, 0xf0, 0x0d, 0xde, 0xfa, 0xce, 0xda, 0x11, 0xfe, 0xd2, 0xba,
                0xd1, 0xc0, 0xff, 0xe0
            ]
        );
    }

    #[test]
    fn uint_to_le_bytes() {
        assert_eq!(Uint128([0xdeafbabe2bedfeed, 0x1badcafedeadbeef]).to_le_bytes(), [
            0xed, 0xfe, 0xed, 0x2b, 0xbe, 0xba, 0xaf, 0xde, 0xef, 0xbe, 0xad, 0xde, 0xfe, 0xca,
            0xad, 0x1b
        ]);

        assert_eq!(
            u256([0x11fed2bad1c0ffe0, 0xbaadf00ddefaceda, 0xdeafbabe2bedfeed, 0x1badcafedeadbeef])
                .to_le_bytes(),
            [
                0xe0, 0xff, 0xc0, 0xd1, 0xba, 0xd2, 0xfe, 0x11, 0xda, 0xce, 0xfa, 0xde, 0x0d, 0xf0,
                0xad, 0xba, 0xed, 0xfe, 0xed, 0x2b, 0xbe, 0xba, 0xaf, 0xde, 0xef, 0xbe, 0xad, 0xde,
                0xfe, 0xca, 0xad, 0x1b,
            ]
        );
    }

    #[test]
    fn u256_div_rem_0() {
        let zero = u256::ZERO;
        let number_one = u256::from(0xDEADBEEFu64);
        let number_two = u256::from(::core::u64::MAX);
        let one_div_rem_two = (
            u256::from(::core::u64::MAX / 0xDEADBEEFu64),
            u256::from(::core::u64::MAX % 0xDEADBEEFu64),
        );
        let max = u256::MAX;

        // Division by zero gets not panic and gets None
        assert_eq!(u256::div_rem(max, zero), Err(DivError::ZeroDiv));
        assert_eq!(u256::div_rem(number_two, zero), Err(DivError::ZeroDiv));
        assert_eq!(u256::div_rem(number_one, zero), Err(DivError::ZeroDiv));

        // Division of zero gets Zero
        assert_eq!(u256::div_rem(zero, max), Ok((zero, zero)));
        assert_eq!(u256::div_rem(zero, number_two), Ok((zero, zero)));
        assert_eq!(u256::div_rem(zero, number_one), Ok((zero, zero)));

        // Division by another than zero not gets None
        assert!(u256::div_rem(max, number_one).is_ok());
        assert!(u256::div_rem(number_two, number_one).is_ok());

        // In u256 division gets the same as in u64
        assert_eq!(u256::div_rem(number_two, number_one), Ok(one_div_rem_two));
    }

    #[test]
    fn u256_div_rem_1() {
        let zero = u256::ZERO;
        let number_one = u256::from(0xDEADBEEFu64);
        let number_two = u256::from(::core::u64::MAX);
        let max = u256::MAX;

        assert!(u256::div_rem(max, zero).is_err());
        assert!(u256::div_rem(number_one, zero).is_err());
        assert!(u256::div_rem(number_two, zero).is_err());

        assert_eq!(u256::MAX / u256::ONE, u256::MAX);
        assert_eq!(u256::from(12u8) / u256::from(4u8), u256::from(3u8));
        assert!(std::panic::catch_unwind(|| number_one / zero).is_err());
        assert!(std::panic::catch_unwind(|| i256::MIN / (-i256::ONE)).is_err());
    }

    #[test]
    fn bigint_min_max() {
        assert_eq!(u256::MIN.as_inner(), &[0u64; 4]);
        assert_eq!(u512::MIN.as_inner(), &[0u64; 8]);
        assert_eq!(u1024::MIN.as_inner(), &[0u64; 16]);
        assert_eq!(u256::MAX.as_inner(), &[::core::u64::MAX; 4]);
        assert_eq!(u512::MAX.as_inner(), &[::core::u64::MAX; 8]);
        assert_eq!(u1024::MAX.as_inner(), &[::core::u64::MAX; 16]);
        assert_eq!(u256::BITS, 4 * 64);
        assert_eq!(u512::BITS, 8 * 64);
        assert_eq!(u1024::BITS, 16 * 64);
    }

    #[test]
    fn u256_arithmetic_test() {
        let init = u256::from(0xDEADBEEFDEADBEEFu64);
        let copy = init;

        let add = init + copy;
        assert_eq!(add, u256([0xBD5B7DDFBD5B7DDEu64, 1, 0, 0]));
        // Bitshifts
        let shl = add << 88;
        assert_eq!(shl, u256([0u64, 0xDFBD5B7DDE000000, 0x1BD5B7D, 0]));
        let shr = shl >> 40;
        assert_eq!(shr, u256([0x7DDE000000000000u64, 0x0001BD5B7DDFBD5B, 0, 0]));
        // Increment
        let mut incr = shr;
        incr += 1u32;
        assert_eq!(incr, u256([0x7DDE000000000001u64, 0x0001BD5B7DDFBD5B, 0, 0]));
        // Subtraction
        let sub = incr - init;
        assert_eq!(sub, u256([0x9F30411021524112u64, 0x0001BD5B7DDFBD5A, 0, 0]));
        // Multiplication
        let mult = sub * 300u32;
        assert_eq!(mult, u256([0x8C8C3EE70C644118u64, 0x0209E7378231E632, 0, 0]));
        // Division
        assert_eq!(u256::from(105u64) / u256::from(5u64), u256::from(21u64));
        let div = mult / u256::from(300u64);
        assert_eq!(div, u256([0x9F30411021524112u64, 0x0001BD5B7DDFBD5A, 0, 0]));

        assert_eq!(u256::from(105u64) % u256::from(5u64), u256::from(0u64));
        assert_eq!(u256::from(35498456u64) % u256::from(3435u64), u256::from(1166u64));
        let rem_src = mult * u256::from(39842u64) + u256::from(9054u64);
        assert_eq!(rem_src % u256::from(39842u64), u256::from(9054u64));
        // TODO: bit inversion
    }

    #[test]
    fn mul_u32_test() {
        let u64_val = u256::from(0xDEADBEEFDEADBEEFu64);

        let u96_res = u64_val * 0xFFFFFFFFu32;
        let u128_res = u96_res * 0xFFFFFFFFu32;
        let u160_res = u128_res * 0xFFFFFFFFu32;
        let u192_res = u160_res * 0xFFFFFFFFu32;
        let u224_res = u192_res * 0xFFFFFFFFu32;
        let u256_res = u224_res * 0xFFFFFFFFu32;

        assert_eq!(u96_res, u256([0xffffffff21524111u64, 0xDEADBEEE, 0, 0]));
        assert_eq!(u128_res, u256([0x21524111DEADBEEFu64, 0xDEADBEEE21524110, 0, 0]));
        assert_eq!(u160_res, u256([0xBD5B7DDD21524111u64, 0x42A4822200000001, 0xDEADBEED, 0]));
        assert_eq!(
            u192_res,
            u256([0x63F6C333DEADBEEFu64, 0xBD5B7DDFBD5B7DDB, 0xDEADBEEC63F6C334, 0])
        );
        assert_eq!(
            u224_res,
            u256([0x7AB6FBBB21524111u64, 0xFFFFFFFBA69B4558, 0x854904485964BAAA, 0xDEADBEEB])
        );
        assert_eq!(
            u256_res,
            u256([
                0xA69B4555DEADBEEFu64,
                0xA69B455CD41BB662,
                0xD41BB662A69B4550,
                0xDEADBEEAA69B455C
            ])
        );
    }

    #[test]
    fn multiplication_test() {
        let u64_val = u256::from(0xDEADBEEFDEADBEEFu64);

        let u128_res = u64_val * u64_val;

        assert_eq!(u128_res, u256([0x048D1354216DA321u64, 0xC1B1CD13A4D13D46, 0, 0]));

        let u256_res = u128_res * u128_res;

        assert_eq!(
            u256_res,
            u256([
                0xF4E166AAD40D0A41u64,
                0xF5CF7F3618C2C886u64,
                0x4AFCFF6F0375C608u64,
                0x928D92B4D7F5DF33u64
            ])
        );
    }

    #[test]
    fn u256_extreme_bitshift_test() {
        // Shifting a u64 by 64 bits gives an undefined value, so make sure that
        // we're doing the Right Thing here
        let init = u256::from(0xDEADBEEFDEADBEEFu64);

        assert_eq!(init << 64, u256([0, 0xDEADBEEFDEADBEEF, 0, 0]));
        let add = (init << 64) + init;
        assert_eq!(add, u256([0xDEADBEEFDEADBEEF, 0xDEADBEEFDEADBEEF, 0, 0]));
        assert_eq!(add >> 0, u256([0xDEADBEEFDEADBEEF, 0xDEADBEEFDEADBEEF, 0, 0]));
        assert_eq!(add << 0, u256([0xDEADBEEFDEADBEEF, 0xDEADBEEFDEADBEEF, 0, 0]));
        assert_eq!(add >> 64, u256([0xDEADBEEFDEADBEEF, 0, 0, 0]));
        assert_eq!(add << 64, u256([0, 0xDEADBEEFDEADBEEF, 0xDEADBEEFDEADBEEF, 0]));
    }

    #[cfg(feature = "serde")]
    #[test]
    fn u256_serde_test() {
        let check = |uint, hex| {
            let json = format!("\"{}\"", hex);
            assert_eq!(::serde_json::to_string(&uint).unwrap(), json);
            assert_eq!(::serde_json::from_str::<u256>(&json).unwrap(), uint);
        };

        check(u256::from(0u64), "0000000000000000000000000000000000000000000000000000000000000000");
        check(
            u256::from(0xDEADBEEFu64),
            "00000000000000000000000000000000000000000000000000000000deadbeef",
        );
        check(
            u256([0xaa11, 0xbb22, 0xcc33, 0xdd44]),
            "000000000000dd44000000000000cc33000000000000bb22000000000000aa11",
        );
        check(
            u256([u64::max_value(), u64::max_value(), u64::max_value(), u64::max_value()]),
            "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
        );
        check(
            u256([0xA69B4555DEADBEEF, 0xA69B455CD41BB662, 0xD41BB662A69B4550, 0xDEADBEEAA69B455C]),
            "deadbeeaa69b455cd41bb662a69b4550a69b455cd41bb662a69b4555deadbeef",
        );

        assert!(
            ::serde_json::from_str::<u256>(
                "\"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffg\""
            )
            .is_err()
        ); // invalid char
        assert!(
            ::serde_json::from_str::<u256>(
                "\"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\""
            )
            .is_err()
        ); // invalid length
        assert!(
            ::serde_json::from_str::<u256>(
                "\"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\""
            )
            .is_err()
        ); // invalid length
    }

    #[test]
    fn i256_test() {
        let x = i256::from(1);
        let y = i256::from(1);
        assert_eq!(x.checked_add(y), Some(i256::from(2)));
    }

    #[test]
    fn i256_is_positive_test() {
        assert!(i256::from(1).is_positive());
        assert!(!i256::from(-1).is_positive());
        assert!(!i256::from(0).is_positive());
        assert!(i256::MAX.is_positive());
        assert!(!i256::MIN.is_positive());
        assert!(i256::MIN.is_negative());
    }

    #[test]
    fn u256_add_test() {
        assert_eq!((u256::MAX - u256::ONE, true), u256::MAX.overflowing_add(u256::MAX));
    }

    #[test]
    fn i256_add_test() {
        assert_eq!((i256::from(3), false), i256::from(1).overflowing_add(i256::from(2)));
        assert_eq!((i256::from(1), false), i256::from(-1).overflowing_add(i256::from(2)));
        assert_eq!((i256::from(-2), false), i256::from(-1).overflowing_add(i256::from(-1)));
        assert_eq!((i256::from(0), false), i256::from(0).overflowing_add(i256::from(0)));
        assert_eq!((i256::MIN, true), i256::from(1).overflowing_add(i256::MAX));
    }

    #[test]
    fn i256_sub_test() {
        assert_eq!((i256::from(-1), false), i256::from(1).overflowing_sub(i256::from(2)));
        assert_eq!((i256::from(1), false), i256::from(3).overflowing_sub(i256::from(2)));
        assert_eq!((i256::from(-3), false), i256::from(-4).overflowing_sub(i256::from(-1)));
        assert_eq!((i256::from(0), false), i256::from(0).overflowing_add(i256::from(0)));
        assert_eq!((i256::MIN, false), i256::from(0).overflowing_sub(i256::MIN));
        assert_eq!((i256::ZERO, false), i256::MIN.overflowing_sub(i256::MIN));
        assert_eq!((-i256::ONE, false), i256::MAX.overflowing_sub(i256::MIN));
        assert_eq!((i256::MAX, true), (-i256::from(2)).overflowing_sub(i256::MAX));
    }

    #[test]
    fn i256_neg_test() {
        assert_eq!(i256::from(1), -i256::from(-1));
        assert_eq!(i256::from(-1), -i256::from(1));
        assert_eq!(i256::from(0), -i256::from(0));
        assert_eq!(i256::MIN + 1, -i256::MAX);
    }

    #[test]
    #[should_panic]
    fn i256_neg_min_test() {
        assert_eq!(-i256::MIN, -i256::MIN);
    }

    #[test]
    fn i256_mul_test() {
        assert_eq!((i256::from(-12), false), i256::from(3).overflowing_mul(i256::from(-4)));
        assert_eq!((i256::from(6), false), i256::from(2).overflowing_mul(i256::from(3)));
        assert_eq!((i256::from(30), false), i256::from(-6).overflowing_mul(i256::from(-5)));
        assert_eq!((i256::from(-2), true), i256::MAX.overflowing_mul(i256::from(2)));
        assert_eq!((i256::ZERO, true), i256::MIN.overflowing_mul(i256::from(2)));
        assert_eq!((i256::ONE, true), i256::MAX.overflowing_mul(i256::MAX));
    }

    #[test]
    fn i256_arithmetic_shr_test() {
        assert_eq!(i256::from(-1), i256::from(-1) >> 1);
        assert_eq!(i256::from(-1), i256::from(-2) >> 1);
        assert_eq!(i256::from(1), i256::from(2) >> 1);
        assert_eq!(i256::from(1), i256::from(2) >> 1);
        assert_eq!(i256::from(0), i256::from(1) >> 1);
    }

    #[test]
    fn i256_bits_required_test() {
        assert_eq!(i256::from(255).bits_required(), 9);
        assert_eq!(i256::from(256).bits_required(), 10);
        assert_eq!(i256::from(300).bits_required(), 10);
        assert_eq!(i256::from(60000).bits_required(), 17);
        assert_eq!(i256::from(70000).bits_required(), 18);
        assert_eq!(i256::from(-128).bits_required(), 8);
        assert_eq!(i256::from(-129).bits_required(), 9);
        assert_eq!(i256::from(0).bits_required(), 1);
        assert_eq!(i256::from(-1).bits_required(), 1);
        assert_eq!(i256::from(-2).bits_required(), 2);
        assert_eq!(i256::MIN.bits_required(), 256);
        assert_eq!(i256::MAX.bits_required(), 256);
    }

    #[test]
    fn i256_div_test() {
        assert_eq!(Ok((i256::from(3), i256::from(1))), i256::from(7).div_rem(i256::from(2i32)));
        assert_eq!(Ok((i256::from(-3), i256::from(1))), i256::from(7).div_rem(i256::from(-2i128)));
        assert_eq!(Ok((i256::from(-3), i256::from(-1))), i256::from(-7).div_rem(i256::from(2)));
        assert_eq!(Ok((i256::from(3), i256::from(-1))), i256::from(-7).div_rem(i256::from(-2)));
        assert!(i256::div_rem(i256::MAX, i256::ZERO).is_err());
    }

    #[test]
    fn overflowing_div_est() {
        assert_eq!((i256::from(3), false), i256::from(7).overflowing_div(i256::from(2i32)));
        assert_eq!((i256::MIN, true), i256::MIN.overflowing_div(i256::from(-1)));
        let res = std::panic::catch_unwind(|| i256::overflowing_div(i256::MAX, i256::ZERO));
        assert!(res.is_err());
    }

    #[test]
    fn wrapping_div_est() {
        assert_eq!(i1024::from(3), i1024::from(7).wrapping_div(2));
        assert_eq!(i512::MIN, i512::MIN.wrapping_div(-1));
        let res = std::panic::catch_unwind(|| i256::wrapping_div(i256::MAX, i256::ZERO));
        assert!(res.is_err());
    }

    #[test]
    fn checked_div_est() {
        assert_eq!(Some(i1024::from(3)), i1024::from(7).checked_div(2));
        assert_eq!(Some(i512::MAX), i512::MAX.checked_div(1));
        assert_eq!(Some(i512::MIN + 1), i512::MAX.checked_div(-1));
        assert_eq!(None, i512::MIN.checked_div(-1));
        assert_eq!(None, i512::MAX.checked_div(0));
    }

    #[test]
    fn saturating_div_test() {
        assert_eq!(i256::from(5).saturating_div(2), i256::from(2));
        assert_eq!(i256::MAX.saturating_div(-i256::ONE), i256::MIN + 1);
        assert_eq!(i256::MIN.saturating_div(-1), i256::MAX);
    }

    #[test]
    fn overflowing_rem_est() {
        assert_eq!((i256::from(1), false), i256::from(7).overflowing_rem(i256::from(2i32)));
        assert_eq!((i256::ZERO, true), i256::MIN.overflowing_rem(i256::from(-1)));
        let res = std::panic::catch_unwind(|| i256::overflowing_rem(i256::MAX, i256::ZERO));
        assert!(res.is_err());
    }

    #[test]
    fn wrapping_rem_test() {
        assert_eq!(i1024::from(1), i1024::from(7).wrapping_rem(2));
        assert_eq!(i512::ZERO, i512::MIN.wrapping_rem(-1));
        let res = std::panic::catch_unwind(|| i256::wrapping_rem(i256::MAX, i256::ZERO));
        assert!(res.is_err());
    }

    #[test]
    fn checked_rem_test() {
        assert_eq!(Some(i1024::from(1)), i1024::from(7).checked_rem(2));
        assert_eq!(None, i512::MIN.checked_rem(-1));
        assert_eq!(None, i512::MAX.checked_rem(0));
    }

    #[test]
    fn div_euclid_test() {
        assert_eq!(i1024::from(1), i1024::from(7).div_euclid(4));
        assert_eq!(i1024::from(-1), i1024::from(7).div_euclid(-4));
        assert_eq!(i1024::from(-2), i1024::from(-7).div_euclid(4));
        assert_eq!(i1024::from(2), i1024::from(-7).div_euclid(-4));
    }

    #[test]
    fn overflowing_div_euclid_test() {
        assert_eq!((u512::from(2u8), false), u512::from(5u8).overflowing_div_euclid(2u8));
        assert_eq!((i1024::MIN, true), i1024::MIN.overflowing_div_euclid(-1));
    }

    #[test]
    fn wrapping_div_euclid_test() {
        assert_eq!(u256::from(10u8), u256::from(100u8).wrapping_div_euclid(10u8));
        assert_eq!(i1024::MIN, i1024::MIN.wrapping_div_euclid(-1));
    }

    #[test]
    fn checked_div_euclid_test() {
        assert_eq!(None, u256::from(100u8).checked_div_euclid(0u8));
        assert_eq!(None, i1024::MIN.checked_div_euclid(-1));
        assert_eq!(Some(i1024::from(-3)), i1024::from(6).checked_div_euclid(-2));
    }

    #[test]
    fn rem_euclid_test() {
        assert_eq!(i1024::from(3), i1024::from(7).rem_euclid(4));
        assert_eq!(i1024::from(1), i1024::from(-7).rem_euclid(4));
        assert_eq!(i1024::from(3), i1024::from(7).rem_euclid(-4));
        assert_eq!(i1024::from(1), i1024::from(-7).rem_euclid(-4));
    }

    #[test]
    fn overflowing_rem_euclid_test() {
        assert_eq!((u512::from(1u8), false), u512::from(5u8).overflowing_rem_euclid(2u8));
        assert_eq!((i1024::ZERO, true), i1024::MIN.overflowing_rem_euclid(-1));
    }

    #[test]
    fn wrapping_rem_euclid_test() {
        assert_eq!(u256::ZERO, u256::from(100u8).wrapping_rem_euclid(10u8));
        assert_eq!(i1024::ZERO, i1024::MIN.wrapping_rem_euclid(-1));
    }

    #[test]
    fn checked_rem_euclid_test() {
        assert_eq!(None, u256::from(100u8).checked_rem_euclid(0u8));
        assert_eq!(None, i1024::MIN.checked_rem_euclid(-1));
        assert_eq!(Some(i1024::from(1)), i1024::from(5).checked_rem_euclid(2));
    }

    #[test]
    fn i256_cmp_test() {
        assert!(i256::ZERO < i256::ONE);
        assert!(-i256::ONE < i256::ZERO);
        assert!(i256::MIN < i256::MAX);
        assert!(i256::MIN < i256::ZERO);
        assert!(i256::from(200) < i256::from(10000000));
        assert!(i256::from(-3) < i256::from(87));
    }

    #[test]
    fn u256_to_u512_test() {
        assert_eq!(u512::from(u256::from(30u8)), u512::from(30u8));
    }

    #[test]
    fn leading_zeros_test() {
        assert_eq!(u512::ZERO.leading_zeros(), 512);
        assert_eq!(u512::ZERO.leading_ones(), 0);
        assert_eq!(u512::ZERO.trailing_zeros(), 512);
        assert_eq!(u512::ZERO.trailing_ones(), 0);
        assert_eq!(u512::MAX.leading_zeros(), 0);
        assert_eq!(u512::MAX.leading_ones(), 512);
        assert_eq!(u512::MAX.trailing_zeros(), 0);
        assert_eq!(u512::MAX.trailing_ones(), 512);
        assert_eq!(u256::from(32u8).leading_zeros(), 256 - 6);
        assert_eq!(u256::from(32u8).leading_ones(), 0);
        assert_eq!(u256::from(32u8).trailing_zeros(), 5);
        assert_eq!(u256::from(32u8).trailing_ones(), 0);
        assert_eq!(i256::from(-2).leading_zeros(), 0);
        assert_eq!(i256::from(-2).leading_ones(), 255);
        assert_eq!(i256::from(-2).trailing_zeros(), 1);
        assert_eq!(i256::from(-2).trailing_ones(), 0);
    }

    #[test]
    fn checked_shl_test() {
        assert_eq!(i256::from(4).checked_shl(0), Some(i256::from(4)));
        assert_eq!(i256::from(4).checked_shl(1), Some(i256::from(8)));
        assert_eq!(i256::from(1).checked_shl(255), Some(i256::MIN));
        assert_eq!(i256::from(4).checked_shl(255), Some(i256::from(0)));
        assert_eq!(i256::from(4).checked_shl(256), None);
        assert_eq!(u256::from(4u8).checked_shl(0), Some(u256::from(4u8)));
        assert_eq!(u256::from(4u8).checked_shl(1), Some(u256::from(8u8)));
        assert_eq!(u256::from(4u8).checked_shl(255), Some(u256::from(0u8)));
        assert_eq!(u256::from(4u8).checked_shl(256), None);
    }

    #[test]
    fn checked_shr_test() {
        assert_eq!(i256::from(4).checked_shr(0), Some(i256::from(4)));
        assert_eq!(i256::from(4).checked_shr(1), Some(i256::from(2)));
        assert_eq!(i256::from(4).checked_shr(255), Some(i256::from(0)));
        assert_eq!(i256::from(4).checked_shr(256), None);
        assert_eq!(u256::from(4u8).checked_shr(0), Some(u256::from(4u8)));
        assert_eq!(u256::from(4u8).checked_shr(1), Some(u256::from(2u8)));
        assert_eq!(u256::from(4u8).checked_shr(255), Some(u256::from(0u8)));
        assert_eq!(u256::from(4u8).checked_shr(256), None);
    }

    #[test]
    fn wrapping_neg_test() {
        assert_eq!(i256::from(2).wrapping_neg(), i256::from(-2));
        assert_eq!(i256::MIN.wrapping_neg(), i256::MIN);
        assert_eq!(i256::from(0).wrapping_neg(), i256::from(0));
        assert_eq!(u256::from(1u8).wrapping_neg(), u256::MAX);
    }
}