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
#![allow(unused_imports)]

use alloc::vec::Vec;
use alloc::{format, vec};

use crate::bitstream::BitStreamReader;
use crate::constants::{
    DEFLATE_BLOCKTYPE_DYNAMIC_HUFFMAN, DEFLATE_BLOCKTYPE_RESERVED, DEFLATE_BLOCKTYPE_STATIC,
    DEFLATE_BLOCKTYPE_UNCOMPRESSED, DEFLATE_MAX_CODEWORD_LENGTH,
    DEFLATE_MAX_LITLEN_CODEWORD_LENGTH, DEFLATE_MAX_NUM_SYMS, DEFLATE_MAX_OFFSET_CODEWORD_LENGTH,
    DEFLATE_MAX_PRE_CODEWORD_LEN, DEFLATE_NUM_LITLEN_SYMS, DEFLATE_NUM_OFFSET_SYMS,
    DEFLATE_NUM_PRECODE_SYMS, DEFLATE_PRECODE_LENS_PERMUTATION, DELFATE_MAX_LENS_OVERRUN,
    FASTCOPY_BYTES, FASTLOOP_MAX_BYTES_WRITTEN, HUFFDEC_END_OF_BLOCK, HUFFDEC_EXCEPTIONAL,
    HUFFDEC_LITERAL, HUFFDEC_SUITABLE_POINTER, LITLEN_DECODE_BITS, LITLEN_DECODE_RESULTS,
    LITLEN_ENOUGH, LITLEN_TABLE_BITS, OFFSET_DECODE_RESULTS, OFFSET_ENOUGH, OFFSET_TABLEBITS,
    PRECODE_DECODE_RESULTS, PRECODE_ENOUGH, PRECODE_TABLE_BITS
};
use crate::errors::{DecodeErrorStatus, InflateDecodeErrors};
#[cfg(feature = "gzip")]
use crate::gzip_constants::{
    GZIP_CM_DEFLATE, GZIP_FCOMMENT, GZIP_FEXTRA, GZIP_FHCRC, GZIP_FNAME, GZIP_FOOTER_SIZE,
    GZIP_FRESERVED, GZIP_ID1, GZIP_ID2
};
use crate::utils::{copy_rep_matches, fixed_copy_within, make_decode_table_entry};

struct DeflateHeaderTables
{
    litlen_decode_table: [u32; LITLEN_ENOUGH],
    offset_decode_table: [u32; OFFSET_ENOUGH]
}

impl Default for DeflateHeaderTables
{
    fn default() -> Self
    {
        DeflateHeaderTables {
            litlen_decode_table: [0; LITLEN_ENOUGH],
            offset_decode_table: [0; OFFSET_ENOUGH]
        }
    }
}

/// Options that can influence decompression
/// in Deflate/Zlib/Gzip
///
/// To use them, pass a customized options to
/// the deflate decoder.
#[derive(Copy, Clone)]
pub struct DeflateOptions
{
    limit:            usize,
    confirm_checksum: bool,
    size_hint:        usize
}

impl Default for DeflateOptions
{
    fn default() -> Self
    {
        DeflateOptions {
            limit:            1 << 30,
            confirm_checksum: true,
            size_hint:        37000
        }
    }
}

impl DeflateOptions
{
    /// Get deflate/zlib limit option
    ///
    /// The decoder won't extend the inbuilt limit and will
    /// return an error if the limit is exceeded
    ///
    /// # Returns
    ///  The currently set limit of the instance
    /// # Note
    /// This is provided as a best effort, correctly quiting
    /// is detrimental to speed and hence this should not be relied too much.
    pub const fn get_limit(&self) -> usize
    {
        self.limit
    }
    /// Set a limit to the internal vector
    /// used to store decoded zlib/deflate output.
    ///
    /// # Arguments
    /// limit: The new decompressor limit
    /// # Returns
    /// A modified version of DeflateDecoder
    ///
    /// # Note
    /// This is provided as a best effort, correctly quiting
    /// is detrimental to speed and hence this should not be relied too much
    #[must_use]
    pub fn set_limit(mut self, limit: usize) -> Self
    {
        self.limit = limit;
        self
    }

    /// Get whether the decoder will confirm a checksum
    /// after decoding
    pub const fn get_confirm_checksum(&self) -> bool
    {
        self.confirm_checksum
    }
    /// Set whether the decoder should confirm a checksum
    /// after decoding
    ///
    /// Note, you should definitely confirm your checksum, use
    /// this with caution, otherwise data returned may be corrupt
    ///
    /// # Arguments
    /// - yes: When true, the decoder will confirm checksum
    /// when false, the decoder will skip checksum verification
    /// # Notes
    /// This does not have an influence for deflate decoding as
    /// it does not have a checksum
    pub fn set_confirm_checksum(mut self, yes: bool) -> Self
    {
        self.confirm_checksum = yes;
        self
    }

    /// Get the default set size hint for the decompressor
    ///
    /// The decompressor initializes the internal storage for decompressed bytes
    /// with this size and will reallocate the vec if the decompressed size becomes bigger
    /// than this, but when the user currently knows how big the output will be, can be used
    /// to prevent unnecessary re-allocations
    pub const fn get_size_hint(&self) -> usize
    {
        self.size_hint
    }
    /// Set the size hint for the decompressor
    ///
    /// This can be used to prevent multiple re-allocations
    #[must_use]
    pub const fn set_size_hint(mut self, hint: usize) -> Self
    {
        self.size_hint = hint;
        self
    }
}

/// A deflate decoder instance.
///
/// The decoder manages output buffer as opposed to requiring the caller to provide a pre-allocated buffer
/// it tracks number of bytes written and on successfully reaching the
/// end of the block, will return a vector with exactly
/// the number of decompressed bytes.
///
/// This means that it may use up huge amounts of memory if not checked, but
/// there are [options] that can prevent that
///
/// [options]: DeflateOptions
pub struct DeflateDecoder<'a>
{
    data:                  &'a [u8],
    position:              usize,
    stream:                BitStreamReader<'a>,
    is_last_block:         bool,
    static_codes_loaded:   bool,
    deflate_header_tables: DeflateHeaderTables,
    options:               DeflateOptions
}

