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
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
#![allow(dead_code)]
pub mod hq;
pub mod hash_to_binary_tree;
mod test;
mod benchmark;
use super::command::{Command, ComputeDistanceCode, InitCommand, BrotliDistanceParams};
use super::hash_to_binary_tree::{H10, H10Buckets, H10DefaultParams, ZopfliNode};
use super::dictionary_hash::kStaticDictionaryHash;
use super::static_dict::{BROTLI_UNALIGNED_LOAD32, BROTLI_UNALIGNED_LOAD64, FindMatchLengthWithLimit, FindMatchLengthWithLimitMin4};
use super::static_dict::BrotliDictionary;
use super::super::alloc;
use super::super::alloc::{SliceWrapper, SliceWrapperMut, Allocator};
use super::util::{Log2FloorNonZero, brotli_max_size_t, floatX};
use core;
static kBrotliMinWindowBits: i32 = 10i32;

static kBrotliMaxWindowBits: i32 = 24i32;

pub static kInvalidMatch: u32 = 0xfffffffu32;

static kCutoffTransformsCount: u32 = 10u32;

static kCutoffTransforms: u64 = 0x71b520au64 << 32i32 | 0xda2d3200u32 as (u64);

pub static kHashMul32: u32 = 0x1e35a7bdu32;

pub static kHashMul64: u64 = 0x1e35a7bdu64 << 32i32 | 0x1e35a7bdu64;

pub static kHashMul64Long: u64 = 0x1fe35a7bu32 as (u64) << 32i32 | 0xd3579bd3u32 as (u64);


#[derive(PartialEq, Eq, Copy, Clone, Debug)]
#[repr(C)]
pub enum BrotliEncoderMode {
  BROTLI_MODE_GENERIC = 0,
  BROTLI_MODE_TEXT = 1,
  BROTLI_MODE_FONT = 2,
  BROTLI_FORCE_LSB_PRIOR = 3,
  BROTLI_FORCE_MSB_PRIOR = 4,
  BROTLI_FORCE_UTF8_PRIOR = 5,
  BROTLI_FORCE_SIGNED_PRIOR = 6,
}

#[derive(Clone,Copy, Debug, PartialEq)]
pub struct BrotliHasherParams {
  // type of hasher to use (default: type 6, but others have tradeoffs of speed/memory)
  pub type_: i32,
  // number of the number of buckets to have in the hash table (defaults to quality - 1)
  pub bucket_bits: i32,
  // number of potential matches to hold per bucket (hash collisions)
  pub block_bits: i32,
  // number of bytes of a potential match to hash
  pub hash_len: i32,
  // number of previous distance matches to check for future matches (defaults to 16)
  pub num_last_distances_to_check: i32,
  // how much to weigh distance vs an extra byte of copy match when comparing possible copy srcs
  pub literal_byte_score: i32,
}


#[derive(Clone, Debug)]
pub struct BrotliEncoderParams {
  pub dist: BrotliDistanceParams,
  // if this brotli file is generic, font or specifically text
  pub mode: BrotliEncoderMode,
  // quality param between 0 and 11 (11 is smallest but takes longest to encode)
  pub quality: i32,
  pub q9_5: bool,
  // log of how big the ring buffer should be for copying prior data
  pub lgwin: i32,
  // log of how often metablocks should be serialized
  pub lgblock: i32,
  // how big the source file is (or 0 if no hint is provided)
  pub size_hint: usize,
  // avoid serializing out priors for literal sections in the favor of decode speed
  pub disable_literal_context_modeling: i32,
  pub hasher: BrotliHasherParams,
  // produce an IR of the compression file
  pub log_meta_block: bool,
  // attempt to detect how many bytes before the current byte generates the best prediction of it
  pub stride_detection_quality: u8, // 0 = off (stride 1 always) 1 = on per 16th of a file 2 = on per block type switch
  // if nonzero, will search for high entropy strings and log them differently to the IR
  pub high_entropy_detection_quality: u8, // search for high entropy literal strings and annotate them differently
  // if nonzero it will search for the temporal locality and effectiveness of the priors
  // for literals. The best adaptation and forgetfulness will be logged per metablock to the IR
  pub cdf_adaptation_detection: u8,
  // whether to search for whether the previous byte or the context_map are better predictors on a per-context-map basis
  pub prior_bitmask_detection: u8,
  // for prior bitmask detection: stride_low, stride_speed, cm_low, cm_speed
  pub literal_adaptation:[(u16, u16); 4],
  pub large_window: bool,
  // avoid search for the best ndirect vs npostfix parameters for distance
  pub avoid_distance_prefix_search: bool,
  // construct brotli in such a way that it may be concatenated with another brotli file using appropriate bit ops
  pub catable: bool,
  // can use the dictionary (default yes unless catable is set)
  pub use_dictionary: bool,
  // construct brotli in such a way that another concatable brotli file may be appended
  pub appendable: bool,
  // include a magic number and version number and size_hint at the beginning
  pub magic_number: bool,
  // prefer to compute the map of previously seen strings
  // just once for all the threads at the beginning, since they overlap significantly
  pub favor_cpu_efficiency: bool,
}

impl Default for BrotliEncoderParams {
   fn default() -> BrotliEncoderParams {
      super::encode::BrotliEncoderInitParams()
   }
}

#[derive(Clone,Copy,Default,PartialEq)]
pub struct H9Opts{
   pub literal_byte_score: u32,
}
pub enum HowPrepared {
  ALREADY_PREPARED,
  NEWLY_PREPARED,
}
#[derive(Clone, PartialEq)]
pub struct Struct1 {
  pub params: BrotliHasherParams,
  pub is_prepared_: i32,
  pub dict_num_lookups: usize,
  pub dict_num_matches: usize,
}

fn LiteralSpreeLengthForSparseSearch(params: &BrotliEncoderParams) -> usize {
  (if (*params).quality < 9 {
     64i32
   } else {
     512i32
   }) as (usize)
}

fn brotli_min_size_t(a: usize, b: usize) -> usize {
  if a < b { a } else { b }
}


pub struct HasherSearchResult {
  pub len: usize,
  pub len_x_code: usize,
  pub distance: usize,
  pub score: u64,
}

pub trait CloneWithAlloc<Alloc: alloc::Allocator<u16> + alloc::Allocator<u32>> {
    fn clone_with_alloc(&self, m: &mut Alloc) -> Self;
}

pub trait AnyHasher {
  fn Opts(&self) -> H9Opts;
  fn GetHasherCommon(&mut self) -> &mut Struct1;
  fn HashBytes(&self, data: &[u8]) -> usize;
  fn HashTypeLength(&self) -> usize;
  fn StoreLookahead(&self) -> usize;
  fn PrepareDistanceCache(&self, distance_cache: &mut [i32]);
  fn FindLongestMatch(&mut self,
                      dictionary: Option<&BrotliDictionary>,
                      dictionary_hash: &[u16],
                      data: &[u8],
                      ring_buffer_mask: usize,
                      distance_cache: &[i32],
                      cur_ix: usize,
                      max_length: usize,
                      max_backward: usize,
                      gap: usize,
                      max_distance: usize,
                      out: &mut HasherSearchResult)
                      -> bool;
  fn Store(&mut self, data: &[u8], mask: usize, ix: usize);
  fn Store4Vec4(&mut self, data: &[u8], mask: usize, ix: usize) {
    for i in 0..4 {
      self.Store(data, mask, ix + i * 4);
    }
  }
  fn StoreEvenVec4(&mut self, data: &[u8], mask: usize, ix: usize) {
    for i in 0..4 {
      self.Store(data, mask, ix + i * 2);
    }
  }
  fn StoreRange(&mut self, data: &[u8], mask: usize, ix_start: usize, ix_end: usize);
  fn BulkStoreRange(&mut self, data: &[u8], mask: usize, ix_start: usize, ix_end: usize);
  fn Prepare(&mut self, one_shot: bool, input_size: usize, data: &[u8]) -> HowPrepared;
  fn StitchToPreviousBlock(&mut self,
                           num_bytes: usize,
                           position: usize,
                           ringbuffer: &[u8],
                           ringbuffer_mask: usize);
}


pub fn StitchToPreviousBlockInternal<T: AnyHasher>(handle: &mut T,
                                                   num_bytes: usize,
                                                   position: usize,
                                                   ringbuffer: &[u8],
                                                   ringbuffer_mask: usize) {
  if num_bytes >= handle.HashTypeLength().wrapping_sub(1) && (position >= 3) {
    handle.Store(ringbuffer, ringbuffer_mask, position.wrapping_sub(3));
    handle.Store(ringbuffer, ringbuffer_mask, position.wrapping_sub(2));
    handle.Store(ringbuffer, ringbuffer_mask, position.wrapping_sub(1));
  }
}

pub fn StoreLookaheadThenStore<T: AnyHasher>(hasher: &mut T, size: usize, dict: &[u8]) {
  let overlap = hasher.StoreLookahead().wrapping_sub(1usize);
  if size > overlap {
    hasher.BulkStoreRange(dict, !(0usize), 0, size - overlap);
  }
}

pub trait BasicHashComputer {
  fn HashBytes(&self, data: &[u8]) -> u32;
  fn BUCKET_BITS(&self) -> i32;
  fn USE_DICTIONARY(&self) -> i32;
  fn BUCKET_SWEEP(&self) -> i32;
}
pub struct BasicHasher<Buckets: SliceWrapperMut<u32> + SliceWrapper<u32> + BasicHashComputer> {
  pub GetHasherCommon: Struct1,
  pub buckets_: Buckets,
  pub h9_opts: H9Opts,
}

impl<A: SliceWrapperMut<u32> + SliceWrapper<u32> + BasicHashComputer> PartialEq<BasicHasher<A>> for BasicHasher<A> {
    fn eq(&self, other: &BasicHasher<A>) -> bool {
        self.GetHasherCommon == other.GetHasherCommon && self.h9_opts == other.h9_opts && self.buckets_.slice() == other.buckets_.slice()
    }
}

impl<T: SliceWrapperMut<u32> + SliceWrapper<u32> + BasicHashComputer> BasicHasher<T> {
    fn StoreRangeOptBasic(&mut self, data: &[u8], mask: usize, ix_start: usize, ix_end: usize) -> usize {
      let lookahead = 8;
      if ix_end >= ix_start + lookahead * 2{
        let chunk_count = (ix_end - ix_start) / 4;
        for chunk_id in 0..chunk_count {
          let i = (ix_start + chunk_id * 4) & mask;
          let word11 = data.split_at(i).1.split_at(11).0;
          let mixed0 = self.HashBytes(word11);
          let mixed1 = self.HashBytes(word11.split_at(1).1);
          let mixed2 = self.HashBytes(word11.split_at(2).1);
          let mixed3 = self.HashBytes(word11.split_at(3).1);
          let off: u32 = (i >> 3i32).wrapping_rem(self.buckets_.BUCKET_SWEEP() as usize) as (u32);
          let offset0: usize = mixed0 + off as usize;
          let offset1: usize = mixed1 + off as usize;
          let offset2: usize = mixed2 + off as usize;
          let offset3: usize = mixed3 + off as usize;
          self.buckets_.slice_mut()[offset0] = i as u32;
          self.buckets_.slice_mut()[offset1] = i as u32 + 1;
          self.buckets_.slice_mut()[offset2] = i as u32 + 2;
          self.buckets_.slice_mut()[offset3] = i as u32 + 3;
      }
      return ix_start + chunk_count * 4;
    }
    ix_start
  }

}
pub struct H2Sub<AllocU32: alloc::Allocator<u32>> {
  pub buckets_: AllocU32::AllocatedMemory, // 65537
}
impl<T: SliceWrapperMut<u32> + SliceWrapper<u32> + BasicHashComputer> AnyHasher for BasicHasher<T> {
  #[inline(always)]
  fn Opts(&self) -> H9Opts {
     self.h9_opts
  }
  #[allow(unused_variables)]
  fn PrepareDistanceCache(&self, distance_cache: &mut [i32]) {}
  #[inline(always)]
  fn HashTypeLength(&self) -> usize {
    8
  }
  #[inline(always)]
  fn StoreLookahead(&self) -> usize {
    8
  }
  fn StitchToPreviousBlock(&mut self,
                           num_bytes: usize,
                           position: usize,
                           ringbuffer: &[u8],
                           ringbuffer_mask: usize) {
    StitchToPreviousBlockInternal(self, num_bytes, position, ringbuffer, ringbuffer_mask);
  }
  #[inline(always)]
  fn GetHasherCommon(&mut self) -> &mut Struct1 {
    return &mut self.GetHasherCommon;
  }
  #[inline(always)]
  fn HashBytes(&self, data: &[u8]) -> usize {
    self.buckets_.HashBytes(data) as usize
  }
  fn Store(&mut self, data: &[u8], mask: usize, ix: usize) {
    let (_, data_window) = data.split_at((ix & mask) as (usize));
    let key: u32 = self.HashBytes(data_window) as u32;
    let off: u32 = (ix >> 3i32).wrapping_rem(self.buckets_.BUCKET_SWEEP() as usize) as (u32);
    self.buckets_.slice_mut()[key.wrapping_add(off) as (usize)] = ix as (u32);
  }
  fn StoreRange(&mut self, data: &[u8], mask: usize, ix_start: usize, ix_end: usize) {
    for i in self.StoreRangeOptBasic(data, mask, ix_start, ix_end)..ix_end {
      self.Store(data, mask, i);
    }
  }
  fn BulkStoreRange(&mut self, data: &[u8], mask: usize, ix_start: usize, ix_end: usize) {
    self.StoreRange(data, mask, ix_start, ix_end);
  }
  fn Prepare(&mut self, one_shot: bool, input_size: usize, data: &[u8]) -> HowPrepared {
    if self.GetHasherCommon.is_prepared_ != 0 {
      return HowPrepared::ALREADY_PREPARED;
    }
    let partial_prepare_threshold = (4 << self.buckets_.BUCKET_BITS()) >> 7;
    if one_shot && input_size <= partial_prepare_threshold {
      for i in 0..input_size {
        let key = self.HashBytes(&data[i..]) as usize;
        let bs = self.buckets_.BUCKET_SWEEP() as usize;
        for item in self.buckets_.slice_mut()[key..(key + bs)].iter_mut() {
          *item = 0;
        }
      }
    } else {
      for item in self.buckets_.slice_mut().iter_mut() {
        *item = 0;
      }
    }
    self.GetHasherCommon.is_prepared_ = 1;
    HowPrepared::NEWLY_PREPARED
  }

  fn FindLongestMatch(&mut self,
                      dictionary: Option<&BrotliDictionary>,
                      dictionary_hash: &[u16],
                      data: &[u8],
                      ring_buffer_mask: usize,
                      distance_cache: &[i32],
                      cur_ix: usize,
                      max_length: usize,
                      max_backward: usize,
                      gap: usize,
                      max_distance: usize,
                      out: &mut HasherSearchResult)
                      -> bool {
    let opts = self.Opts();
    let best_len_in: usize = (*out).len;
    let cur_ix_masked: usize = cur_ix & ring_buffer_mask;
    let key: u32 = self.HashBytes(&data[(cur_ix_masked as (usize))..]) as u32;
    let mut compare_char: i32 = data[(cur_ix_masked.wrapping_add(best_len_in) as (usize))] as (i32);
    let mut best_score: u64 = (*out).score;
    let mut best_len: usize = best_len_in;
    let cached_backward: usize = distance_cache[(0usize)] as (usize);
    let mut prev_ix: usize = cur_ix.wrapping_sub(cached_backward);
    let mut is_match_found: i32 = 0i32;
    (*out).len_x_code = 0usize;
    if prev_ix < cur_ix {
      prev_ix = prev_ix & ring_buffer_mask as (u32) as (usize);
      if compare_char == data[(prev_ix.wrapping_add(best_len) as (usize))] as (i32) {
        let len: usize = FindMatchLengthWithLimitMin4(&data[(prev_ix as (usize))..],
                                                      &data[(cur_ix_masked as (usize))..],
                                                      max_length);
        if len != 0 {
          best_score = BackwardReferenceScoreUsingLastDistance(len, opts);
          best_len = len;
          (*out).len = len;
          (*out).distance = cached_backward;
          (*out).score = best_score;
          compare_char = data[(cur_ix_masked.wrapping_add(best_len) as (usize))] as (i32);
          if self.buckets_.BUCKET_SWEEP() == 1i32 {
            (*self).buckets_.slice_mut()[key as (usize)] = cur_ix as (u32);
            return true;
          } else {
            is_match_found = 1i32;
          }
        }
      }
    }
    let bucket_sweep = self.buckets_.BUCKET_SWEEP();
    if bucket_sweep == 1i32 {
      let backward: usize;
      let len: usize;
      prev_ix = (*self).buckets_.slice()[key as (usize)] as (usize);
      (*self).buckets_.slice_mut()[key as (usize)] = cur_ix as (u32);
      backward = cur_ix.wrapping_sub(prev_ix);
      prev_ix = prev_ix & ring_buffer_mask as (u32) as (usize);
      if compare_char != data[(prev_ix.wrapping_add(best_len_in) as (usize))] as (i32) {
        return false;
      }
      if backward == 0usize || backward > max_backward {
        return false;
      }
      len = FindMatchLengthWithLimitMin4(&data[(prev_ix as (usize))..],
                                     &data[(cur_ix_masked as (usize))..],
                                     max_length);
      if len != 0 {
        (*out).len = len;
        (*out).distance = backward;
        (*out).score = BackwardReferenceScore(len, backward, opts);
        return true;
      }
    } else {
      for prev_ix_ref in self.buckets_.slice().split_at(key as usize).1[..bucket_sweep as usize].iter() {
        let mut prev_ix = *prev_ix_ref as usize;
        let backward: usize = cur_ix.wrapping_sub(prev_ix);
        prev_ix = prev_ix & ring_buffer_mask as (u32) as (usize);
        if compare_char != data[(prev_ix.wrapping_add(best_len) as (usize))] as (i32) {
          continue;
        }
        if backward == 0usize || backward > max_backward {
          continue;
        }
        let len = FindMatchLengthWithLimitMin4(&data[(prev_ix as (usize))..],
                                           &data[(cur_ix_masked as (usize))..],
                                           max_length);
        if len != 0 {
          let score: u64 = BackwardReferenceScore(len, backward, opts);
          if best_score < score {
            best_score = score;
            best_len = len;
            (*out).len = best_len;
            (*out).distance = backward;
            (*out).score = score;
            compare_char = data[(cur_ix_masked.wrapping_add(best_len) as (usize))] as (i32);
            is_match_found = 1i32;
          }
        }
      }
    }
    if dictionary.is_some() && self.buckets_.USE_DICTIONARY() != 0 && (is_match_found == 0) {
      is_match_found = SearchInStaticDictionary(dictionary.unwrap(),
                                                dictionary_hash,
                                                self,
                                                &data[(cur_ix_masked as (usize))..],
                                                max_length,
                                                max_backward.wrapping_add(gap),
                                                max_distance,
                                                out,
                                                1i32);
    }
    (*self).buckets_.slice_mut()[(key as (usize)).wrapping_add((cur_ix >> 3)
                                    .wrapping_rem(bucket_sweep as usize))] = cur_ix as (u32);
    is_match_found != 0

  }
}
impl<AllocU32: alloc::Allocator<u32>> BasicHashComputer for H2Sub<AllocU32> {
  fn HashBytes(&self, data: &[u8]) -> u32 {
    let h: u64 = (BROTLI_UNALIGNED_LOAD64(data) << 64i32 - 8i32 * 5i32).wrapping_mul(kHashMul64);
    (h >> 64i32 - 16i32) as (u32)
  }
  fn BUCKET_BITS(&self) -> i32 {
    16
  }
  fn BUCKET_SWEEP(&self) -> i32 {
    1
  }
  fn USE_DICTIONARY(&self) -> i32 {
    1
  }
}
impl<AllocU32: alloc::Allocator<u32>> SliceWrapperMut<u32> for H2Sub<AllocU32> {
  fn slice_mut(&mut self) -> &mut [u32] {
    return self.buckets_.slice_mut();
  }
}
impl<AllocU32: alloc::Allocator<u32>> SliceWrapper<u32> for H2Sub<AllocU32> {
  fn slice(&self) -> &[u32] {
    return self.buckets_.slice();
  }
}
pub struct H3Sub<AllocU32: alloc::Allocator<u32>> {
  pub buckets_: AllocU32::AllocatedMemory, // 65538
}
impl<AllocU32: alloc::Allocator<u32>> SliceWrapperMut<u32> for H3Sub<AllocU32> {
  fn slice_mut(&mut self) -> &mut [u32] {
    return self.buckets_.slice_mut();
  }
}
impl<AllocU32: alloc::Allocator<u32>> SliceWrapper<u32> for H3Sub<AllocU32> {
  fn slice(&self) -> &[u32] {
    return self.buckets_.slice();
  }
}
impl<AllocU32: alloc::Allocator<u32>> BasicHashComputer for H3Sub<AllocU32> {
  fn BUCKET_BITS(&self) -> i32 {
    16
  }
  fn BUCKET_SWEEP(&self) -> i32 {
    2
  }
  fn USE_DICTIONARY(&self) -> i32 {
    0
  }
  fn HashBytes(&self, data: &[u8]) -> u32 {
    let h: u64 = (BROTLI_UNALIGNED_LOAD64(data) << 64i32 - 8i32 * 5i32).wrapping_mul(kHashMul64);
    (h >> 64i32 - 16i32) as (u32)
  }
}
pub struct H4Sub<AllocU32: alloc::Allocator<u32>> {
  pub buckets_: AllocU32::AllocatedMemory, // 131076
}
impl<AllocU32: alloc::Allocator<u32>> BasicHashComputer for H4Sub<AllocU32> {
  fn BUCKET_BITS(&self) -> i32 {
    17
  }
  fn BUCKET_SWEEP(&self) -> i32 {
    4
  }
  fn USE_DICTIONARY(&self) -> i32 {
    1
  }
  fn HashBytes(&self, data: &[u8]) -> u32 {
    let h: u64 = (BROTLI_UNALIGNED_LOAD64(data) << 64i32 - 8i32 * 5i32).wrapping_mul(kHashMul64);
    (h >> 64i32 - 17i32) as (u32)
  }
}
impl<AllocU32: alloc::Allocator<u32>> SliceWrapperMut<u32> for H4Sub<AllocU32> {
  fn slice_mut(&mut self) -> &mut [u32] {
    return self.buckets_.slice_mut();
  }
}
impl<AllocU32: alloc::Allocator<u32>> SliceWrapper<u32> for H4Sub<AllocU32> {
  fn slice(&self) -> &[u32] {
    return self.buckets_.slice();
  }
}
pub struct H54Sub<AllocU32: alloc::Allocator<u32>> {
  pub buckets_: AllocU32::AllocatedMemory,
}
impl<AllocU32: alloc::Allocator<u32>> BasicHashComputer for H54Sub<AllocU32> {
  fn BUCKET_BITS(&self) -> i32 {
    20
  }
  fn BUCKET_SWEEP(&self) -> i32 {
    4
  }
  fn USE_DICTIONARY(&self) -> i32 {
    0
  }
  fn HashBytes(&self, data: &[u8]) -> u32 {
    let h: u64 = (BROTLI_UNALIGNED_LOAD64(data) << 64i32 - 8i32 * 7i32).wrapping_mul(kHashMul64);
    (h >> 64i32 - 20i32) as (u32)
  }
}


impl<AllocU32: alloc::Allocator<u32>> SliceWrapperMut<u32> for H54Sub<AllocU32> {
  fn slice_mut(&mut self) -> &mut [u32] {
    return self.buckets_.slice_mut();
  }
}
impl<AllocU32: alloc::Allocator<u32>> SliceWrapper<u32> for H54Sub<AllocU32> {
  fn slice(&self) -> &[u32] {
    return self.buckets_.slice();
  }
}
pub const H9_BUCKET_BITS :usize = 15;
pub const H9_BLOCK_BITS :usize =8;
pub const H9_NUM_LAST_DISTANCES_TO_CHECK:usize = 16;
const H9_BLOCK_MASK :usize= (1 << H9_BLOCK_BITS) - 1;


impl H9Opts {
   pub fn new(params:&BrotliHasherParams) -> H9Opts {
      H9Opts {
         literal_byte_score: if params.literal_byte_score != 0 { params.literal_byte_score as u32} else {540},
      }
   }
}

fn adv_prepare_distance_cache(distance_cache: &mut [i32], num_distances: i32) {
        if num_distances > 4i32 {
            let last_distance: i32 = distance_cache[(0usize)];
            distance_cache[(4usize)] = last_distance - 1i32;
            distance_cache[(5usize)] = last_distance + 1i32;
            distance_cache[(6usize)] = last_distance - 2i32;
            distance_cache[(7usize)] = last_distance + 2i32;
            distance_cache[(8usize)] = last_distance - 3i32;
            distance_cache[(9usize)] = last_distance + 3i32;
            if num_distances > 10i32 {
                let next_last_distance: i32 = distance_cache[(1usize)];
                distance_cache[(10usize)] = next_last_distance - 1i32;
                distance_cache[(11usize)] = next_last_distance + 1i32;
                distance_cache[(12usize)] = next_last_distance - 2i32;
                distance_cache[(13usize)] = next_last_distance + 2i32;
                distance_cache[(14usize)] = next_last_distance - 3i32;
                distance_cache[(15usize)] = next_last_distance + 3i32;
            }
        }
}