impl<'a> DeflateDecoder<'a>
{
    /// Create a new decompressor that will read compressed
    /// data from `data` and return a new vector containing new data
    ///
    /// # Arguments
    /// - `data`: The compressed data. Data can be of any type
    /// gzip,zlib or raw deflate.
    ///
    /// # Returns
    /// A decoder instance which will pull compressed data from `data` to inflate the output output
    ///
    ///  # Note
    ///
    /// The default output size limit is **1 GiB.**
    /// this is to protect the end user against ddos attacks as deflate does not specify it's
    /// output size upfront
    ///
    /// The checksum will be verified depending on the called function.
    /// this only works for zlib and gzip since deflate does not have a checksum
    ///
    /// These defaults can be overridden via [new_with_options()](Self::new_with_options).
    pub fn new(data: &'a [u8]) -> DeflateDecoder<'a>
    {
        let options = DeflateOptions::default();

        Self::new_with_options(data, options)
    }
    /// Create new decoder with specified options
    ///
    /// This can be used to fine tune the decoder to the user's
    /// needs.
    ///
    ///
    /// # Arguments
    /// - `data`: The compressed data. Data can be of any format i.e
    /// gzip, zlib or raw deflate.
    /// - `options` : A set of user defined options which tune how the decompressor
    ///
    ///  # Returns
    /// A decoder instance which will pull compressed data from `data` to inflate output
    ///
    /// # Example
    /// ```no_run
    /// use zune_inflate::{DeflateDecoder, DeflateOptions};
    /// let data  = [37];
    /// let options = DeflateOptions::default()
    ///     .set_confirm_checksum(true) // confirm the checksum for zlib and gzip
    ///     .set_limit(1000); // how big I think the input will be    
    /// let mut decoder = DeflateDecoder::new_with_options(&data,options);
    /// // do some stuff and then call decode
    /// let data = decoder.decode_zlib();
    ///
    /// ```
    pub fn new_with_options(data: &'a [u8], options: DeflateOptions) -> DeflateDecoder<'a>
    {
        // create stream
        DeflateDecoder {
            data,
            position: 0,
            stream: BitStreamReader::new(data),
            is_last_block: false,
            static_codes_loaded: false,
            deflate_header_tables: DeflateHeaderTables::default(),
            options
        }
    }
    /// Decode zlib-encoded data returning the uncompressed in a `Vec<u8>`
    /// or an error if something went wrong.
    ///
    /// Bytes consumed will be from the data passed when the
    /// `new` method was called.
    ///
    /// # Arguments
    /// - None
    /// # Returns
    /// Result type containing the decoded data.
    ///
    /// - `Ok(Vec<u8>)`: Decoded vector containing the uncompressed bytes
    /// - `Err(InflateDecodeErrors)`: Error that occurred during decoding
    ///
    /// It's possible to recover bytes even after an error occurred, bytes up
    /// to when error was encountered are stored in [InflateDecodeErrors]
    ///
    ///
    /// # Note
    /// This needs the `zlib` feature enabled to be available otherwise it's a
    /// compile time error
    ///
    /// [InflateDecodeErrors]:crate::errors::InflateDecodeErrors
    ///
    #[cfg(feature = "zlib")]
    pub fn decode_zlib(&mut self) -> Result<Vec<u8>, InflateDecodeErrors>
    {
        use crate::utils::calc_adler_hash;

        if self.data.len()
            < 2 /* zlib header */
            + 4
        /* Deflate */
        {
            return Err(InflateDecodeErrors::new_with_error(
                DecodeErrorStatus::InsufficientData
            ));
        }

        // Zlib flags
        // See https://www.ietf.org/rfc/rfc1950.txt for
        // the RFC
        let cmf = self.data[0];
        let flg = self.data[1];

        let cm = cmf & 0xF;
        let cinfo = cmf >> 4;

        // let fcheck = flg & 0xF;
        // let fdict = (flg >> 4) & 1;
        // let flevel = flg >> 5;

        // confirm we have the right deflate methods
        if cm != 8
        {
            if cm == 15
            {
                return Err(InflateDecodeErrors::new_with_error(DecodeErrorStatus::Generic(
                    "CM of 15 is preserved by the standard,currently don't know how to handle it"
                )));
            }
            return Err(InflateDecodeErrors::new_with_error(
                DecodeErrorStatus::GenericStr(format!("Unknown zlib compression method {cm}"))
            ));
        }
        if cinfo > 7
        {
            return Err(InflateDecodeErrors::new_with_error(
                DecodeErrorStatus::GenericStr(format!(
                    "Unknown cinfo `{cinfo}` greater than 7, not allowed"
                ))
            ));
        }
        let flag_checks = (u16::from(cmf) * 256) + u16::from(flg);

        if flag_checks % 31 != 0
        {
            return Err(InflateDecodeErrors::new_with_error(
                DecodeErrorStatus::Generic("FCHECK integrity not preserved")
            ));
        }

        self.position = 2;

        let data = self.decode_deflate()?;

        if self.options.confirm_checksum
        {
            // Get number of consumed bytes from the input
            let out_pos = self.stream.get_position() + self.position + self.stream.over_read;

            // read adler
            if let Some(adler) = self.data.get(out_pos..out_pos + 4)
            {
                let adler_bits: [u8; 4] = adler.try_into().unwrap();

                let adler32_expected = u32::from_be_bytes(adler_bits);

                let adler32_found = calc_adler_hash(&data);

                if adler32_expected != adler32_found
                {
                    let err_msg =
                        DecodeErrorStatus::MismatchedAdler(adler32_expected, adler32_found);
                    let err = InflateDecodeErrors::new(err_msg, data);

                    return Err(err);
                }
            }
            else
            {
                let err = InflateDecodeErrors::new(DecodeErrorStatus::InsufficientData, data);

                return Err(err);
            }
        }

        Ok(data)
    }

    /// Decode a gzip encoded data and return the uncompressed data in a
    /// `Vec<u8>` or an error if something went wrong
    ///
    /// Bytes consumed will be from the data passed when the
    /// `new` method was called.
    ///
    /// # Arguments
    /// - None
    /// # Returns
    /// Result type containing the decoded data.
    ///
    /// - `Ok(Vec<u8>)`: Decoded vector containing the uncompressed bytes
    /// - `Err(InflateDecodeErrors)`: Error that occurred during decoding
    ///
    /// It's possible to recover bytes even after an error occurred, bytes up
    /// to when error was encountered are stored in [InflateDecodeErrors]
    ///
    /// # Note
    /// This needs the `gzip` feature enabled to be available, otherwise it's a
    /// compile time error
    ///
    /// [InflateDecodeErrors]:crate::errors::InflateDecodeErrors
    ///
    #[cfg(feature = "gzip")]
    pub fn decode_gzip(&mut self) -> Result<Vec<u8>, InflateDecodeErrors>
    {
        if self.data.len() < 18
        {
            return Err(InflateDecodeErrors::new_with_error(
                DecodeErrorStatus::InsufficientData
            ));
        }

        if self.data[self.position] != GZIP_ID1
        {
            return Err(InflateDecodeErrors::new_with_error(
                DecodeErrorStatus::CorruptData
            ));
        }
        self.position += 1;
        if self.data[self.position] != GZIP_ID2
        {
            return Err(InflateDecodeErrors::new_with_error(
                DecodeErrorStatus::CorruptData
            ));
        }
        self.position += 1;

        if self.data[self.position] != GZIP_CM_DEFLATE
        {
            return Err(InflateDecodeErrors::new_with_error(
                DecodeErrorStatus::CorruptData
            ));
        }
        self.position += 1;

        let flg = self.data[self.position];
        self.position += 1;

        // skip mtime
        self.position += 4;
        // skip xfl
        self.position += 1;
        // skip os
        self.position += 1;

        if (flg & GZIP_FRESERVED) != 0
        {
            return Err(InflateDecodeErrors::new_with_error(
                DecodeErrorStatus::CorruptData
            ));
        }
        // extra field
        if (flg & GZIP_FEXTRA) != 0
        {
            let len_bytes = self.data[self.position..self.position + 2]
                .try_into()
                .unwrap();
            let xlen = usize::from(u16::from_le_bytes(len_bytes));

            self.position += 2;

            if self.data.len().saturating_sub(self.position) < xlen + GZIP_FOOTER_SIZE
            {
                return Err(InflateDecodeErrors::new_with_error(
                    DecodeErrorStatus::CorruptData
                ));
            }
            self.position += xlen;
        }
        // original file name zero terminated
        if (flg & GZIP_FNAME) != 0
        {
            loop
            {
                if let Some(byte) = self.data.get(self.position)
                {
                    self.position += 1;

                    if *byte == 0
                    {
                        break;
                    }
                }
                else
                {
                    return Err(InflateDecodeErrors::new_with_error(
                        DecodeErrorStatus::InsufficientData
                    ));
                }
            }
        }
        // File comment zero terminated
        if (flg & GZIP_FCOMMENT) != 0
        {
            loop
            {
                if let Some(byte) = self.data.get(self.position)
                {
                    self.position += 1;

                    if *byte == 0
                    {
                        break;
                    }
                }
                else
                {
                    return Err(InflateDecodeErrors::new_with_error(
                        DecodeErrorStatus::InsufficientData
                    ));
                }
            }
        }
        // crc16 for gzip header
        if (flg & GZIP_FHCRC) != 0
        {
            self.position += 2;
        }

        if self.position + GZIP_FOOTER_SIZE > self.data.len()
        {
            return Err(InflateDecodeErrors::new_with_error(
                DecodeErrorStatus::InsufficientData
            ));
        }

        let data = self.decode_deflate()?;

        let mut out_pos = self.stream.get_position() + self.position + self.stream.over_read;

        if self.options.confirm_checksum
        {
            // Get number of consumed bytes from the input

            if let Some(crc) = self.data.get(out_pos..out_pos + 4)
            {
                let crc_bits: [u8; 4] = crc.try_into().unwrap();

                let crc32_expected = u32::from_le_bytes(crc_bits);

                let crc32_found = !crate::crc::crc32(&data, !0);

                if crc32_expected != crc32_found
                {
                    let err_msg = DecodeErrorStatus::MismatchedCRC(crc32_expected, crc32_found);
                    let err = InflateDecodeErrors::new(err_msg, data);

                    return Err(err);
                }
            }
            else
            {
                let err = InflateDecodeErrors::new(DecodeErrorStatus::InsufficientData, data);

                return Err(err);
            }
        }
        //checksum
        out_pos += 4;

        if let Some(val) = self.data.get(out_pos..out_pos + 4)
        {
            let actual_bytes: [u8; 4] = val.try_into().unwrap();
            let ac = u32::from_le_bytes(actual_bytes) as usize;

            if data.len() != ac
            {
                let err = DecodeErrorStatus::Generic("ISIZE does not match actual bytes");

                let err = InflateDecodeErrors::new(err, data);

                return Err(err);
            }
        }
        else
        {
            let err = InflateDecodeErrors::new(DecodeErrorStatus::InsufficientData, data);

            return Err(err);
        }

        Ok(data)
    }
    /// Decode a deflate stream returning the data as `Vec<u8>` or an error
    /// indicating what went wrong.
    /// # Arguments
    /// - None
    /// # Returns
    /// Result type containing the decoded data.
    ///
    /// - `Ok(Vec<u8>)`: Decoded vector containing the uncompressed bytes
    /// - `Err(InflateDecodeErrors)`: Error that occurred during decoding
    ///
    /// It's possible to recover bytes even after an error occurred, bytes up
    /// to when error was encountered are stored in [InflateDecodeErrors]
    ///
    ///
    /// # Example
    /// ```no_run
    /// let data = [42]; // answer to life, the universe and everything
    ///
    /// let mut decoder = zune_inflate::DeflateDecoder::new(&data);
    /// let bytes = decoder.decode_deflate().unwrap();
    /// ```
    ///
    ///  [InflateDecodeErrors]:crate::errors::InflateDecodeErrors
    pub fn decode_deflate(&mut self) -> Result<Vec<u8>, InflateDecodeErrors>
    {
        self.start_deflate_block()
    }
    /// Main inner loop for decompressing deflate data
    #[allow(unused_assignments)]
    fn start_deflate_block(&mut self) -> Result<Vec<u8>, InflateDecodeErrors>
    {
        // start deflate decode
        // re-read the stream so that we can remove code read by zlib
        self.stream = BitStreamReader::new(&self.data[self.position..]);

        self.stream.refill();

        // Output space for our decoded bytes.
        let mut out_block = vec![0; self.options.size_hint];
        // bits used

        let mut src_offset = 0;
        let mut dest_offset = 0;

        loop
        {
            self.stream.refill();

            self.is_last_block = self.stream.get_bits(1) == 1;
            let block_type = self.stream.get_bits(2);

            if block_type == DEFLATE_BLOCKTYPE_UNCOMPRESSED
            {
                /*
                 * Uncompressed block: copy 'len' bytes literally from the input
                 * buffer to the output buffer.
                 */
                /*
                 * The RFC says that
                 * skip any remaining bits in current partially
                 *       processed byte
                 *     read LEN and NLEN (see next section)
                 *     copy LEN bytes of data to output
                 */

                if self.stream.over_read > usize::from(self.stream.get_bits_left() >> 3)
                {
                    out_block.truncate(dest_offset);

                    let err_msg = DecodeErrorStatus::Generic("over-read stream");
                    let error = InflateDecodeErrors::new(err_msg, out_block);

                    return Err(error);
                }
                let partial_bits = self.stream.get_bits_left() & 7;

                self.stream.drop_bits(partial_bits);

                let len = self.stream.get_bits(16) as u16;
                let nlen = self.stream.get_bits(16) as u16;

                // copy to deflate
                if len != !nlen
                {
                    out_block.truncate(dest_offset);

                    let err_msg = DecodeErrorStatus::Generic("Len and nlen do not match");
                    let error = InflateDecodeErrors::new(err_msg, out_block);

                    return Err(error);
                }
                let len = len as usize;

                let start = self.stream.get_position() + self.position + self.stream.over_read;

                // ensure there is enough space for a fast copy
                if dest_offset + len + FASTCOPY_BYTES > out_block.len()
                {
                    // and if there is not, resize
                    let new_len = out_block.len() + RESIZE_BY + len;

                    out_block.resize(new_len, 0);
                }

                if self.data.get((start + len).saturating_sub(1)).is_none()
                {
                    out_block.truncate(dest_offset);

                    let err_msg = DecodeErrorStatus::CorruptData;
                    let error = InflateDecodeErrors::new(err_msg, out_block);

                    return Err(error);
                }
                if dest_offset > self.options.limit
                {
                    out_block.truncate(dest_offset);

                    let err_msg =
                        DecodeErrorStatus::OutputLimitExceeded(self.options.limit, out_block.len());
                    let error = InflateDecodeErrors::new(err_msg, out_block);

                    return Err(error);
                }

                out_block[dest_offset..dest_offset + len]
                    .copy_from_slice(&self.data[start..start + len]);

                dest_offset += len;

                // get the new position to write.
                self.stream.position =
                    len + (self.stream.position - usize::from(self.stream.bits_left >> 3));

                self.stream.reset();

                if self.is_last_block
                {
                    break;
                }

                continue;
            }
            else if block_type == DEFLATE_BLOCKTYPE_RESERVED
            {
                out_block.truncate(dest_offset);

                let err_msg = DecodeErrorStatus::Generic("Reserved block type 0b11 encountered");
                let error = InflateDecodeErrors::new(err_msg, out_block);

                return Err(error);
            }

            // build decode tables for static and dynamic tables
            match self.build_decode_table(block_type)
            {
                Ok(_) => (),
                Err(value) =>
                {
                    out_block.truncate(dest_offset);

                    let err_msg = value;
                    let error = InflateDecodeErrors::new(err_msg, out_block);

                    return Err(error);
                }
            };

            // Tables are mutated into the struct, so at this point we know the tables
            // are loaded, take a reference to them
            let litlen_decode_table = &self.deflate_header_tables.litlen_decode_table;
            let offset_decode_table = &self.deflate_header_tables.offset_decode_table;

            /*
             * This is the "fast loop" for decoding literals and matches.  It does
             * bounds checks on in_next and out_next in the loop conditions so that
             * additional bounds checks aren't needed inside the loop body.
             *
             * To reduce latency, the bit-buffer is refilled and the next litlen
             * decode table entry is preloaded before each loop iteration.
             */
            let (mut literal, mut length, mut offset, mut entry) = (0, 0, 0, 0);

            let mut saved_bitbuf;

            'decode: loop
            {
                let close_src = 3 * FASTCOPY_BYTES < self.stream.remaining_bytes();

                if close_src
                {
                    self.stream.refill_inner_loop();

                    let lit_mask = self.stream.peek_bits::<LITLEN_DECODE_BITS>();

                    entry = litlen_decode_table[lit_mask];

                    'sequence: loop
                    {
                        // Resize the output vector here to ensure we can always have
                        // enough space for sloppy copies
                        if dest_offset + FASTLOOP_MAX_BYTES_WRITTEN > out_block.len()
                        {
                            let curr_len = out_block.len();
                            out_block.resize(curr_len + FASTLOOP_MAX_BYTES_WRITTEN + RESIZE_BY, 0)
                        }
                        // At this point entry contains the next value of the litlen
                        // This will always be the case so meaning all our exit paths need
                        // to load in the next entry.

                        // recheck after every sequence
                        // when we hit continue, we need to recheck this
                        // as we are trying to emulate a do while
                        let new_check = self.stream.src.len() < self.stream.position + 8;

                        if new_check
                        {
                            break 'sequence;
                        }

                        self.stream.refill_inner_loop();
                        /*
                         * Consume the bits for the litlen decode table entry.  Save the
                         * original bit-buf for later, in case the extra match length
                         * bits need to be extracted from it.
                         */
                        saved_bitbuf = self.stream.buffer;

                        self.stream.drop_bits((entry & 0xFF) as u8);

                        /*
                         * Begin by checking for a "fast" literal, i.e. a literal that
                         * doesn't need a subtable.
                         */
                        if (entry & HUFFDEC_LITERAL) != 0
                        {
                            /*
                             * On 64-bit platforms, we decode up to 2 extra fast
                             * literals in addition to the primary item, as this
                             * increases performance and still leaves enough bits
                             * remaining for what follows.  We could actually do 3,
                             * assuming LITLEN_TABLEBITS=11, but that actually
                             * decreases performance slightly (perhaps by messing
                             * with the branch prediction of the conditional refill
                             * that happens later while decoding the match offset).
                             */

                            literal = entry >> 16;

                            let new_pos = self.stream.peek_bits::<LITLEN_DECODE_BITS>();

                            entry = litlen_decode_table[new_pos];
                            saved_bitbuf = self.stream.buffer;

                            self.stream.drop_bits(entry as u8);

                            let out: &mut [u8; 2] = out_block
                                .get_mut(dest_offset..dest_offset + 2)
                                .unwrap()
                                .try_into()
                                .unwrap();

                            out[0] = literal as u8;
                            dest_offset += 1;

                            if (entry & HUFFDEC_LITERAL) != 0
                            {
                                /*
                                 * Another fast literal, but this one is in lieu of the
                                 * primary item, so it doesn't count as one of the extras.
                                 */

                                // load in the next entry.
                                literal = entry >> 16;

                                let new_pos = self.stream.peek_bits::<LITLEN_DECODE_BITS>();

                                entry = litlen_decode_table[new_pos];

                                out[1] = literal as u8;
                                dest_offset += 1;

                                continue;
                            }
                        }
                        /*
                         * It's not a literal entry, so it can be a length entry, a
                         * subtable pointer entry, or an end-of-block entry.  Detect the
                         * two unlikely cases by testing the HUFFDEC_EXCEPTIONAL flag.
                         */
                        if (entry & HUFFDEC_EXCEPTIONAL) != 0
                        {
                            // Subtable pointer or end of block entry
                            if (entry & HUFFDEC_END_OF_BLOCK) != 0
                            {
                                // block done
                                break 'decode;
                            }
                            /*
                             * A subtable is required.  Load and consume the
                             * subtable entry.  The subtable entry can be of any
                             * type: literal, length, or end-of-block.
                             */
                            let entry_position = ((entry >> 8) & 0x3F) as usize;
                            let mut pos = (entry >> 16) as usize;

                            saved_bitbuf = self.stream.buffer;

                            pos += self.stream.peek_var_bits(entry_position);
                            entry = litlen_decode_table[pos.min(LITLEN_ENOUGH - 1)];

                            self.stream.drop_bits(entry as u8);

                            if (entry & HUFFDEC_LITERAL) != 0
                            {
                                // decode a literal that required a sub table
                                let new_pos = self.stream.peek_bits::<LITLEN_DECODE_BITS>();

                                literal = entry >> 16;
                                entry = litlen_decode_table[new_pos];

                                *out_block.get_mut(dest_offset).unwrap_or(&mut 0) =
                                    (literal & 0xFF) as u8;

                                dest_offset += 1;

                                continue;
                            }

                            if (entry & HUFFDEC_END_OF_BLOCK) != 0
                            {
                                break 'decode;
                            }
                        }

                        //  At this point,we dropped at most 22 bits(LITLEN_DECODE is 11 and we
                        // can do it twice), we now just have 34 bits min remaining.

                        /*
                         * Decode the match length: the length base value associated
                         * with the litlen symbol (which we extract from the decode
                         * table entry), plus the extra length bits.  We don't need to
                         * consume the extra length bits here, as they were included in
                         * the bits consumed by the entry earlier.  We also don't need
                         * to check for too-long matches here, as this is inside the
                         * fast loop where it's already been verified that the output
                         * buffer has enough space remaining to copy a max-length match.
                         */
                        let entry_dup = entry;

                        entry = offset_decode_table[self.stream.peek_bits::<OFFSET_TABLEBITS>()];
                        length = (entry_dup >> 16) as usize;

                        let mask = (1 << entry_dup as u8) - 1;

                        length += (saved_bitbuf & mask) as usize >> ((entry_dup >> 8) as u8);

                        // offset requires a subtable
                        if (entry & HUFFDEC_EXCEPTIONAL) != 0
                        {
                            self.stream.drop_bits(OFFSET_TABLEBITS as u8);
                            let extra = self.stream.peek_var_bits(((entry >> 8) & 0x3F) as usize);
                            entry = offset_decode_table[((entry >> 16) as usize + extra) & 511];
                            // refill to handle some weird edge case where we have
                            // less bits than needed for reading the lit-len
                        }
                        saved_bitbuf = self.stream.buffer;

                        self.stream.drop_bits((entry & 0xFF) as u8);

                        let mask = (1 << entry as u8) - 1;

                        offset = (entry >> 16) as usize;
                        offset += (saved_bitbuf & mask) as usize >> (((entry >> 8) & 0xFF) as u8);

                        if offset > dest_offset
                        {
                            out_block.truncate(dest_offset);

                            let err_msg = DecodeErrorStatus::CorruptData;
                            let error = InflateDecodeErrors::new(err_msg, out_block);

                            return Err(error);
                        }

                        src_offset = dest_offset - offset;

                        if self.stream.bits_left < 11
                        {
                            self.stream.refill_inner_loop();
                        }
                        // Copy some bytes unconditionally
                        // This makes us copy smaller match lengths quicker because we don't need
                        // a loop + don't send too much pressure to the Memory unit.
                        fixed_copy_within::<FASTCOPY_BYTES>(
                            &mut out_block,
                            src_offset,
                            dest_offset
                        );

                        entry = litlen_decode_table[self.stream.peek_bits::<LITLEN_DECODE_BITS>()];

                        let mut current_position = dest_offset;

                        dest_offset += length;

                        if offset == 1
                        {
                            // RLE fill with a single byte
                            let byte_to_repeat = out_block[src_offset];
                            out_block[current_position..dest_offset].fill(byte_to_repeat);
                        }
                        else if offset <= FASTCOPY_BYTES
                            && current_position + offset < dest_offset
                        {
                            // The second conditional ensures we only come
                            // here if the first copy didn't succeed to copy just enough bytes for a rep
                            // match to be valid, i.e we want this path to be taken the least amount
                            // of times possible

                            // the unconditional copy above copied some bytes
                            // don't let it go into waste
                            // Increment the position we are in by the number of correct bytes
                            // currently copied
                            let mut src_position = src_offset + offset;
                            let mut dest_position = current_position + offset;

                            // loop copying offset bytes in place
                            // notice this loop does fixed copies but increments in offset bytes :)
                            // that is intentional.
                            loop
                            {
                                fixed_copy_within::<FASTCOPY_BYTES>(
                                    &mut out_block,
                                    src_position,
                                    dest_position
                                );

                                src_position += offset;
                                dest_position += offset;

                                if dest_position > dest_offset
                                {
                                    break;
                                }
                            }
                        }
                        else if length > FASTCOPY_BYTES
                        {
                            current_position += FASTCOPY_BYTES;
                            // fast non-overlapping copy
                            //
                            // We have enough space to write the ML+FAST_COPY bytes ahead
                            // so we know this won't come to shoot us in the foot.
                            //
                            // An optimization is to copy FAST_COPY_BITS per invocation
                            // Currently FASTCOPY_BYTES is 16, this fits in nicely as we
                            // it's a single SIMD instruction on a lot of things, i.e x86,Arm and even
                            // wasm.

                            // current position of the match
                            let mut dest_src_offset = src_offset + FASTCOPY_BYTES;

                            // Number of bytes we are to copy
                            // copy in batches of FAST_BYTES
                            'match_lengths: loop
                            {
                                // Safety: We resized out_block hence we know it can handle
                                // sloppy copies without it being out of bounds
                                //
                                // Reason: This is a latency critical loop, even branches start
                                // to matter
                                fixed_copy_within::<FASTCOPY_BYTES>(
                                    &mut out_block,
                                    dest_src_offset,
                                    current_position
                                );

                                dest_src_offset += FASTCOPY_BYTES;
                                current_position += FASTCOPY_BYTES;

                                if current_position > dest_offset
                                {
                                    break 'match_lengths;
                                }
                            }
                        }

                        if dest_offset > self.options.limit
                        {
                            out_block.truncate(dest_offset);

                            let err_msg = DecodeErrorStatus::OutputLimitExceeded(
                                self.options.limit,
                                dest_offset
                            );
                            let error = InflateDecodeErrors::new(err_msg, out_block);

                            return Err(error);
                        }

                        if self.stream.src.len() < self.stream.position + 8
                        {
                            // close to input end, move to the slower one
                            break 'sequence;
                        }
                    }
                }
                // generic loop that does things a bit slower but it's okay since it doesn't
                // deal with a lot of things
                // We can afford to be more careful here, checking that we do
                // not drop non-existent bits etc etc as we do not have the
                // assurances of the fast loop bits above.
                loop
                {
                    self.stream.refill();

                    if self.stream.over_read > usize::from(self.stream.bits_left >> 3)
                    {
                        out_block.truncate(dest_offset);

                        let err_msg = DecodeErrorStatus::CorruptData;
                        let error = InflateDecodeErrors::new(err_msg, out_block);

                        return Err(error);
                    }

                    let literal_mask = self.stream.peek_bits::<LITLEN_DECODE_BITS>();

                    entry = litlen_decode_table[literal_mask];

                    saved_bitbuf = self.stream.buffer;

                    self.stream.drop_bits((entry & 0xFF) as u8);

                    if (entry & HUFFDEC_SUITABLE_POINTER) != 0
                    {
                        let extra = self.stream.peek_var_bits(((entry >> 8) & 0x3F) as usize);

                        entry = litlen_decode_table[(entry >> 16) as usize + extra];
                        saved_bitbuf = self.stream.buffer;

                        self.stream.drop_bits((entry & 0xFF) as u8);
                    }

                    length = (entry >> 16) as usize;

                    if (entry & HUFFDEC_LITERAL) != 0
                    {
                        resize_and_push(&mut out_block, dest_offset, length as u8);

                        dest_offset += 1;

                        continue;
                    }

                    if (entry & HUFFDEC_END_OF_BLOCK) != 0
                    {
                        break 'decode;
                    }

                    let mask = (1 << entry as u8) - 1;

                    length += (saved_bitbuf & mask) as usize >> ((entry >> 8) as u8);

                    self.stream.refill();

                    entry = offset_decode_table[self.stream.peek_bits::<OFFSET_TABLEBITS>()];

                    if (entry & HUFFDEC_EXCEPTIONAL) != 0
                    {
                        // offset requires a subtable
                        self.stream.drop_bits(OFFSET_TABLEBITS as u8);

                        let extra = self.stream.peek_var_bits(((entry >> 8) & 0x3F) as usize);

                        entry = offset_decode_table[((entry >> 16) as usize + extra) & 511];
                    }

                    // ensure there is enough space for a fast copy
                    if dest_offset + length + FASTCOPY_BYTES > out_block.len()
                    {
                        let new_len = out_block.len() + RESIZE_BY + length;
                        out_block.resize(new_len, 0);
                    }
                    saved_bitbuf = self.stream.buffer;

                    let mask = (1 << (entry & 0xFF) as u8) - 1;

                    offset = (entry >> 16) as usize;
                    offset += (saved_bitbuf & mask) as usize >> ((entry >> 8) as u8);

                    if offset > dest_offset
                    {
                        out_block.truncate(dest_offset);

                        let err_msg = DecodeErrorStatus::CorruptData;
                        let error = InflateDecodeErrors::new(err_msg, out_block);

                        return Err(error);
                    }

                    src_offset = dest_offset - offset;

                    self.stream.drop_bits(entry as u8);

                    let (dest_src, dest_ptr) = out_block.split_at_mut(dest_offset);

                    if src_offset + length + FASTCOPY_BYTES > dest_offset
                    {
                        // overlapping copy
                        // do a simple rep match
                        copy_rep_matches(&mut out_block, src_offset, dest_offset, length);
                    }
                    else
                    {
                        dest_ptr[0..length]
                            .copy_from_slice(&dest_src[src_offset..src_offset + length]);
                    }

                    dest_offset += length;

                    if dest_offset > self.options.limit
                    {
                        out_block.truncate(dest_offset);

                        let err_msg =
                            DecodeErrorStatus::OutputLimitExceeded(self.options.limit, dest_offset);
                        let error = InflateDecodeErrors::new(err_msg, out_block);

                        return Err(error);
                    }
                }
            }
            /*
             * If any of the implicit appended zero bytes were consumed (not just
             * refilled) before hitting end of stream, then the data is bad.
             */
            if self.stream.over_read > usize::from(self.stream.bits_left >> 3)
            {
                out_block.truncate(dest_offset);

                let err_msg = DecodeErrorStatus::CorruptData;
                let error = InflateDecodeErrors::new(err_msg, out_block);

                return Err(error);
            }

            if self.is_last_block
            {
                break;
            }
        }

        // decompression. DONE
        // Truncate data to match the number of actual
        // bytes written.
        out_block.truncate(dest_offset);

        Ok(out_block)
    }

    /// Build decode tables for static and dynamic
    /// huffman blocks.
    fn build_decode_table(&mut self, block_type: u64) -> Result<(), DecodeErrorStatus>
    {
        const COUNT: usize =
            DEFLATE_NUM_LITLEN_SYMS + DEFLATE_NUM_OFFSET_SYMS + DELFATE_MAX_LENS_OVERRUN;

        let mut lens = [0_u8; COUNT];
        let mut precode_lens = [0; DEFLATE_NUM_PRECODE_SYMS];
        let mut precode_decode_table = [0_u32; PRECODE_ENOUGH];
        let mut litlen_decode_table = [0_u32; LITLEN_ENOUGH];
        let mut offset_decode_table = [0; OFFSET_ENOUGH];

        let mut num_litlen_syms = 0;
        let mut num_offset_syms = 0;

        if block_type == DEFLATE_BLOCKTYPE_DYNAMIC_HUFFMAN
        {
            const SINGLE_PRECODE: usize = 3;

            self.static_codes_loaded = false;

            // Dynamic Huffman block
            // Read codeword lengths
            if !self.stream.has(5 + 5 + 4)
            {
                return Err(DecodeErrorStatus::InsufficientData);
            }

            num_litlen_syms = 257 + (self.stream.get_bits(5)) as usize;
            num_offset_syms = 1 + (self.stream.get_bits(5)) as usize;

            let num_explicit_precode_lens = 4 + (self.stream.get_bits(4)) as usize;

            self.stream.refill();

            if !self.stream.has(3)
            {
                return Err(DecodeErrorStatus::InsufficientData);
            }

            let first_precode = self.stream.get_bits(3) as u8;
            let expected = (SINGLE_PRECODE * num_explicit_precode_lens.saturating_sub(1)) as u8;

            precode_lens[usize::from(DEFLATE_PRECODE_LENS_PERMUTATION[0])] = first_precode;

            self.stream.refill();

            if !self.stream.has(expected)
            {
                return Err(DecodeErrorStatus::InsufficientData);
            }

            for i in DEFLATE_PRECODE_LENS_PERMUTATION[1..]
                .iter()
                .take(num_explicit_precode_lens - 1)
            {
                let bits = self.stream.get_bits(3) as u8;

                precode_lens[usize::from(*i)] = bits;
            }

            self.build_decode_table_inner(
                &precode_lens,
                &PRECODE_DECODE_RESULTS,
                &mut precode_decode_table,
                PRECODE_TABLE_BITS,
                DEFLATE_NUM_PRECODE_SYMS,
                DEFLATE_MAX_CODEWORD_LENGTH
            )?;

            /* Decode the litlen and offset codeword lengths. */

            let mut i = 0;

            loop
            {
                if i >= num_litlen_syms + num_offset_syms
                {
                    // confirm here since with a continue loop stuff
                    // breaks
                    break;
                }

                let rep_val: u8;
                let rep_count: u64;

                if !self.stream.has(DEFLATE_MAX_PRE_CODEWORD_LEN + 7)
                {
                    self.stream.refill();
                }
                // decode next pre-code symbol
                let entry_pos = self
                    .stream
                    .peek_bits::<{ DEFLATE_MAX_PRE_CODEWORD_LEN as usize }>();

                let entry = precode_decode_table[entry_pos];
                let presym = entry >> 16;

                if !self.stream.has(entry as u8)
                {
                    return Err(DecodeErrorStatus::InsufficientData);
                }

                self.stream.drop_bits(entry as u8);

                if presym < 16
                {
                    // explicit codeword length
                    lens[i] = presym as u8;
                    i += 1;
                    continue;
                }

                /* Run-length encoded codeword lengths */

                /*
                 * Note: we don't need verify that the repeat count
                 * doesn't overflow the number of elements, since we've
                 * sized the lens array to have enough extra space to
                 * allow for the worst-case overrun (138 zeroes when
                 * only 1 length was remaining).
                 *
                 * In the case of the small repeat counts (presyms 16
                 * and 17), it is fastest to always write the maximum
                 * number of entries.  That gets rid of branches that
                 * would otherwise be required.
                 *
                 * It is not just because of the numerical order that
                 * our checks go in the order 'presym < 16', 'presym ==
                 * 16', and 'presym == 17'.  For typical data this is
                 * ordered from most frequent to least frequent case.
                 */
                if presym == 16
                {
                    if i == 0
                    {
                        return Err(DecodeErrorStatus::CorruptData);
                    }

                    if !self.stream.has(2)
                    {
                        return Err(DecodeErrorStatus::InsufficientData);
                    }

                    // repeat previous length three to 6 times
                    rep_val = lens[i - 1];
                    rep_count = 3 + self.stream.get_bits(2);
                    lens[i..i + 6].fill(rep_val);
                    i += rep_count as usize;
                }
                else if presym == 17
                {
                    if !self.stream.has(3)
                    {
                        return Err(DecodeErrorStatus::InsufficientData);
                    }
                    /* Repeat zero 3 - 10 times. */
                    rep_count = 3 + self.stream.get_bits(3);
                    lens[i..i + 10].fill(0);
                    i += rep_count as usize;
                }
                else
                {
                    if !self.stream.has(7)
                    {
                        return Err(DecodeErrorStatus::InsufficientData);
                    }
                    // repeat zero 11-138 times.
                    rep_count = 11 + self.stream.get_bits(7);
                    lens[i..i + rep_count as usize].fill(0);
                    i += rep_count as usize;
                }

                if i >= num_litlen_syms + num_offset_syms
                {
                    break;
                }
            }
        }
        else if block_type == DEFLATE_BLOCKTYPE_STATIC
        {
            if self.static_codes_loaded
            {
                return Ok(());
            }

            self.static_codes_loaded = true;

            lens[000..144].fill(8);
            lens[144..256].fill(9);
            lens[256..280].fill(7);
            lens[280..288].fill(8);
            lens[288..].fill(5);

            num_litlen_syms = 288;
            num_offset_syms = 32;
        }
        // build offset decode table
        self.build_decode_table_inner(
            &lens[num_litlen_syms..],
            &OFFSET_DECODE_RESULTS,
            &mut offset_decode_table,
            OFFSET_TABLEBITS,
            num_offset_syms,
            DEFLATE_MAX_OFFSET_CODEWORD_LENGTH
        )?;

        self.build_decode_table_inner(
            &lens,
            &LITLEN_DECODE_RESULTS,
            &mut litlen_decode_table,
            LITLEN_TABLE_BITS,
            num_litlen_syms,
            DEFLATE_MAX_LITLEN_CODEWORD_LENGTH
        )?;

        self.deflate_header_tables.offset_decode_table = offset_decode_table;
        self.deflate_header_tables.litlen_decode_table = litlen_decode_table;

        Ok(())
    }
    /// Build the decode table for the precode
    #[allow(clippy::needless_range_loop)]
    fn build_decode_table_inner(
        &mut self, lens: &[u8], decode_results: &[u32], decode_table: &mut [u32],
        table_bits: usize, num_syms: usize, mut max_codeword_len: usize
    ) -> Result<(), DecodeErrorStatus>
    {
        const BITS: u32 = usize::BITS - 1;

        let mut len_counts: [u32; DEFLATE_MAX_CODEWORD_LENGTH + 1] =
            [0; DEFLATE_MAX_CODEWORD_LENGTH + 1];
        let mut offsets: [u32; DEFLATE_MAX_CODEWORD_LENGTH + 1] =
            [0; DEFLATE_MAX_CODEWORD_LENGTH + 1];
        let mut sorted_syms: [u16; DEFLATE_MAX_NUM_SYMS] = [0; DEFLATE_MAX_NUM_SYMS];

        let mut i;

        // count how many codewords have each length, including 0.
        for sym in 0..num_syms
        {
            len_counts[usize::from(lens[sym])] += 1;
        }

        /*
         * Determine the actual maximum codeword length that was used, and
         * decrease table_bits to it if allowed.
         */
        while max_codeword_len > 1 && len_counts[max_codeword_len] == 0
        {
            max_codeword_len -= 1;
        }
        /*
         * Sort the symbols primarily by increasing codeword length and
         *	A temporary array of length @num_syms.
         * secondarily by increasing symbol value; or equivalently by their
         * codewords in lexicographic order, since a canonical code is assumed.
         *
         * For efficiency, also compute 'codespace_used' in the same pass over
         * 'len_counts[]' used to build 'offsets[]' for sorting.
         */
        offsets[0] = 0;
        offsets[1] = len_counts[0];

        let mut codespace_used = 0_u32;

        for len in 1..max_codeword_len
        {
            offsets[len + 1] = offsets[len] + len_counts[len];
            codespace_used = (codespace_used << 1) + len_counts[len];
        }
        codespace_used = (codespace_used << 1) + len_counts[max_codeword_len];

        for sym in 0..num_syms
        {
            let pos = usize::from(lens[sym]);
            sorted_syms[offsets[pos] as usize] = sym as u16;
            offsets[pos] += 1;
        }
        i = (offsets[0]) as usize;

        /*
         * Check whether the lengths form a complete code (exactly fills the
         * codespace), an incomplete code (doesn't fill the codespace), or an
         * overfull code (overflows the codespace).  A codeword of length 'n'
         * uses proportion '1/(2^n)' of the codespace.  An overfull code is
         * nonsensical, so is considered invalid.  An incomplete code is
         * considered valid only in two specific cases; see below.
         */

        // Overfull code
        if codespace_used > 1 << max_codeword_len
        {
            return Err(DecodeErrorStatus::Generic("Overflown code"));
        }
        // incomplete code
        if codespace_used < 1 << max_codeword_len
        {
            let entry = if codespace_used == 0
            {
                /*
                 * An empty code is allowed.  This can happen for the
                 * offset code in DEFLATE, since a dynamic Huffman block
                 * need not contain any matches.
                 */

                /* sym=0, len=1 (arbitrary) */
                make_decode_table_entry(decode_results, 0, 1)
            }
            else
            {
                /*
                 * Allow codes with a single used symbol, with codeword
                 * length 1.  The DEFLATE RFC is unclear regarding this
                 * case.  What zlib's decompressor does is permit this
                 * for the litlen and offset codes and assume the
                 * codeword is '0' rather than '1'.  We do the same
                 * except we allow this for precodes too, since there's
                 * no convincing reason to treat the codes differently.
                 * We also assign both codewords '0' and '1' to the
                 * symbol to avoid having to handle '1' specially.
                 */
                if codespace_used != 1 << (max_codeword_len - 1) || len_counts[1] != 1
                {
                    return Err(DecodeErrorStatus::Generic(
                        "Cannot work with empty pre-code table"
                    ));
                }
                make_decode_table_entry(decode_results, usize::from(sorted_syms[i]), 1)
            };
            /*
             * Note: the decode table still must be fully initialized, in
             * case the stream is malformed and contains bits from the part
             * of the codespace the incomplete code doesn't use.
             */
            decode_table.fill(entry);
            return Ok(());
        }

        /*
         * The lengths form a complete code.  Now, enumerate the codewords in
         * lexicographic order and fill the decode table entries for each one.
         *
         * First, process all codewords with len <= table_bits.  Each one gets
         * '2^(table_bits-len)' direct entries in the table.
         *
         * Since DEFLATE uses bit-reversed codewords, these entries aren't
         * consecutive but rather are spaced '2^len' entries apart.  This makes
         * filling them naively somewhat awkward and inefficient, since strided
         * stores are less cache-friendly and preclude the use of word or
         * vector-at-a-time stores to fill multiple entries per instruction.
         *
         * To optimize this, we incrementally double the table size.  When
         * processing codewords with length 'len', the table is treated as
         * having only '2^len' entries, so each codeword uses just one entry.
         * Then, each time 'len' is incremented, the table size is doubled and
         * the first half is copied to the second half.  This significantly
         * improves performance over naively doing strided stores.
         *
         * Note that some entries copied for each table doubling may not have
         * been initialized yet, but it doesn't matter since they're guaranteed
         * to be initialized later (because the Huffman code is complete).
         */
        let mut codeword = 0;
        let mut len = 1;
        let mut count = len_counts[1];

        while count == 0
        {
            len += 1;

            if len >= len_counts.len()
            {
                break;
            }
            count = len_counts[len];
        }

        let mut curr_table_end = 1 << len;

        while len <= table_bits
        {
            // Process all count codewords with length len
            loop
            {
                let entry = make_decode_table_entry(
                    decode_results,
                    usize::from(sorted_syms[i]),
                    len as u32
                );
                i += 1;
                // fill first entry for current codeword
                decode_table[codeword] = entry;

                if codeword == curr_table_end - 1
                {
                    // last codeword (all 1's)
                    for _ in len..table_bits
                    {
                        decode_table.copy_within(0..curr_table_end, curr_table_end);

                        curr_table_end <<= 1;
                    }
                    return Ok(());
                }
                /*
                 * To advance to the lexicographically next codeword in
                 * the canonical code, the codeword must be incremented,
                 * then 0's must be appended to the codeword as needed
                 * to match the next codeword's length.
                 *
                 * Since the codeword is bit-reversed, appending 0's is
                 * a no-op.  However, incrementing it is nontrivial.  To
                 * do so efficiently, use the 'bsr' instruction to find
                 * the last (highest order) 0 bit in the codeword, set
                 * it, and clear any later (higher order) 1 bits.  But
                 * 'bsr' actually finds the highest order 1 bit, so to
                 * use it first flip all bits in the codeword by XOR' ing
                 * it with (1U << len) - 1 == cur_table_end - 1.
                 */

                let adv = BITS - (codeword ^ (curr_table_end - 1)).leading_zeros();
                let bit = 1 << adv;

                codeword &= bit - 1;
                codeword |= bit;
                count -= 1;

                if count == 0
                {
                    break;
                }
            }
            // advance to the next codeword length
            loop
            {
                len += 1;

                if len <= table_bits
                {
                    // dest is decode_table[curr_table_end]
                    // source is decode_table(start of table);
                    // size is curr_table;

                    decode_table.copy_within(0..curr_table_end, curr_table_end);

                    //decode_table.copy_within(range, curr_table_end);
                    curr_table_end <<= 1;
                }
                count = len_counts[len];

                if count != 0
                {
                    break;
                }
            }
        }
        // process codewords with len > table_bits.
        // Require sub-tables
        curr_table_end = 1 << table_bits;

        let mut subtable_prefix = usize::MAX;
        let mut subtable_start = 0;
        let mut subtable_bits;

        loop
        {
            /*
             * Start a new sub-table if the first 'table_bits' bits of the
             * codeword don't match the prefix of the current subtable.
             */
            if codeword & ((1_usize << table_bits) - 1) != subtable_prefix
            {
                subtable_prefix = codeword & ((1 << table_bits) - 1);
                subtable_start = curr_table_end;

                /*
                 * Calculate the subtable length.  If the codeword has
                 * length 'table_bits + n', then the subtable needs
                 * '2^n' entries.  But it may need more; if fewer than
                 * '2^n' codewords of length 'table_bits + n' remain,
                 * then the length will need to be incremented to bring
                 * in longer codewords until the subtable can be
                 * completely filled.  Note that because the Huffman
                 * code is complete, it will always be possible to fill
                 * the sub-table eventually.
                 */
                subtable_bits = len - table_bits;
                codespace_used = count;

                while codespace_used < (1 << subtable_bits)
                {
                    subtable_bits += 1;

                    if subtable_bits + table_bits > 15
                    {
                        return Err(DecodeErrorStatus::CorruptData);
                    }

                    codespace_used = (codespace_used << 1) + len_counts[table_bits + subtable_bits];
                }

                /*
                 * Create the entry that points from the main table to
                 * the subtable.
                 */
                decode_table[subtable_prefix] = (subtable_start as u32) << 16
                    | HUFFDEC_EXCEPTIONAL
                    | HUFFDEC_SUITABLE_POINTER
                    | (subtable_bits as u32) << 8
                    | table_bits as u32;

                curr_table_end = subtable_start + (1 << subtable_bits);
            }

            /* Fill the sub-table entries for the current codeword. */

            let stride = 1 << (len - table_bits);

            let mut j = subtable_start + (codeword >> table_bits);

            let entry = make_decode_table_entry(
                decode_results,
                sorted_syms[i] as usize,
                (len - table_bits) as u32
            );
            i += 1;

            while j < curr_table_end
            {
                decode_table[j] = entry;
                j += stride;
            }
            //advance to the next codeword
            if codeword == (1 << len) - 1
            {
                // last codeword
                return Ok(());
            }

            let adv = BITS - (codeword ^ ((1 << len) - 1)).leading_zeros();
            let bit = 1 << adv;

            codeword &= bit - 1;
            codeword |= bit;
            count -= 1;

            while count == 0
            {
                len += 1;
                count = len_counts[len];
            }
        }
    }
}

const RESIZE_BY: usize = 1024 * 4; // 4 kb

/// Resize vector if its current space wont
/// be able to store a new byte and then push an element to that new space
#[inline(always)]
fn resize_and_push(buf: &mut Vec<u8>, position: usize, elm: u8)
{
    if buf.len() <= position
    {
        let new_len = buf.len() + RESIZE_BY;
        buf.resize(new_len, 0);
    }
    buf[position] = elm;
}