pub const kDistanceCacheIndex : [u8;16] = [
    0, 1, 2, 3, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1,
];

pub const kDistanceCacheOffset : [i8;16]= [
    0i8,
    0i8,
    0i8,
    0i8,
    -1i8,
    1i8,
    -2i8,
    2i8,
    -3i8,
    3i8,
    -1i8,
    1i8,
    -2i8,
    2i8,
    -3i8,
    3i8];

//const BROTLI_LITERAL_BYTE_SCORE: u64 = 540;
const BROTLI_DISTANCE_BIT_PENALTY: u32 = 120;


// Score must be positive after applying maximal penalty.
const BROTLI_SCORE_BASE : u32 = (BROTLI_DISTANCE_BIT_PENALTY * 8 * 8/* sizeof usize*/);
const kDistanceShortCodeCost : [u32;16] = [
  /* Repeat last */
  BROTLI_SCORE_BASE +  60,
  /* 2nd, 3rd, 4th last */
  BROTLI_SCORE_BASE -  95,
  BROTLI_SCORE_BASE - 117,
  BROTLI_SCORE_BASE - 127,
  /* Last with offset */
  BROTLI_SCORE_BASE -  93,
  BROTLI_SCORE_BASE -  93,
  BROTLI_SCORE_BASE -  96,
  BROTLI_SCORE_BASE -  96,
  BROTLI_SCORE_BASE -  99,
  BROTLI_SCORE_BASE -  99,
  /* 2nd last with offset */
  BROTLI_SCORE_BASE - 105,
  BROTLI_SCORE_BASE - 105,
  BROTLI_SCORE_BASE - 115,
  BROTLI_SCORE_BASE - 115,
  BROTLI_SCORE_BASE - 125,
  BROTLI_SCORE_BASE - 125
];

pub trait AdvHashSpecialization : PartialEq<Self>{
  #[inline(always)]
  fn get_hash_mask(&self) -> u64;
  #[inline(always)]
  fn set_hash_mask(&mut self, params_hash_len: i32);
  #[inline(always)]
  fn get_k_hash_mul(&self) -> u64;
  #[inline(always)]
  fn HashTypeLength(&self) -> usize;
  #[inline(always)]
  fn StoreLookahead(&self) -> usize;
    #[inline(always)]
  fn load_and_mix_word(&self, data: &[u8]) -> u64;
    #[inline(always)]
  fn hash_shift(&self) -> i32;
    #[inline(always)]
  fn bucket_size(&self) -> u32;
    #[inline(always)]
  fn block_mask(&self) -> u32;
    #[inline(always)]
  fn block_size(&self) -> u32;
  #[inline(always)]
  fn block_bits(&self) -> i32;
}
pub struct AdvHasher<Specialization: AdvHashSpecialization + Sized + Clone,
                     Alloc: alloc::Allocator<u16> + alloc::Allocator<u32>>
{
  pub GetHasherCommon: Struct1,
  pub specialization: Specialization, // contains hash_mask_
  pub num: <Alloc as Allocator<u16>>::AllocatedMemory,
  pub buckets: <Alloc as Allocator<u32>>::AllocatedMemory,
  pub h9_opts: H9Opts,
}

impl<Specialization: AdvHashSpecialization + Sized + Clone,
     Alloc: alloc::Allocator<u16> + alloc::Allocator<u32>> PartialEq<AdvHasher<Specialization, Alloc>> for AdvHasher<Specialization, Alloc> {
  fn eq(&self, other: &Self) -> bool {
    self.GetHasherCommon == other.GetHasherCommon
      && self.specialization == other.specialization
      && self.num.slice() == other.num.slice()
      && self.buckets.slice() == other.buckets.slice()
      && self.h9_opts == other.h9_opts
  }
}


#[derive(Clone, PartialEq)]
pub struct HQ5Sub {}
impl AdvHashSpecialization for HQ5Sub {
  #[inline(always)]
  fn hash_shift(&self) -> i32 {
    32i32 - 14 // 32 - bucket_bits
  }
  #[inline(always)]
  fn bucket_size(&self) -> u32 {
    1 << 14
  }
  #[inline(always)]
  fn block_bits(&self) -> i32 {
    4
  }
  #[inline(always)]
  fn block_size(&self) -> u32 {
    1 << 4
  }
  #[inline(always)]
  fn block_mask(&self) -> u32 {
    (1 << 4) - 1
  }
  #[inline(always)]
  fn get_hash_mask(&self) -> u64 {
    //return 0xffffffffffffffffu64;
    return 0xffffffffu64; // make it 32 bit
  }
  #[inline(always)]
  fn get_k_hash_mul(&self) -> u64 {
    return kHashMul32 as u64;
  }
  #[inline(always)]
  fn load_and_mix_word(&self, data: &[u8]) -> u64 {
    return (BROTLI_UNALIGNED_LOAD32(data) as u64 * self.get_k_hash_mul()) & self.get_hash_mask();
  }
  #[inline(always)]
  fn set_hash_mask(&mut self, _params_hash_len: i32) {}
  fn HashTypeLength(&self) -> usize {
    4
  }
  #[inline(always)]
  fn StoreLookahead(&self) -> usize {
    4
  }
}


#[derive(Clone, PartialEq)]
pub struct HQ7Sub {}
impl AdvHashSpecialization for HQ7Sub {
  #[inline(always)]
  fn hash_shift(&self) -> i32 {
    32i32 - 15 // 32 - bucket_bits
  }
  #[inline(always)]
  fn bucket_size(&self) -> u32 {
    1 << 15
  }
  #[inline(always)]
  fn block_bits(&self) -> i32 {
    6
  }
  #[inline(always)]
  fn block_size(&self) -> u32 {
    1 << 6
  }
  #[inline(always)]
  fn block_mask(&self) -> u32 {
    (1 << 6) - 1
  }
  #[inline(always)]
  fn get_hash_mask(&self) -> u64 {
    //return 0xffffffffffffffffu64;
    return 0xffffffffu64; // make it 32 bit
  }
  #[inline(always)]
  fn get_k_hash_mul(&self) -> u64 {
    return kHashMul32 as u64;
  }
  #[inline(always)]
  fn load_and_mix_word(&self, data: &[u8]) -> u64 {
    return (BROTLI_UNALIGNED_LOAD32(data) as u64 * self.get_k_hash_mul()) & self.get_hash_mask();
  }
  #[inline(always)]
  fn set_hash_mask(&mut self, _params_hash_len: i32) {}
  fn HashTypeLength(&self) -> usize {
    4
  }
  #[inline(always)]
  fn StoreLookahead(&self) -> usize {
    4
  }
}


#[derive(Clone, PartialEq)]
pub struct H9Sub {}
impl AdvHashSpecialization for H9Sub {
  #[inline(always)]
  fn hash_shift(&self) -> i32 {
    32i32 - H9_BUCKET_BITS as i32 // 32 - bucket_bits
  }
  #[inline(always)]
  fn bucket_size(&self) -> u32 {
    1 << H9_BUCKET_BITS
  }
  #[inline(always)]
  fn block_bits(&self) -> i32 {
    H9_BLOCK_BITS as i32
  }
  #[inline(always)]
  fn block_size(&self) -> u32 {
    1 << H9_BLOCK_BITS
  }
  #[inline(always)]
  fn block_mask(&self) -> u32 {
    (1 << H9_BLOCK_BITS) - 1
  }
  #[inline(always)]
  fn get_hash_mask(&self) -> u64 {
    //return 0xffffffffffffffffu64;
    return 0xffffffffu64; // make it 32 bit
  }
  #[inline(always)]
  fn get_k_hash_mul(&self) -> u64 {
    return kHashMul32 as u64;
  }
  #[inline(always)]
  fn load_and_mix_word(&self, data: &[u8]) -> u64 {
    return (BROTLI_UNALIGNED_LOAD32(data) as u64 * self.get_k_hash_mul()) & self.get_hash_mask();
  }
  #[inline(always)]
  fn set_hash_mask(&mut self, _params_hash_len: i32) {}
  fn HashTypeLength(&self) -> usize {
    4
  }
  #[inline(always)]
  fn StoreLookahead(&self) -> usize {
    4
  }
}


#[derive(Clone, PartialEq)]
pub struct H5Sub {
  pub hash_shift_: i32,
  pub bucket_size_: u32,
  pub block_mask_:u32,
  pub block_bits_: i32,
}

impl AdvHashSpecialization for H5Sub {
  #[inline(always)]
  fn hash_shift(&self) -> i32 {
    return self.hash_shift_
  }
  fn bucket_size(&self) -> u32 {
    return self.bucket_size_
  }
  fn block_bits(&self) -> i32 {
    self.block_bits_
  }
  fn block_size(&self) -> u32 {
    1 << self.block_bits_
  }
  fn block_mask(&self) -> u32 {
    return self.block_mask_
  }
  fn get_hash_mask(&self) -> u64 {
    //return 0xffffffffffffffffu64;
    return 0xffffffffu64; // make it 32 bit
  }
  fn get_k_hash_mul(&self) -> u64 {
    return kHashMul32 as u64;
  }
  fn load_and_mix_word(&self, data: &[u8]) -> u64 {
    return (BROTLI_UNALIGNED_LOAD32(data) as u64 * self.get_k_hash_mul()) & self.get_hash_mask();
  }
  #[allow(unused_variables)]
  fn set_hash_mask(&mut self, params_hash_len: i32) {}
  fn HashTypeLength(&self) -> usize {
    4
  }
  fn StoreLookahead(&self) -> usize {
    4
  }
}

#[derive(Clone, PartialEq)]
pub struct H6Sub {
  pub hash_mask: u64,
  pub hash_shift_: i32,
  pub bucket_size_: u32,
  pub block_mask_:u32,
  pub block_bits_: i32,
}

impl AdvHashSpecialization for H6Sub {
  #[inline(always)]
  fn hash_shift(&self) -> i32 {
    return self.hash_shift_
  }
  #[inline(always)]
  fn bucket_size(&self) -> u32 {
    return self.bucket_size_
  }
  fn block_bits(&self) -> i32 {
    self.block_bits_
  }
  fn block_size(&self) -> u32 {
    1 << self.block_bits_
  }
  #[inline(always)]
  fn block_mask(&self) -> u32 {
    return self.block_mask_
  }
  #[inline(always)]
  fn get_hash_mask(&self) -> u64 {
    self.hash_mask
  }
  #[inline(always)]
  fn set_hash_mask(&mut self, params_hash_len: i32) {
    self.hash_mask = !(0u32 as (u64)) >> 64i32 - 8i32 * params_hash_len;
  }
  #[inline(always)]
  fn get_k_hash_mul(&self) -> u64 {
    kHashMul64Long
  }
  #[inline(always)]
  fn load_and_mix_word(&self, data: &[u8]) -> u64 {
    return (BROTLI_UNALIGNED_LOAD64(data) & self.get_hash_mask())
             .wrapping_mul(self.get_k_hash_mul());
  }
  #[inline(always)]
  fn HashTypeLength(&self) -> usize {
    8
  }
  #[inline(always)]
  fn StoreLookahead(&self) -> usize {
    8
  }
}

fn BackwardReferencePenaltyUsingLastDistance(distance_short_code: usize) -> u64 {
  (39u64).wrapping_add((0x1ca10u64 >> (distance_short_code & 0xeusize) & 0xeu64))
}

impl<Specialization: AdvHashSpecialization + Clone, Alloc: alloc::Allocator<u16> + alloc::Allocator<u32>> AdvHasher<Specialization, Alloc> {
  // 7 opt
  // returns a new ix_start
  fn StoreRangeOptBatch(&mut self, data: &[u8], mask: usize, ix_start: usize, ix_end: usize) -> usize {
    let lookahead = self.specialization.StoreLookahead();
    if ix_end >= ix_start + lookahead * 2 && lookahead == 4{
      let num = self.num.slice_mut();
      let buckets = self.buckets.slice_mut();
      assert_eq!(num.len(), self.specialization.bucket_size() as usize);
      assert_eq!(buckets.len(), self.specialization.bucket_size() as usize * self.specialization.block_size() as usize);
      let shift = self.specialization.hash_shift();
      let chunk_count = (ix_end - ix_start) / 4;
      for chunk_id in 0..chunk_count {
        let i = (ix_start + chunk_id * 4) & mask;
        let ffffffff = 0xffffffff;
        let word = u64::from(data[i])
          | (u64::from(data[i + 1]) << 8)
          | (u64::from(data[i + 2]) << 16)
          | (u64::from(data[i + 3]) << 24)
          | (u64::from(data[i + 4]) << 32)
          | (u64::from(data[i + 5]) << 40)
          | (u64::from(data[i + 6]) << 48);
          let mixed0 = ((((word & ffffffff) * self.specialization.get_k_hash_mul()) & self.specialization.get_hash_mask()) >> shift) as usize;
          let mixed1 = (((((word >> 8) & ffffffff) * self.specialization.get_k_hash_mul()) & self.specialization.get_hash_mask()) >> shift) as usize;
          let mixed2 = (((((word >> 16) & ffffffff) * self.specialization.get_k_hash_mul()) & self.specialization.get_hash_mask()) >> shift) as usize;
          let mixed3 = (((((word >> 24) & ffffffff) * self.specialization.get_k_hash_mul()) & self.specialization.get_hash_mask()) >> shift) as usize;
          let mut num_ref0 = u32::from(num[mixed0]);
          num[mixed0] = num_ref0.wrapping_add(1) as u16;
          num_ref0 &= (*self).specialization.block_mask();
          let mut num_ref1 = u32::from(num[mixed1]);
          num[mixed1] = num_ref1.wrapping_add(1) as u16;
          num_ref1 &= (*self).specialization.block_mask();
          let mut num_ref2 = u32::from(num[mixed2]);
          num[mixed2] = num_ref2.wrapping_add(1) as u16;
          num_ref2 &= (*self).specialization.block_mask();
          let mut num_ref3 = u32::from(num[mixed3]);
          num[mixed3] = num_ref3.wrapping_add(1) as u16;
          num_ref3 &= (*self).specialization.block_mask();
          let offset0: usize = (mixed0 << self.specialization.block_bits()) + num_ref0 as usize;
          let offset1: usize = (mixed1 << self.specialization.block_bits()) + num_ref1 as usize;
          let offset2: usize = (mixed2 << self.specialization.block_bits()) + num_ref2 as usize;
          let offset3: usize = (mixed3 << self.specialization.block_bits()) + num_ref3 as usize;
          buckets[offset0] = (i) as u32;
          buckets[offset1] = (i + 1) as u32;
          buckets[offset2] = (i + 2) as u32;
          buckets[offset3] = (i + 3) as u32;
      }
      return ix_start + chunk_count * 4;
    }
    ix_start
  }

  fn BulkStoreRangeOptMemFetch(&mut self, data: &[u8], mask: usize, ix_start: usize, ix_end: usize) -> usize {
      const REG_SIZE : usize = 32usize;
    let lookahead = self.specialization.StoreLookahead();
      if mask == !0 && ix_end > ix_start + REG_SIZE && lookahead == 4{
      const lookahead4: usize = 4;
      assert_eq!(lookahead4, lookahead);
      let mut data64 = [0u8;REG_SIZE + lookahead4 - 1];
      let del = (ix_end - ix_start) / REG_SIZE;
      let num = self.num.slice_mut();
      let buckets = self.buckets.slice_mut();
      assert_eq!(num.len(), self.specialization.bucket_size() as usize);
      assert_eq!(buckets.len(), self.specialization.bucket_size() as usize * self.specialization.block_size() as usize);
      let shift = self.specialization.hash_shift();
      for chunk_id in 0..del {
        let ix_offset = ix_start + chunk_id * REG_SIZE;
        data64[..REG_SIZE + lookahead4 - 1].clone_from_slice(data.split_at(ix_offset).1.split_at(REG_SIZE + lookahead4 - 1).0);
        for quad_index in 0..(REG_SIZE>>2) {
          let i = quad_index<<2;
          let ffffffff = 0xffffffff;
          let word = u64::from(data64[i])
            | (u64::from(data64[i + 1]) << 8)
            | (u64::from(data64[i + 2]) << 16)
            | (u64::from(data64[i + 3]) << 24)
            | (u64::from(data64[i + 4]) << 32)
            | (u64::from(data64[i + 5]) << 40)
            | (u64::from(data64[i + 6]) << 48);
          let mixed0 = ((((word & ffffffff) * self.specialization.get_k_hash_mul()) & self.specialization.get_hash_mask()) >> shift) as usize;
          let mixed1 = (((((word >> 8) & ffffffff) * self.specialization.get_k_hash_mul()) & self.specialization.get_hash_mask()) >> shift) as usize;
          let mixed2 = (((((word >> 16) & ffffffff) * self.specialization.get_k_hash_mul()) & self.specialization.get_hash_mask()) >> shift) as usize;
          let mixed3 = (((((word >> 24) & ffffffff) * self.specialization.get_k_hash_mul()) & self.specialization.get_hash_mask()) >> shift) as usize;
          let mut num_ref0 = u32::from(num[mixed0]);
          num[mixed0] = num_ref0.wrapping_add(1) as u16;
          num_ref0 &= (*self).specialization.block_mask();
          let mut num_ref1 = u32::from(num[mixed1]);
          num[mixed1] = num_ref1.wrapping_add(1) as u16;
          num_ref1 &= (*self).specialization.block_mask();
          let mut num_ref2 = u32::from(num[mixed2]);
          num[mixed2] = num_ref2.wrapping_add(1) as u16;
          num_ref2 &= (*self).specialization.block_mask();
          let mut num_ref3 = u32::from(num[mixed3]);
          num[mixed3] = num_ref3.wrapping_add(1) as u16;
          num_ref3 &= (*self).specialization.block_mask();
          let offset0: usize = (mixed0 << self.specialization.block_bits()) + num_ref0 as usize;
          let offset1: usize = (mixed1 << self.specialization.block_bits()) + num_ref1 as usize;
          let offset2: usize = (mixed2 << self.specialization.block_bits()) + num_ref2 as usize;
          let offset3: usize = (mixed3 << self.specialization.block_bits()) + num_ref3 as usize;
          buckets[offset0] = (ix_offset + i) as u32;
          buckets[offset1] = (ix_offset + i + 1) as u32;
          buckets[offset2] = (ix_offset + i + 2) as u32;
          buckets[offset3] = (ix_offset + i + 3) as u32;
        }
      }
      return ix_start + del * REG_SIZE;
      }
    ix_start
  }
  fn BulkStoreRangeOptMemFetchLazyDupeUpdate(&mut self, data: &[u8], mask: usize, ix_start: usize, ix_end: usize) -> usize {
    const REG_SIZE : usize = 32usize;
    let lookahead = self.specialization.StoreLookahead();
    if mask == !0 && ix_end > ix_start + REG_SIZE && lookahead == 4{
      const lookahead4: usize = 4;
      assert_eq!(lookahead4, lookahead);
      let mut data64 = [0u8;REG_SIZE + lookahead4];
      let del = (ix_end - ix_start) / REG_SIZE;
      let num = self.num.slice_mut();
      let buckets = self.buckets.slice_mut();
      assert_eq!(num.len(), self.specialization.bucket_size() as usize);
      assert_eq!(buckets.len(), self.specialization.bucket_size() as usize * self.specialization.block_size() as usize);
      let shift = self.specialization.hash_shift();
      for chunk_id in 0..del {
        let ix_offset = ix_start + chunk_id * REG_SIZE;
        data64[..REG_SIZE + lookahead4].clone_from_slice(data.split_at(ix_offset).1.split_at(REG_SIZE + lookahead4).0);
        for quad_index in 0..(REG_SIZE>>2) {
          let i = quad_index<<2;
          let ffffffff = 0xffffffff;
          let word = u64::from(data64[i])
            | (u64::from(data64[i + 1]) << 8)
            | (u64::from(data64[i + 2]) << 16)
            | (u64::from(data64[i + 3]) << 24)
            | (u64::from(data64[i + 4]) << 32)
            | (u64::from(data64[i + 5]) << 40)
            | (u64::from(data64[i + 6]) << 48);
          let mixed0 = ((((word & ffffffff) * self.specialization.get_k_hash_mul()) & self.specialization.get_hash_mask()) >> shift) as usize;
          let mixed1 = (((((word >> 8) & ffffffff) * self.specialization.get_k_hash_mul()) & self.specialization.get_hash_mask()) >> shift) as usize;
          let mixed2 = (((((word >> 16) & ffffffff) * self.specialization.get_k_hash_mul()) & self.specialization.get_hash_mask()) >> shift) as usize;
          let mixed3 = (((((word >> 24) & ffffffff) * self.specialization.get_k_hash_mul()) & self.specialization.get_hash_mask()) >> shift) as usize;
          let mut num_ref0 = u32::from(num[mixed0]);
          let mut num_ref1 = u32::from(num[mixed1]);
          let mut num_ref2 = u32::from(num[mixed2]);
          let mut num_ref3 = u32::from(num[mixed3]);
          num[mixed0] = num_ref0.wrapping_add(1) as u16;
          num[mixed1] = num_ref1.wrapping_add(1) as u16;
          num[mixed2] = num_ref2.wrapping_add(1) as u16;
          num[mixed3] = num_ref3.wrapping_add(1) as u16;
          num_ref0 &= (*self).specialization.block_mask();
          num_ref1 &= (*self).specialization.block_mask();
          num_ref2 &= (*self).specialization.block_mask();
          num_ref3 &= (*self).specialization.block_mask();
          let offset0: usize = (mixed0 << self.specialization.block_bits()) + num_ref0 as usize;
          let offset1: usize = (mixed1 << self.specialization.block_bits()) + num_ref1 as usize;
          let offset2: usize = (mixed2 << self.specialization.block_bits()) + num_ref2 as usize;
          let offset3: usize = (mixed3 << self.specialization.block_bits()) + num_ref3 as usize;
          buckets[offset0] = (ix_offset + i) as u32;
          buckets[offset1] = (ix_offset + i + 1) as u32;
          buckets[offset2] = (ix_offset + i + 2) as u32;
          buckets[offset3] = (ix_offset + i + 3) as u32;
        }
      }
      return ix_start + del * REG_SIZE;
    }
    ix_start
  }
  fn BulkStoreRangeOptRandomDupeUpdate(&mut self, data: &[u8], mask: usize, ix_start: usize, ix_end: usize) -> usize {
    const REG_SIZE : usize = 32usize;
    let lookahead = self.specialization.StoreLookahead();
    if mask == !0 && ix_end > ix_start + REG_SIZE && lookahead == 4{
      const lookahead4: usize = 4;
      assert_eq!(lookahead4, lookahead);
      let mut data64 = [0u8;REG_SIZE + lookahead4];
      let del = (ix_end - ix_start) / REG_SIZE;
      let num = self.num.slice_mut();
      let buckets = self.buckets.slice_mut();
      assert_eq!(num.len(), self.specialization.bucket_size() as usize);
      assert_eq!(buckets.len(), self.specialization.bucket_size() as usize * self.specialization.block_size() as usize);
      let shift = self.specialization.hash_shift();
      for chunk_id in 0..del {
        let ix_offset = ix_start + chunk_id * REG_SIZE;
        data64[..REG_SIZE + lookahead4].clone_from_slice(data.split_at(ix_offset).1.split_at(REG_SIZE + lookahead4).0);
        for i in 0..REG_SIZE {
          let mixed_word = ((u32::from(data64[i])
                             | (u32::from(data64[i + 1]) << 8)
                             | (u32::from(data64[i + 2]) << 16)
                             | (u32::from(data64[i + 3]) << 24)) as u64
                            * self.specialization.get_k_hash_mul()) & self.specialization.get_hash_mask();
          let key = mixed_word >> shift;
          let minor_ix: usize = chunk_id&(*self).specialization.block_mask() as usize;//   *num_ref as usize & (*self).specialization.block_mask() as usize; //GIGANTIC HAX: overwrite firsst option
          let offset: usize = minor_ix + (key << self.specialization.block_bits()) as usize;
          buckets[offset] = (ix_offset + i) as u32;
        }
      }
      for (bucket_index, num_ref) in num.iter_mut().enumerate() {
        let region = buckets.split_at_mut(bucket_index << self.specialization.block_bits()).1.split_at_mut( self.specialization.block_size() as usize).0;
        let mut lnum = 0usize;
        for block_index in 0..self.specialization.block_size() as usize{
          if region[block_index] != 0 {
            let byte_addr = region[block_index];
            region[lnum] = byte_addr;
            lnum += 1;
          }
        }
        *num_ref = lnum as u16;
      }
      return ix_start + del * REG_SIZE;
    }
    ix_start
  }
}

impl<Specialization: AdvHashSpecialization + Clone, Alloc: alloc::Allocator<u16> + alloc::Allocator<u32>> AnyHasher
  for AdvHasher<Specialization, Alloc> {
  fn Opts(&self) -> H9Opts {
     self.h9_opts
  }
  fn PrepareDistanceCache(&self, distance_cache: &mut [i32]){
    let num_distances = self.GetHasherCommon.params.num_last_distances_to_check;
    adv_prepare_distance_cache(distance_cache, num_distances);
  }
  fn StitchToPreviousBlock(&mut self,
                           num_bytes: usize,
                           position: usize,
                           ringbuffer: &[u8],
                           ringbuffer_mask: usize) {
      StitchToPreviousBlockInternal(self,
                                    num_bytes,
                                    position,
                                    ringbuffer,
                                    ringbuffer_mask);
  }
  fn Prepare(&mut self, one_shot: bool, input_size:usize, data:&[u8]) ->HowPrepared {
      if self.GetHasherCommon.is_prepared_ != 0 {
          return HowPrepared::ALREADY_PREPARED;
      }
      let partial_prepare_threshold = self.specialization.bucket_size() as usize >> 6;
      if one_shot && input_size <= partial_prepare_threshold {
        for i in 0..input_size {
          let key = self.HashBytes(&data[i..]);
          self.num.slice_mut()[key] = 0;
        }
      } else {
        for item in self.num.slice_mut()[..(self.specialization.bucket_size() as usize)].iter_mut() {
          *item =0;
        }
      }
      self.GetHasherCommon.is_prepared_ = 1;
      HowPrepared::NEWLY_PREPARED
  }

  fn GetHasherCommon(&mut self) -> &mut Struct1 {
    &mut self.GetHasherCommon
  }
  fn HashTypeLength(&self) -> usize {
     self.specialization.HashTypeLength()
  }
  fn StoreLookahead(&self) -> usize {
     self.specialization.StoreLookahead()
  }
  fn HashBytes(&self, data: &[u8]) -> usize {
    let shift = self.specialization.hash_shift();
    let h: u64 = self.specialization.load_and_mix_word(data);
    (h >> shift) as (u32) as usize
  }
  fn StoreEvenVec4(&mut self, data: &[u8], mask: usize, ix: usize) {
    if self.specialization.StoreLookahead() != 4 {
      for i in 0..4 {
        self.Store(data, mask, ix + i * 2);
      }
      return;
    }
    let shift = self.specialization.hash_shift();
    let num = self.num.slice_mut();
    let buckets = self.buckets.slice_mut();
    let li = ix & mask;
    let lword = u64::from(data[li])
      | (u64::from(data[li + 1]) << 8)
      | (u64::from(data[li + 2]) << 16)
      | (u64::from(data[li + 3]) << 24)
      | (u64::from(data[li + 4]) << 32)
      | (u64::from(data[li + 5]) << 40)
      | (u64::from(data[li + 6]) << 48)
      | (u64::from(data[li + 7]) << 56);
    let hi = (ix + 8) & mask;
    let hword = u64::from(data[hi])
      | (u64::from(data[hi + 1]) << 8);
    let mixed0 = ((((lword & 0xffffffff) * self.specialization.get_k_hash_mul()) & self.specialization.get_hash_mask()) >> shift) as usize;
    let mixed1 = (((((lword >> 16) & 0xffffffff) * self.specialization.get_k_hash_mul()) & self.specialization.get_hash_mask()) >> shift) as usize;
    let mixed2 = (((((lword >> 32) & 0xffffffff) * self.specialization.get_k_hash_mul()) & self.specialization.get_hash_mask()) >> shift) as usize;
    let mixed3 = ((((((hword & 0xffff) << 16) | ((lword >> 48) & 0xffff)) * self.specialization.get_k_hash_mul()) & self.specialization.get_hash_mask()) >> shift) as usize;
    let mut num_ref0 = u32::from(num[mixed0]);
    num[mixed0] = num_ref0.wrapping_add(1) as u16;
    num_ref0 &= (*self).specialization.block_mask();
    let mut num_ref1 = u32::from(num[mixed1]);
    num[mixed1] = num_ref1.wrapping_add(1) as u16;
    num_ref1 &= (*self).specialization.block_mask();
    let mut num_ref2 = u32::from(num[mixed2]);
    num[mixed2] = num_ref2.wrapping_add(1) as u16;
    num_ref2 &= (*self).specialization.block_mask();
    let mut num_ref3 = u32::from(num[mixed3]);
    num[mixed3] = num_ref3.wrapping_add(1) as u16;
    num_ref3 &= (*self).specialization.block_mask();
    let offset0: usize = (mixed0 << self.specialization.block_bits()) + num_ref0 as usize;
    let offset1: usize = (mixed1 << self.specialization.block_bits()) + num_ref1 as usize;
    let offset2: usize = (mixed2 << self.specialization.block_bits()) + num_ref2 as usize;
    let offset3: usize = (mixed3 << self.specialization.block_bits()) + num_ref3 as usize;
    buckets[offset0] = ix as u32;
    buckets[offset1] = (ix + 2) as u32;
    buckets[offset2] = (ix + 4) as u32;
    buckets[offset3] = (ix + 6) as u32;
  }
  fn Store4Vec4(&mut self, data: &[u8], mask: usize, ix: usize) {
    if self.specialization.StoreLookahead() != 4 {
      for i in 0..4 {
        self.Store(data, mask, ix + i * 4);
      }
      return;
    }
    let shift = self.specialization.hash_shift();
    let num = self.num.slice_mut();
    let buckets = self.buckets.slice_mut();
    let li = ix & mask;
    let llword = u32::from(data[li])
      | (u32::from(data[li + 1]) << 8)
      | (u32::from(data[li + 2]) << 16)
      | (u32::from(data[li + 3]) << 24);
    let luword = u32::from(data[li + 4])
      | (u32::from(data[li + 5]) << 8)
      | (u32::from(data[li + 6]) << 16)
      | (u32::from(data[li + 7]) << 24);
    let ui = (ix + 8) & mask;
    let ulword = u32::from(data[ui])
      | (u32::from(data[ui + 1]) << 8)
      | (u32::from(data[ui + 2]) << 16)
      | (u32::from(data[ui + 3]) << 24);
    
    let uuword = u32::from(data[ui + 4])
      | (u32::from(data[ui + 5]) << 8)
      | (u32::from(data[ui + 6]) << 16)
      | (u32::from(data[ui + 7]) << 24);

    let mixed0 = (((u64::from(llword) * self.specialization.get_k_hash_mul()) & self.specialization.get_hash_mask()) >> shift) as usize;
    let mixed1 = (((u64::from(luword) * self.specialization.get_k_hash_mul()) & self.specialization.get_hash_mask()) >> shift) as usize;
    let mixed2 = (((u64::from(ulword) * self.specialization.get_k_hash_mul()) & self.specialization.get_hash_mask()) >> shift) as usize;
    let mixed3 = (((u64::from(uuword) * self.specialization.get_k_hash_mul()) & self.specialization.get_hash_mask()) >> shift) as usize;
    let mut num_ref0 = u32::from(num[mixed0]);
    num[mixed0] = num_ref0.wrapping_add(1) as u16;
    num_ref0 &= (*self).specialization.block_mask();
    let mut num_ref1 = u32::from(num[mixed1]);
    num[mixed1] = num_ref1.wrapping_add(1) as u16;
    num_ref1 &= (*self).specialization.block_mask();
    let mut num_ref2 = u32::from(num[mixed2]);
    num[mixed2] = num_ref2.wrapping_add(1) as u16;
    num_ref2 &= (*self).specialization.block_mask();
    let mut num_ref3 = u32::from(num[mixed3]);
    num[mixed3] = num_ref3.wrapping_add(1) as u16;
    num_ref3 &= (*self).specialization.block_mask();
    let offset0: usize = (mixed0 << self.specialization.block_bits()) + num_ref0 as usize;
    let offset1: usize = (mixed1 << self.specialization.block_bits()) + num_ref1 as usize;
    let offset2: usize = (mixed2 << self.specialization.block_bits()) + num_ref2 as usize;
    let offset3: usize = (mixed3 << self.specialization.block_bits()) + num_ref3 as usize;
    buckets[offset0] = ix as u32;
    buckets[offset1] = (ix + 4) as u32;
    buckets[offset2] = (ix + 8) as u32;
    buckets[offset3] = (ix + 12) as u32;
  }
  fn Store(&mut self, data: &[u8], mask: usize, ix: usize) {
    let (_, data_window) = data.split_at((ix & mask) as (usize));
    let key: u32 = self.HashBytes(data_window) as u32;
    let minor_ix: usize = (self.num.slice()[(key as (usize))] as (u32) & (*self).specialization.block_mask() as u32) as (usize);
    let offset: usize = minor_ix.wrapping_add((key << (*self).specialization.block_bits()) as
                                              (usize));
    self.buckets.slice_mut()[offset] = ix as (u32);
    {
      let _lhs = &mut self.num.slice_mut()[(key as (usize))];
      *_lhs = (*_lhs as (i32) + 1) as (u16);
    }
  }
    fn StoreRange(&mut self, data: &[u8], mask: usize, ix_start: usize, ix_end: usize) {
      for i in self.StoreRangeOptBatch(data, mask, ix_start, ix_end)..ix_end {
        self.Store(data, mask, i);
      }
    }
    fn BulkStoreRange(&mut self, data: &[u8], mask: usize, mut ix_start: usize, ix_end: usize) {
      /*
      if ix_start + 4096 < ix_end {
        for vec_offset in 0..(ix_end - ix_start - 4096) / 16 {
          self.Store4Vec4(data, mask, ix_start + vec_offset * 16);
        }
        ix_start += 16 * ((ix_end - ix_start - 4096) / 16);
      }
      if ix_start + 512 < ix_end {
        for vec_offset in 0..(ix_end - ix_start - 512) / 8 {
          self.StoreEvenVec4(data, mask, ix_start + vec_offset * 8);
          //self.StoreRange(data, mask, ix_start + vec_offset * 8, ix_start + (1+ vec_offset) * 8);
        }
        ix_start += 8 * ((ix_end - ix_start - 512) / 8);
      }
       */
      ix_start = self.BulkStoreRangeOptMemFetch(data, mask, ix_start, ix_end);
      for i in ix_start..ix_end {
        self.Store(data, mask, i);
      }
    }

  fn FindLongestMatch(&mut self,
                      dictionary: Option<&BrotliDictionary>,
                      dictionary_hash: &[u16],
                      data: &[u8],
                      ring_buffer_mask: usize,
                      distance_cache: &[i32],
                      cur_ix: usize,
                      max_length: usize,
                      max_backward: usize,
                      gap: usize,
                      max_distance: usize,
                      out: &mut HasherSearchResult)
                      -> bool {
    let opts = self.Opts();
    let cur_ix_masked: usize = cur_ix & ring_buffer_mask;
    let mut is_match_found: i32 = 0i32;
    let mut best_score: u64 = (*out).score;
    let mut best_len: usize = (*out).len;
    let mut i: usize;
    (*out).len = 0usize;
    (*out).len_x_code = 0usize;
    let cur_data = data.split_at(cur_ix_masked).1;
    let mut prev_best = cur_data[best_len];
    for i in 0..self.GetHasherCommon.params.num_last_distances_to_check as (usize) {
      let backward: usize = distance_cache[(i as (usize))] as (usize);
      let mut prev_ix: usize = cur_ix.wrapping_sub(backward);
      if prev_ix >= cur_ix {
        continue;
      }
      if backward > max_backward {
        continue;
      }
      prev_ix = prev_ix & ring_buffer_mask;
      if (cur_ix_masked.wrapping_add(best_len) > ring_buffer_mask || prev_ix.wrapping_add(best_len) > ring_buffer_mask ||
        prev_best != data[prev_ix.wrapping_add(best_len)]) {
        continue;
      }
      let prev_data = data.split_at(prev_ix).1;
          
      let len: usize = FindMatchLengthWithLimit(&prev_data,
                                                cur_data,
                                                max_length);
      if len >= 3usize || len == 2usize && (i < 2usize) {
        let mut score: u64 = BackwardReferenceScoreUsingLastDistance(len, opts);
        if best_score < score {
          if i != 0usize {
                score = score.wrapping_sub(BackwardReferencePenaltyUsingLastDistance(i));
          }
          if best_score < score {
            best_score = score;
            best_len = len;
            (*out).len = best_len;
            (*out).distance = backward;
            (*out).score = best_score;
            is_match_found = 1i32;
            prev_best = cur_data[best_len];
          }
        }
      }
    }
    {
      let key: u32 = self.HashBytes(cur_data) as u32;
      let common_block_bits = self.specialization.block_bits();
      let num_ref_mut = &mut self.num.slice_mut()[key as usize];
      let num_copy = *num_ref_mut;
      let bucket: &mut [u32] = self.buckets.slice_mut().split_at_mut((key << common_block_bits) as (usize)).1.split_at_mut(
        (*self).specialization.block_size() as usize).0;
      assert!(bucket.len() > (*self).specialization.block_mask() as usize);
      if num_copy != 0 {
        let down: usize = core::cmp::max(i32::from(num_copy) - (*self).specialization.block_size() as i32,
                                         0) as usize;
        i = num_copy as (usize);
        while i > down {
          i -= 1;
          let mut prev_ix = bucket[i & (*self).specialization.block_mask() as usize] as usize;
          let backward = cur_ix.wrapping_sub(prev_ix);
          prev_ix &= ring_buffer_mask;
          if (cur_ix_masked.wrapping_add(best_len) > ring_buffer_mask || prev_ix.wrapping_add(best_len) > ring_buffer_mask ||
              cur_data[best_len] != data[prev_ix.wrapping_add(best_len)]) {
            if backward > max_backward {
              break;
            }
            continue;
          }
          if backward > max_backward {
            break;
          }
          let prev_data = data.split_at(prev_ix as usize).1;
          let len = FindMatchLengthWithLimitMin4(&prev_data,
                                                 &cur_data,
                                                 max_length);
          if len != 0 {
            let score: u64 = BackwardReferenceScore(len, backward, opts);
            if best_score < score {
              best_score = score;
              best_len = len;
              (*out).len = best_len;
              (*out).distance = backward;
              (*out).score = best_score;
              is_match_found = 1i32;
            }
          }
        }
      }
      bucket[((num_copy as (u32) & (self).specialization.block_mask() as u32) as (usize))] = cur_ix as (u32);
      *num_ref_mut = num_ref_mut.wrapping_add(1);
    }
    if is_match_found == 0 && dictionary.is_some() {
      let (_, cur_data) = data.split_at(cur_ix_masked as usize);
      is_match_found = SearchInStaticDictionary(dictionary.unwrap(),
                                                dictionary_hash,
                                                self,
                                                cur_data,
                                                max_length,
                                                max_backward.wrapping_add(gap),
                                                max_distance,
                                                out,
                                                0i32);
    }
    is_match_found != 0

  }
}


pub struct BankH40 {
  pub slots: [SlotH40; 65536],
}

pub struct BankH41 {
  pub slots: [SlotH41; 65536],
}

pub struct BankH42 {
  pub slots: [SlotH42; 512],
}


pub struct SlotH40 {
  pub delta: u16,
  pub next: u16,
}
pub struct SlotH41 {
  pub delta: u16,
  pub next: u16,
}

pub struct SlotH42 {
  pub delta: u16,
  pub next: u16,
}

// UNSUPPORTED, for now.
pub struct H40 {
  pub common: Struct1,
  pub addr: [u32; 32768],
  pub head: [u16; 32768],
  pub tiny_hash: [u8; 65536],
  pub banks: [BankH40; 1],
  pub free_slot_idx: [u16; 1],
  pub max_hops: usize,
}


pub struct H41 {
  pub common: Struct1,
  pub addr: [u32; 32768],
  pub head: [u16; 32768],
  pub tiny_hash: [u8; 65536],
  pub banks: [BankH41; 1],
  pub free_slot_idx: [u16; 1],
  pub max_hops: usize,
}

pub struct H42 {
  pub common: Struct1,
  pub addr: [u32; 32768],
  pub head: [u16; 32768],
  pub tiny_hash: [u8; 65536],
  pub banks: [BankH42; 512],
  free_slot_idx: [u16; 512],
  pub max_hops: usize,
}




fn unopt_ctzll(mut val: usize) -> u8 {
  let mut cnt: u8 = 0i32 as (u8);
  while val & 1usize == 0usize {
    val = val >> 1i32;
    cnt = (cnt as (i32) + 1) as (u8);
  }
  cnt
}


fn BackwardReferenceScoreUsingLastDistance(copy_length: usize, h9_opts: H9Opts) -> u64 {
  ((h9_opts.literal_byte_score as u64) >> 2)
    .wrapping_mul(copy_length as u64)
    .wrapping_add((30u64 * 8u64).wrapping_mul(::core::mem::size_of::<u64>() as u64))
    .wrapping_add(15u64)
}


fn BackwardReferenceScore(copy_length: usize, backward_reference_offset: usize, h9_opts: H9Opts) -> u64 {
  (30u64 * 8u64)
    .wrapping_mul(::core::mem::size_of::<u64>() as u64)
    .wrapping_add(((h9_opts.literal_byte_score as usize) >> 2).wrapping_mul(copy_length) as u64)
    .wrapping_sub((30u64).wrapping_mul(Log2FloorNonZero(backward_reference_offset as u64) as u64))
}

fn Hash14(data: &[u8]) -> u32 {
  let h: u32 = BROTLI_UNALIGNED_LOAD32(data).wrapping_mul(kHashMul32);
  h >> 32i32 - 14i32
}

fn TestStaticDictionaryItem(dictionary: &BrotliDictionary,
                            item: usize,
                            data: &[u8],
                            max_length: usize,
                            max_backward: usize,
                            max_distance: usize,
                            h9_opts: H9Opts,
                            out: &mut HasherSearchResult)
                            -> i32 {
  let len: usize;
  let dist: usize;
  let offset: usize;
  let matchlen: usize;
  let backward: usize;
  let score: u64;
  len = item & 0x1fusize;
  dist = item >> 5i32;
  offset = ((*dictionary).offsets_by_length[len] as (usize)).wrapping_add(len.wrapping_mul(dist));
  if len > max_length {
    return 0i32;
  }
  matchlen = FindMatchLengthWithLimit(data, &(*dictionary).data[offset..], len);
  if matchlen.wrapping_add(kCutoffTransformsCount as usize) <= len || matchlen == 0usize {
    return 0i32;
  }
  {
    let cut: u64 = len.wrapping_sub(matchlen) as u64;
    let transform_id: usize =
      (cut << 2i32).wrapping_add(kCutoffTransforms as u64 >> cut.wrapping_mul(6) & 0x3f) as usize;
    backward = max_backward.wrapping_add(dist)
      .wrapping_add(1usize)
      .wrapping_add(transform_id << (*dictionary).size_bits_by_length[len] as (i32));
  }
  if backward > max_distance {
      return 0i32;
  }
  score = BackwardReferenceScore(matchlen, backward, h9_opts);
  if score < (*out).score {
    return 0i32;
  }
  (*out).len = matchlen;
  (*out).len_x_code = len ^ matchlen;
  (*out).distance = backward;
  (*out).score = score;
  1i32
}

fn SearchInStaticDictionary<HasherType: AnyHasher>(dictionary: &BrotliDictionary,
                                                   dictionary_hash: &[u16],
                                                   handle: &mut HasherType,
                                                   data: &[u8],
                                                   max_length: usize,
                                                   max_backward: usize,
                                                   max_distance: usize,
                                                   out: &mut HasherSearchResult,
                                                   shallow: i32)
                                                   -> i32 {
  let mut key: usize;
  let mut i: usize;
  let mut is_match_found: i32 = 0i32;
  let opts = handle.Opts();
  let xself: &mut Struct1 = handle.GetHasherCommon();
  if (*xself).dict_num_matches < (*xself).dict_num_lookups >> 7i32 {
    return 0i32;
  }
  key = (Hash14(data) << 1i32) as (usize); //FIXME: works for any kind of hasher??
  i = 0usize;
  while i < if shallow != 0 { 1u32 } else { 2u32 } as (usize) {
    {
      let item: usize = dictionary_hash[(key as (usize))] as (usize);
      (*xself).dict_num_lookups = (*xself).dict_num_lookups.wrapping_add(1 as (usize));
      if item != 0usize {
        let item_matches: i32 =
          TestStaticDictionaryItem(dictionary, item, data, max_length, max_backward, max_distance, opts, out);
        if item_matches != 0 {
          (*xself).dict_num_matches = (*xself).dict_num_matches.wrapping_add(1 as (usize));
          is_match_found = 1i32;
        }
      }
    }
    i = i.wrapping_add(1 as (usize));
    key = key.wrapping_add(1 as (usize));
  }
  is_match_found
}

impl<Alloc: alloc::Allocator<u16> + alloc::Allocator<u32>> CloneWithAlloc<Alloc> for BasicHasher<H2Sub<Alloc>> {
  fn clone_with_alloc(&self, m: &mut Alloc) -> Self {
      let mut ret = BasicHasher::<H2Sub<Alloc>> {
          GetHasherCommon: self.GetHasherCommon.clone(),
          buckets_: H2Sub::<Alloc>{
              buckets_:<Alloc as Allocator<u32>>::alloc_cell(m, self.buckets_.buckets_.len()),
          },
          h9_opts: self.h9_opts.clone(),
      };
      ret.buckets_.buckets_.slice_mut().clone_from_slice(self.buckets_.buckets_.slice());
      ret
  }    
}
impl<Alloc: alloc::Allocator<u16> + alloc::Allocator<u32>> CloneWithAlloc<Alloc> for BasicHasher<H3Sub<Alloc>> {
  fn clone_with_alloc(&self, m: &mut Alloc) -> Self {
      let mut ret = BasicHasher::<H3Sub<Alloc>> {
          GetHasherCommon: self.GetHasherCommon.clone(),
          buckets_: H3Sub::<Alloc>{
              buckets_:<Alloc as Allocator<u32>>::alloc_cell(m, self.buckets_.buckets_.len()),
          },
          h9_opts: self.h9_opts.clone(),
      };
      ret.buckets_.buckets_.slice_mut().clone_from_slice(self.buckets_.buckets_.slice());
      ret
  }    
}
impl<Alloc: alloc::Allocator<u16> + alloc::Allocator<u32>> CloneWithAlloc<Alloc> for BasicHasher<H4Sub<Alloc>> {
  fn clone_with_alloc(&self, m: &mut Alloc) -> Self {
      let mut ret = BasicHasher::<H4Sub<Alloc>> {
          GetHasherCommon: self.GetHasherCommon.clone(),
          buckets_: H4Sub::<Alloc>{
              buckets_:<Alloc as Allocator<u32>>::alloc_cell(m, self.buckets_.buckets_.len()),
          },
          h9_opts: self.h9_opts.clone(),
      };
      ret.buckets_.buckets_.slice_mut().clone_from_slice(self.buckets_.buckets_.slice());
      ret
  }        
}
impl<Alloc: alloc::Allocator<u16> + alloc::Allocator<u32>> CloneWithAlloc<Alloc> for BasicHasher<H54Sub<Alloc>> {
  fn clone_with_alloc(&self, m: &mut Alloc) -> Self {
      let mut ret = BasicHasher::<H54Sub<Alloc>> {
          GetHasherCommon: self.GetHasherCommon.clone(),
          buckets_: H54Sub::<Alloc>{
              buckets_:<Alloc as Allocator<u32>>::alloc_cell(m, self.buckets_.len()),
          },
          h9_opts: self.h9_opts.clone(),
      };
      ret.buckets_.buckets_.slice_mut().clone_from_slice(self.buckets_.buckets_.slice());
      ret
  }    
}
impl<Alloc: alloc::Allocator<u16> + alloc::Allocator<u32>,
     Special: AdvHashSpecialization+Sized+Clone,> CloneWithAlloc<Alloc> for AdvHasher<Special, Alloc> {
  fn clone_with_alloc(&self, m: &mut Alloc) -> Self {
    let mut num = <Alloc as Allocator<u16>>::alloc_cell(m, self.num.len());
    num.slice_mut().clone_from_slice(self.num.slice());
    let mut buckets = <Alloc as Allocator<u32>>::alloc_cell(m, self.buckets.len());
    buckets.slice_mut().clone_from_slice(self.buckets.slice());
    AdvHasher::<Special, Alloc> {
      GetHasherCommon: self.GetHasherCommon.clone(),
      specialization:self.specialization.clone(),
      num:num,
      buckets:buckets,
      h9_opts: self.h9_opts.clone(),
    }
  }
}

pub enum UnionHasher<Alloc: alloc::Allocator<u16> + alloc::Allocator<u32>> {
  Uninit,
  H2(BasicHasher<H2Sub<Alloc>>),
  H3(BasicHasher<H3Sub<Alloc>>),
  H4(BasicHasher<H4Sub<Alloc>>),
  H54(BasicHasher<H54Sub<Alloc>>),
  H5(AdvHasher<H5Sub, Alloc>),
  H5q7(AdvHasher<HQ7Sub, Alloc>),
  H5q5(AdvHasher<HQ5Sub, Alloc>),
  H6(AdvHasher<H6Sub, Alloc>),
  H9(AdvHasher<H9Sub, Alloc>),
  H10(H10<Alloc, H10Buckets<Alloc>, H10DefaultParams>),
}
impl<Alloc: alloc::Allocator<u16> + alloc::Allocator<u32>> PartialEq<UnionHasher<Alloc>> for UnionHasher<Alloc> {
    fn eq(&self, other: &UnionHasher<Alloc>) -> bool {
        match *self {
            UnionHasher::H2(ref hasher) => match *other {
                UnionHasher::H2(ref otherh) => *hasher == *otherh,
                _ => false,
            },
            UnionHasher::H3(ref hasher) => match *other {
                UnionHasher::H3(ref otherh) => *hasher == *otherh,
                _ => false,
            },
            UnionHasher::H4(ref hasher) => match *other {
                UnionHasher::H4(ref otherh) => *hasher == *otherh,
                _ => false,
            },
            UnionHasher::H54(ref hasher) => match *other {
                UnionHasher::H54(ref otherh) => *hasher == *otherh,
                _ => false,
            },
            UnionHasher::H5(ref hasher) => match *other {
                UnionHasher::H5(ref otherh) => *hasher == *otherh,
                _ => false,
            },
            UnionHasher::H5q7(ref hasher) => match *other {
                UnionHasher::H5q7(ref otherh) => *hasher == *otherh,
                _ => false,
            },
            UnionHasher::H5q5(ref hasher) => match *other {
                UnionHasher::H5q5(ref otherh) => *hasher == *otherh,
                _ => false,
            },
            UnionHasher::H6(ref hasher) => match *other {
                UnionHasher::H6(ref otherh) => *hasher == *otherh,
                _ => false,
            },
            UnionHasher::H9(ref hasher) => match *other {
                UnionHasher::H9(ref otherh) => *hasher == *otherh,
                _ => false,
            },
            UnionHasher::H10(ref hasher) => match *other {
                UnionHasher::H10(ref otherh) => *hasher == *otherh,
                _ => false,
            },
            UnionHasher::Uninit => match *other {
                UnionHasher::Uninit => true,
                _ => false,
            },
        }        
    }
}
impl<Alloc: alloc::Allocator<u16> + alloc::Allocator<u32>> CloneWithAlloc<Alloc> for UnionHasher<Alloc> {
    fn clone_with_alloc(&self, m: &mut Alloc) -> Self {
        match *self {
            UnionHasher::H2(ref hasher) => UnionHasher::H2(hasher.clone_with_alloc(m)),
            UnionHasher::H3(ref hasher) => UnionHasher::H3(hasher.clone_with_alloc(m)),
            UnionHasher::H4(ref hasher) => UnionHasher::H4(hasher.clone_with_alloc(m)),
            UnionHasher::H5(ref hasher) => UnionHasher::H5(hasher.clone_with_alloc(m)),
            UnionHasher::H5q7(ref hasher) => UnionHasher::H5q7(hasher.clone_with_alloc(m)),
            UnionHasher::H5q5(ref hasher) => UnionHasher::H5q5(hasher.clone_with_alloc(m)),
            UnionHasher::H6(ref hasher) => UnionHasher::H6(hasher.clone_with_alloc(m)),
            UnionHasher::H54(ref hasher) => UnionHasher::H54(hasher.clone_with_alloc(m)),
            UnionHasher::H9(ref hasher) => UnionHasher::H9(hasher.clone_with_alloc(m)),
            UnionHasher::H10(ref hasher) => UnionHasher::H10(hasher.clone_with_alloc(m)),
            UnionHasher::Uninit => UnionHasher::Uninit,
        }
    }
}
macro_rules! match_all_hashers_mut {
    ($xself : expr, $func_call : ident, $( $args:expr),*) => {
        match $xself {
     &mut UnionHasher::H2(ref mut hasher) => hasher.$func_call($($args),*),
     &mut UnionHasher::H3(ref mut hasher) => hasher.$func_call($($args),*),
     &mut UnionHasher::H4(ref mut hasher) => hasher.$func_call($($args),*),
     &mut UnionHasher::H5(ref mut hasher) => hasher.$func_call($($args),*),
     &mut UnionHasher::H5q7(ref mut hasher) => hasher.$func_call($($args),*),
     &mut UnionHasher::H5q5(ref mut hasher) => hasher.$func_call($($args),*),
     &mut UnionHasher::H6(ref mut hasher) => hasher.$func_call($($args),*),
     &mut UnionHasher::H54(ref mut hasher) => hasher.$func_call($($args),*),
     &mut UnionHasher::H9(ref mut hasher) => hasher.$func_call($($args),*),
     &mut UnionHasher::H10(ref mut hasher) => hasher.$func_call($($args),*),
     &mut UnionHasher::Uninit => panic!("UNINTIALIZED"),
        }
    };
}
macro_rules! match_all_hashers {
    ($xself : expr, $func_call : ident, $( $args:expr),*) => {
        match $xself {
     &UnionHasher::H2(ref hasher) => hasher.$func_call($($args),*),
     &UnionHasher::H3(ref hasher) => hasher.$func_call($($args),*),
     &UnionHasher::H4(ref hasher) => hasher.$func_call($($args),*),
     &UnionHasher::H5(ref hasher) => hasher.$func_call($($args),*),
     &UnionHasher::H5q7(ref hasher) => hasher.$func_call($($args),*),
     &UnionHasher::H5q5(ref hasher) => hasher.$func_call($($args),*),
     &UnionHasher::H6(ref hasher) => hasher.$func_call($($args),*),
     &UnionHasher::H54(ref hasher) => hasher.$func_call($($args),*),
     &UnionHasher::H9(ref hasher) => hasher.$func_call($($args),*),
     &UnionHasher::H10(ref hasher) => hasher.$func_call($($args),*),
     &UnionHasher::Uninit => panic!("UNINTIALIZED"),
        }
    };
}
impl<Alloc: alloc::Allocator<u16> + alloc::Allocator<u32>> AnyHasher
  for UnionHasher<Alloc> {
  fn Opts(&self) -> H9Opts {
    return match_all_hashers!(self, Opts,);
  }
  fn GetHasherCommon(&mut self) -> &mut Struct1 {
    return match_all_hashers_mut!(self, GetHasherCommon,);
  }/*
  fn GetH10Tree(&mut self) -> Option<&mut H10<AllocU32, H10Buckets, H10DefaultParams>> {
    return match_all_hashers_mut!(self, GetH10Tree,);
  }*/
  fn Prepare(&mut self, one_shot: bool, input_size: usize, data: &[u8]) -> HowPrepared {
    return match_all_hashers_mut!(self, Prepare, one_shot, input_size, data);
  }
  fn HashBytes(&self, data: &[u8]) -> usize {
    return match_all_hashers!(self, HashBytes, data);
  }
  fn HashTypeLength(&self) -> usize {
    return match_all_hashers!(self, HashTypeLength,);
  }
  fn StoreLookahead(&self) -> usize {
    return match_all_hashers!(self, StoreLookahead,);
  }
  fn PrepareDistanceCache(&self, distance_cache: &mut [i32]) {
    return match_all_hashers!(self, PrepareDistanceCache, distance_cache);
  }
  fn StitchToPreviousBlock(&mut self,
                           num_bytes: usize,
                           position: usize,
                           ringbuffer: &[u8],
                           ringbuffer_mask: usize) {
    return match_all_hashers_mut!(self,
                                  StitchToPreviousBlock,
                                  num_bytes,
                                  position,
                                  ringbuffer,
                                  ringbuffer_mask);
  }
  fn FindLongestMatch(&mut self,
                      dictionary: Option<&BrotliDictionary>,
                      dictionary_hash: &[u16],
                      data: &[u8],
                      ring_buffer_mask: usize,
                      distance_cache: &[i32],
                      cur_ix: usize,
                      max_length: usize,
                      max_backward: usize,
                      gap: usize,
                      max_distance: usize,
                      out: &mut HasherSearchResult)
                      -> bool {
    return match_all_hashers_mut!(self,
                                  FindLongestMatch,
                                  dictionary,
                                  dictionary_hash,
                                  data,
                                  ring_buffer_mask,
                                  distance_cache,
                                  cur_ix,
                                  max_length,
                                  max_backward,
                                  gap,
                                  max_distance,
                                  out);
  }
  fn Store(&mut self, data: &[u8], mask: usize, ix: usize) {
    return match_all_hashers_mut!(self, Store, data, mask, ix);
  }
  fn StoreRange(&mut self, data: &[u8], mask: usize, ix_start: usize, ix_end: usize) {
    return match_all_hashers_mut!(self, StoreRange, data, mask, ix_start, ix_end);
  }
  fn BulkStoreRange(&mut self, data: &[u8], mask: usize, ix_start: usize, ix_end: usize) {
    return match_all_hashers_mut!(self, BulkStoreRange, data, mask, ix_start, ix_end);
  }
}

impl<Alloc: alloc::Allocator<u16> + alloc::Allocator<u32>> UnionHasher<Alloc> {
  pub fn free (&mut self, alloc: &mut Alloc) {
    match self {
      &mut UnionHasher::H2(ref mut hasher) => {
        <Alloc as Allocator<u32>>::free_cell(alloc, core::mem::replace(&mut hasher.buckets_.buckets_, <Alloc as Allocator<u32>>::AllocatedMemory::default()));
      }
      &mut UnionHasher::H3(ref mut hasher) => {
        <Alloc as Allocator<u32>>::free_cell(alloc, core::mem::replace(&mut hasher.buckets_.buckets_, <Alloc as Allocator<u32>>::AllocatedMemory::default()));
      }
      &mut UnionHasher::H4(ref mut hasher) => {
        <Alloc as Allocator<u32>>::free_cell(alloc, core::mem::replace(&mut hasher.buckets_.buckets_, <Alloc as Allocator<u32>>::AllocatedMemory::default()));
      }
      &mut UnionHasher::H54(ref mut hasher) => {
        <Alloc as Allocator<u32>>::free_cell(alloc, core::mem::replace(&mut hasher.buckets_.buckets_, <Alloc as Allocator<u32>>::AllocatedMemory::default()));
      }
      &mut UnionHasher::H5q7(ref mut hasher) => {
        <Alloc as Allocator<u16>>::free_cell(alloc, core::mem::replace(&mut hasher.num, <Alloc as Allocator<u16>>::AllocatedMemory::default()));
        <Alloc as Allocator<u32>>::free_cell(alloc, core::mem::replace(&mut hasher.buckets, <Alloc as Allocator<u32>>::AllocatedMemory::default()));
      }
      &mut UnionHasher::H5q5(ref mut hasher) => {
        <Alloc as Allocator<u16>>::free_cell(alloc, core::mem::replace(&mut hasher.num, <Alloc as Allocator<u16>>::AllocatedMemory::default()));
        <Alloc as Allocator<u32>>::free_cell(alloc, core::mem::replace(&mut hasher.buckets, <Alloc as Allocator<u32>>::AllocatedMemory::default()));
      }
      &mut UnionHasher::H5(ref mut hasher) => {
        <Alloc as Allocator<u16>>::free_cell(alloc, core::mem::replace(&mut hasher.num, <Alloc as Allocator<u16>>::AllocatedMemory::default()));
        <Alloc as Allocator<u32>>::free_cell(alloc, core::mem::replace(&mut hasher.buckets, <Alloc as Allocator<u32>>::AllocatedMemory::default()));
      }
      &mut UnionHasher::H6(ref mut hasher) => {
        <Alloc as Allocator<u16>>::free_cell(alloc, core::mem::replace(&mut hasher.num, <Alloc as Allocator<u16>>::AllocatedMemory::default()));
        <Alloc as Allocator<u32>>::free_cell(alloc, core::mem::replace(&mut hasher.buckets, <Alloc as Allocator<u32>>::AllocatedMemory::default()));
      }
      &mut UnionHasher::H9(ref mut hasher) => {
        <Alloc as Allocator<u16>>::free_cell(alloc,core::mem::replace(&mut hasher.num, <Alloc as Allocator<u16>>::AllocatedMemory::default()));
        <Alloc as Allocator<u32>>::free_cell(alloc, core::mem::replace(&mut hasher.buckets, <Alloc as Allocator<u32>>::AllocatedMemory::default()));
      }
      &mut UnionHasher::H10(ref mut hasher) => {
        hasher.free(alloc);
      }
      &mut UnionHasher::Uninit => {}
    }
    *self = UnionHasher::<Alloc>::default();
  }
}


impl<Alloc: alloc::Allocator<u16> + alloc::Allocator<u32>> Default
  for UnionHasher<Alloc> {
  fn default() -> Self {
    UnionHasher::Uninit
  }
}

/*UnionHasher::H2(BasicHasher {
          GetHasherCommon:Struct1{params:BrotliHasherParams{
           type_:2,
           block_bits: 8,
           bucket_bits:16,
           hash_len: 4,
           num_last_distances_to_check:0},
          is_prepared_:0,
          dict_num_lookups:0,
          dict_num_matches:0,
          },
          buckets_:H2Sub{
          buckets_:[0;65537],
          },
          })
          */
fn CreateBackwardReferences<AH: AnyHasher>(dictionary: Option<&BrotliDictionary>,
                                           dictionary_hash: &[u16],
                                           num_bytes: usize,
                                           mut position: usize,
                                           ringbuffer: &[u8],
                                           ringbuffer_mask: usize,
                                           params: &BrotliEncoderParams,
                                           hasher: &mut AH,
                                           dist_cache: &mut [i32],
                                           last_insert_len: &mut usize,
                                           mut commands: &mut [Command],
                                           num_commands: &mut usize,
                                           num_literals: &mut usize) {
  let gap = 0usize;
  let max_backward_limit: usize = (1usize << (*params).lgwin).wrapping_sub(16usize);
  let mut new_commands_count: usize = 0;
  let mut insert_length: usize = *last_insert_len;
  let pos_end: usize = position.wrapping_add(num_bytes);
  let store_end: usize = if num_bytes >= hasher.StoreLookahead() {
    position.wrapping_add(num_bytes).wrapping_sub(hasher.StoreLookahead()).wrapping_add(1usize)
  } else {
    position
  };
  let random_heuristics_window_size: usize = LiteralSpreeLengthForSparseSearch(params);
  let mut apply_random_heuristics: usize = position.wrapping_add(random_heuristics_window_size);
  let kMinScore: u64 = (30u64 * 8)
    .wrapping_mul(::core::mem::size_of::<u64>() as u64)
    .wrapping_add(100u64);
  hasher.PrepareDistanceCache(dist_cache);
  while position.wrapping_add(hasher.HashTypeLength()) < pos_end {
    let mut max_length: usize = pos_end.wrapping_sub(position);
    let mut max_distance: usize = brotli_min_size_t(position, max_backward_limit);
    let mut sr = HasherSearchResult {
      len: 0,
      len_x_code: 0,
      distance: 0,
      score: 0,
    };
    sr.len = 0usize;
    sr.len_x_code = 0usize;
    sr.distance = 0usize;
    sr.score = kMinScore;
    if hasher.FindLongestMatch(dictionary,
                               dictionary_hash,
                               ringbuffer,
                               ringbuffer_mask,
                               dist_cache,
                               position,
                               max_length,
                               max_distance,
                               gap,
                               params.dist.max_distance,
                               &mut sr) {
      let mut delayed_backward_references_in_row: i32 = 0i32;
      max_length = max_length.wrapping_sub(1 as (usize));
      'break6: loop {
        'continue7: loop {
          let cost_diff_lazy: u64 = 175;
          let is_match_found: bool;
          let mut sr2 = HasherSearchResult {
            len: 0,
            len_x_code: 0,
            distance: 0,
            score: 0,
          };
          sr2.len = if (*params).quality < 5 {
            brotli_min_size_t(sr.len.wrapping_sub(1usize), max_length)
          } else {
            0usize
          };
          sr2.len_x_code = 0usize;
          sr2.distance = 0usize;
          sr2.score = kMinScore;
          max_distance = brotli_min_size_t(position.wrapping_add(1usize), max_backward_limit);
          is_match_found = hasher.FindLongestMatch(dictionary,
                                                   dictionary_hash,
                                                   ringbuffer,
                                                   ringbuffer_mask,
                                                   dist_cache,
                                                   position.wrapping_add(1usize),
                                                   max_length,
                                                   max_distance,
                                                   gap,
                                                   params.dist.max_distance,
                                                   &mut sr2);
          if is_match_found && (sr2.score >= sr.score.wrapping_add(cost_diff_lazy)) {
            position = position.wrapping_add(1 as (usize));
            insert_length = insert_length.wrapping_add(1 as (usize));
            sr = sr2;
            if {
                 delayed_backward_references_in_row = delayed_backward_references_in_row + 1;
                 delayed_backward_references_in_row
               } < 4i32 &&
               (position.wrapping_add(hasher.HashTypeLength()) < pos_end) {
              {
                break 'continue7;
              }
            }
          }
          break 'break6;
        }
        max_length = max_length.wrapping_sub(1 as (usize));
      }
      apply_random_heuristics = position.wrapping_add((2usize).wrapping_mul(sr.len))
        .wrapping_add(random_heuristics_window_size);
      max_distance = brotli_min_size_t(position, max_backward_limit);
      {
        let distance_code: usize = ComputeDistanceCode(sr.distance, max_distance, dist_cache);
        if sr.distance <= max_distance && (distance_code > 0usize) {
          dist_cache[(3usize)] = dist_cache[(2usize)];
          dist_cache[(2usize)] = dist_cache[(1usize)];
          dist_cache[(1usize)] = dist_cache[(0usize)];
          dist_cache[(0usize)] = sr.distance as (i32);
          hasher.PrepareDistanceCache(dist_cache);
        }
        new_commands_count += 1;
        InitCommand({
                      let (mut _old, new_commands) = core::mem::replace(&mut commands, &mut []).split_at_mut(1);
                      commands = new_commands;
                      &mut _old[0]
                    },
                    &params.dist,
                    insert_length,
                    sr.len,
                    sr.len ^ sr.len_x_code,
                    distance_code);
      }
      *num_literals = (*num_literals).wrapping_add(insert_length);
      insert_length = 0usize;
      hasher.StoreRange(ringbuffer,
                        ringbuffer_mask,
                        position.wrapping_add(2usize),
                        brotli_min_size_t(position.wrapping_add(sr.len), store_end));
      position = position.wrapping_add(sr.len);
    } else {
      insert_length = insert_length.wrapping_add(1 as (usize));
      position = position.wrapping_add(1 as (usize));

      if position > apply_random_heuristics {
        let kMargin: usize = brotli_max_size_t(hasher.StoreLookahead().wrapping_sub(1usize),
                                               4usize);
        if position.wrapping_add(16usize) >= pos_end.wrapping_sub(kMargin) {
          insert_length = insert_length.wrapping_add(pos_end - position);
          position = pos_end;
        } else if position >
           apply_random_heuristics.wrapping_add((4usize)
                                                  .wrapping_mul(random_heuristics_window_size)) {
          hasher.Store4Vec4(ringbuffer, ringbuffer_mask, position);
          insert_length = insert_length.wrapping_add(16usize);
          position = position.wrapping_add(16usize);
        } else {
          hasher.StoreEvenVec4(ringbuffer, ringbuffer_mask, position);
          insert_length = insert_length.wrapping_add(8usize);
          position = position.wrapping_add(8usize);
        }
      }
    }
  }
  insert_length = insert_length.wrapping_add(pos_end.wrapping_sub(position));
  *last_insert_len = insert_length;
  *num_commands = (*num_commands).wrapping_add(new_commands_count);
}
pub fn BrotliCreateBackwardReferences<Alloc: alloc::Allocator<u16> + alloc::Allocator<u32> + alloc::Allocator<u64> + alloc::Allocator<floatX> + alloc::Allocator<ZopfliNode>>
  (alloc : &mut Alloc,
   dictionary: &BrotliDictionary,
   num_bytes: usize,
   position: usize,
   ringbuffer: &[u8],
   ringbuffer_mask: usize,
   params: &BrotliEncoderParams,
   hasher_union: &mut UnionHasher<Alloc>,
   dist_cache: &mut [i32],
   last_insert_len: &mut usize,
   commands: &mut [Command],
   num_commands: &mut usize,
   num_literals: &mut usize) {
  match (hasher_union) {
    &mut UnionHasher::Uninit => panic!("working with uninitialized hash map"),
      &mut UnionHasher::H10(ref mut hasher) => {
          if params.quality >= 11 {
              super::backward_references_hq::BrotliCreateHqZopfliBackwardReferences(
                  alloc, if params.use_dictionary {Some(dictionary)} else {None},
                  num_bytes,
                  position,
                  ringbuffer,
                  ringbuffer_mask,
                  params,
                  hasher,
                  dist_cache,
                  last_insert_len,
                  commands,
                  num_commands,
                  num_literals)
          } else {
              super::backward_references_hq::BrotliCreateZopfliBackwardReferences(
                  alloc,
                  if params.use_dictionary {Some(dictionary)} else {None},
                  num_bytes,
                  position,
                  ringbuffer,
                  ringbuffer_mask,
                  params,
                  hasher,
                  dist_cache,
                  last_insert_len,
                  commands,
                  num_commands,
                  num_literals)
          }
    }
    &mut UnionHasher::H2(ref mut hasher) => {
      CreateBackwardReferences(if params.use_dictionary {Some(dictionary)} else {None},
                               &kStaticDictionaryHash[..],
                               num_bytes,
                               position,
                               ringbuffer,
                               ringbuffer_mask,
                               params,
                               hasher,
                               dist_cache,
                               last_insert_len,
                               commands,
                               num_commands,
                               num_literals)
    }
    &mut UnionHasher::H3(ref mut hasher) => {
      CreateBackwardReferences(if params.use_dictionary {Some(dictionary)} else {None},
                               &kStaticDictionaryHash[..],
                               num_bytes,
                               position,
                               ringbuffer,
                               ringbuffer_mask,
                               params,
                               hasher,
                               dist_cache,
                               last_insert_len,
                               commands,
                               num_commands,
                               num_literals)
    }
    &mut UnionHasher::H4(ref mut hasher) => {
      CreateBackwardReferences(if params.use_dictionary {Some(dictionary)} else {None},
                               &kStaticDictionaryHash[..],
                               num_bytes,
                               position,
                               ringbuffer,
                               ringbuffer_mask,
                               params,
                               hasher,
                               dist_cache,
                               last_insert_len,
                               commands,
                               num_commands,
                               num_literals)
    }
    &mut UnionHasher::H5(ref mut hasher) => {
      CreateBackwardReferences(if params.use_dictionary {Some(dictionary)} else {None},
                               &kStaticDictionaryHash[..],
                               num_bytes,
                               position,
                               ringbuffer,
                               ringbuffer_mask,
                               params,
                               hasher,
                               dist_cache,
                               last_insert_len,
                               commands,
                               num_commands,
                               num_literals)
    }
    &mut UnionHasher::H5q7(ref mut hasher) => {
      CreateBackwardReferences(if params.use_dictionary {Some(dictionary)} else {None},
                               &kStaticDictionaryHash[..],
                               num_bytes,
                               position,
                               ringbuffer,
                               ringbuffer_mask,
                               params,
                               hasher,
                               dist_cache,
                               last_insert_len,
                               commands,
                               num_commands,
                               num_literals)
    }
    &mut UnionHasher::H5q5(ref mut hasher) => {
      CreateBackwardReferences(if params.use_dictionary {Some(dictionary)} else {None},
                               &kStaticDictionaryHash[..],
                               num_bytes,
                               position,
                               ringbuffer,
                               ringbuffer_mask,
                               params,
                               hasher,
                               dist_cache,
                               last_insert_len,
                               commands,
                               num_commands,
                               num_literals)
    }
    &mut UnionHasher::H6(ref mut hasher) => {
      CreateBackwardReferences(if params.use_dictionary {Some(dictionary)} else {None},
                               &kStaticDictionaryHash[..],
                               num_bytes,
                               position,
                               ringbuffer,
                               ringbuffer_mask,
                               params,
                               hasher,
                               dist_cache,
                               last_insert_len,
                               commands,
                               num_commands,
                               num_literals)
    }
    &mut UnionHasher::H9(ref mut hasher) => {
      CreateBackwardReferences(if params.use_dictionary {Some(dictionary)} else {None},
                               &kStaticDictionaryHash[..],
                               num_bytes,
                               position,
                               ringbuffer,
                               ringbuffer_mask,
                               params,
                               hasher,
                               dist_cache,
                               last_insert_len,
                               commands,
                               num_commands,
                               num_literals)
    }
    &mut UnionHasher::H54(ref mut hasher) => {
      CreateBackwardReferences(if params.use_dictionary {Some(dictionary)} else {None},
                               &kStaticDictionaryHash[..],
                               num_bytes,
                               position,
                               ringbuffer,
                               ringbuffer_mask,
                               params,
                               hasher,
                               dist_cache,
                               last_insert_len,
                               commands,
                               num_commands,
                               num_literals)
    }
  }
}