1 //
2 // Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
3 //
4 // Distributed under the Boost Software License, Version 1.0. (See accompanying
5 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6 //
7 // Official repository: https://github.com/boostorg/beast
8 //
9 // This is a derivative work based on Zlib, copyright below:
10 /*
11     Copyright (C) 1995-2013 Jean-loup Gailly and Mark Adler
12 
13     This software is provided 'as-is', without any express or implied
14     warranty.  In no event will the authors be held liable for any damages
15     arising from the use of this software.
16 
17     Permission is granted to anyone to use this software for any purpose,
18     including commercial applications, and to alter it and redistribute it
19     freely, subject to the following restrictions:
20 
21     1. The origin of this software must not be misrepresented; you must not
22        claim that you wrote the original software. If you use this software
23        in a product, an acknowledgment in the product documentation would be
24        appreciated but is not required.
25     2. Altered source versions must be plainly marked as such, and must not be
26        misrepresented as being the original software.
27     3. This notice may not be removed or altered from any source distribution.
28 
29     Jean-loup Gailly        Mark Adler
30     jloup@gzip.org          madler@alumni.caltech.edu
31 
32     The data format used by the zlib library is described by RFCs (Request for
33     Comments) 1950 to 1952 in the files http://tools.ietf.org/html/rfc1950
34     (zlib format), rfc1951 (deflate format) and rfc1952 (gzip format).
35 */
36 
37 #ifndef BOOST_BEAST_ZLIB_DETAIL_DEFLATE_STREAM_HPP
38 #define BOOST_BEAST_ZLIB_DETAIL_DEFLATE_STREAM_HPP
39 
40 #include <boost/beast/zlib/error.hpp>
41 #include <boost/beast/zlib/zlib.hpp>
42 #include <boost/beast/zlib/detail/ranges.hpp>
43 #include <boost/assert.hpp>
44 #include <boost/config.hpp>
45 #include <boost/optional.hpp>
46 #include <boost/throw_exception.hpp>
47 #include <cstdint>
48 #include <cstdlib>
49 #include <cstring>
50 #include <memory>
51 #include <stdexcept>
52 #include <type_traits>
53 
54 namespace boost {
55 namespace beast {
56 namespace zlib {
57 namespace detail {
58 
59 class deflate_stream
60 {
61 protected:
62     // Upper limit on code length
63     static std::uint8_t constexpr maxBits = 15;
64 
65     // Number of length codes, not counting the special END_BLOCK code
66     static std::uint16_t constexpr lengthCodes = 29;
67 
68     // Number of literal bytes 0..255
69     static std::uint16_t constexpr literals = 256;
70 
71     // Number of Literal or Length codes, including the END_BLOCK code
72     static std::uint16_t constexpr lCodes = literals + 1 + lengthCodes;
73 
74     // Number of distance code lengths
75     static std::uint16_t constexpr dCodes = 30;
76 
77     // Number of codes used to transfer the bit lengths
78     static std::uint16_t constexpr blCodes = 19;
79 
80     // Number of distance codes
81     static std::uint16_t constexpr distCodeLen = 512;
82 
83     // Size limit on bit length codes
84     static std::uint8_t constexpr maxBlBits= 7;
85 
86     static std::uint16_t constexpr minMatch = 3;
87     static std::uint16_t constexpr maxMatch = 258;
88 
89     // Can't change minMatch without also changing code, see original zlib
90     BOOST_STATIC_ASSERT(minMatch == 3);
91 
92     // end of block literal code
93     static std::uint16_t constexpr END_BLOCK = 256;
94 
95     // repeat previous bit length 3-6 times (2 bits of repeat count)
96     static std::uint8_t constexpr REP_3_6 = 16;
97 
98     // repeat a zero length 3-10 times  (3 bits of repeat count)
99     static std::uint8_t constexpr REPZ_3_10 = 17;
100 
101     // repeat a zero length 11-138 times  (7 bits of repeat count)
102     static std::uint8_t constexpr REPZ_11_138 = 18;
103 
104     // The three kinds of block type
105     static std::uint8_t constexpr STORED_BLOCK = 0;
106     static std::uint8_t constexpr STATIC_TREES = 1;
107     static std::uint8_t constexpr DYN_TREES    = 2;
108 
109     // Maximum value for memLevel in deflateInit2
110     static std::uint8_t constexpr max_mem_level = 9;
111 
112     // Default memLevel
113     static std::uint8_t constexpr DEF_MEM_LEVEL = max_mem_level;
114 
115     /*  Note: the deflate() code requires max_lazy >= minMatch and max_chain >= 4
116         For deflate_fast() (levels <= 3) good is ignored and lazy has a different
117         meaning.
118     */
119 
120     // maximum heap size
121     static std::uint16_t constexpr HEAP_SIZE = 2 * lCodes + 1;
122 
123     // size of bit buffer in bi_buf
124     static std::uint8_t constexpr Buf_size = 16;
125 
126     // Matches of length 3 are discarded if their distance exceeds kTooFar
127     static std::size_t constexpr kTooFar = 4096;
128 
129     /*  Minimum amount of lookahead, except at the end of the input file.
130         See deflate.c for comments about the minMatch+1.
131     */
132     static std::size_t constexpr kMinLookahead = maxMatch + minMatch+1;
133 
134     /*  Number of bytes after end of data in window to initialize in order
135         to avoid memory checker errors from longest match routines
136     */
137     static std::size_t constexpr kWinInit = maxMatch;
138 
139     // Describes a single value and its code string.
140     struct ct_data
141     {
142         std::uint16_t fc; // frequency count or bit string
143         std::uint16_t dl; // parent node in tree or length of bit string
144 
145         bool
operator ==boost::beast::zlib::detail::deflate_stream::ct_data146         operator==(ct_data const& rhs) const
147         {
148             return fc == rhs.fc && dl == rhs.dl;
149         }
150     };
151 
152     struct static_desc
153     {
154         ct_data const*      static_tree;// static tree or NULL
155         std::uint8_t const* extra_bits; // extra bits for each code or NULL
156         std::uint16_t       extra_base; // base index for extra_bits
157         std::uint16_t       elems;      //  max number of elements in the tree
158         std::uint8_t        max_length; // max bit length for the codes
159     };
160 
161     struct lut_type
162     {
163         // Number of extra bits for each length code
164         std::uint8_t const extra_lbits[lengthCodes] = {
165             0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0
166         };
167 
168         // Number of extra bits for each distance code
169         std::uint8_t const extra_dbits[dCodes] = {
170             0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13
171         };
172 
173         // Number of extra bits for each bit length code
174         std::uint8_t const extra_blbits[blCodes] = {
175             0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7
176         };
177 
178         // The lengths of the bit length codes are sent in order
179         // of decreasing probability, to avoid transmitting the
180         // lengths for unused bit length codes.
181         std::uint8_t const bl_order[blCodes] = {
182             16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15
183         };
184 
185         ct_data ltree[lCodes + 2];
186 
187         ct_data dtree[dCodes];
188 
189         // Distance codes. The first 256 values correspond to the distances
190         // 3 .. 258, the last 256 values correspond to the top 8 bits of
191         // the 15 bit distances.
192         std::uint8_t dist_code[distCodeLen];
193 
194         std::uint8_t length_code[maxMatch-minMatch+1];
195 
196         std::uint8_t base_length[lengthCodes];
197 
198         std::uint16_t base_dist[dCodes];
199 
200         static_desc l_desc = {
201             ltree, extra_lbits, literals+1, lCodes, maxBits
202         };
203 
204         static_desc d_desc = {
205             dtree, extra_dbits, 0, dCodes, maxBits
206         };
207 
208         static_desc bl_desc =
209         {
210             nullptr, extra_blbits, 0, blCodes, maxBlBits
211         };
212     };
213 
214     struct tree_desc
215     {
216         ct_data *dyn_tree;           /* the dynamic tree */
217         int     max_code;            /* largest code with non zero frequency */
218         static_desc const* stat_desc; /* the corresponding static tree */
219     };
220 
221     enum block_state
222     {
223         need_more,      /* block not completed, need more input or more output */
224         block_done,     /* block flush performed */
225         finish_started, /* finish started, need only more output at next deflate */
226         finish_done     /* finish done, accept no more input or output */
227     };
228 
229     // VFALCO This might not be needed, e.g. for zip/gzip
230     enum StreamStatus
231     {
232         EXTRA_STATE = 69,
233         NAME_STATE = 73,
234         COMMENT_STATE = 91,
235         HCRC_STATE = 103,
236         BUSY_STATE = 113,
237         FINISH_STATE = 666
238     };
239 
240     /* A std::uint16_t is an index in the character window. We use short instead of int to
241      * save space in the various tables. IPos is used only for parameter passing.
242      */
243     using IPos = unsigned;
244 
245     using self = deflate_stream;
246     typedef block_state(self::*compress_func)(z_params& zs, Flush flush);
247 
248     //--------------------------------------------------------------------------
249 
250     lut_type const& lut_;
251 
252     bool inited_ = false;
253     std::size_t buf_size_;
254     std::unique_ptr<std::uint8_t[]> buf_;
255 
256     int status_;                    // as the name implies
257     Byte* pending_buf_;             // output still pending
258     std::uint32_t
259         pending_buf_size_;          // size of pending_buf
260     Byte* pending_out_;             // next pending byte to output to the stream
261     uInt pending_;                  // nb of bytes in the pending buffer
262     boost::optional<Flush>
263         last_flush_;                // value of flush param for previous deflate call
264 
265     uInt w_size_;                   // LZ77 window size (32K by default)
266     uInt w_bits_;                   // log2(w_size)  (8..16)
267     uInt w_mask_;                   // w_size - 1
268 
269     /*  Sliding window. Input bytes are read into the second half of the window,
270         and move to the first half later to keep a dictionary of at least wSize
271         bytes. With this organization, matches are limited to a distance of
272         wSize-maxMatch bytes, but this ensures that IO is always
273         performed with a length multiple of the block size. Also, it limits
274         the window size to 64K.
275         To do: use the user input buffer as sliding window.
276     */
277     Byte *window_ = nullptr;
278 
279     /*  Actual size of window: 2*wSize, except when the user input buffer
280         is directly used as sliding window.
281     */
282     std::uint32_t window_size_;
283 
284     /*  Link to older string with same hash index. To limit the size of this
285         array to 64K, this link is maintained only for the last 32K strings.
286         An index in this array is thus a window index modulo 32K.
287     */
288     std::uint16_t* prev_;
289 
290     std::uint16_t* head_;           // Heads of the hash chains or 0
291 
292     uInt  ins_h_;                   // hash index of string to be inserted
293     uInt  hash_size_;               // number of elements in hash table
294     uInt  hash_bits_;               // log2(hash_size)
295     uInt  hash_mask_;               // hash_size-1
296 
297     /*  Number of bits by which ins_h must be shifted at each input
298         step. It must be such that after minMatch steps,
299         the oldest byte no longer takes part in the hash key, that is:
300         hash_shift * minMatch >= hash_bits
301     */
302     uInt hash_shift_;
303 
304     /*  Window position at the beginning of the current output block.
305         Gets negative when the window is moved backwards.
306     */
307     long block_start_;
308 
309     uInt match_length_;             // length of best match
310     IPos prev_match_;               // previous match
311     int match_available_;           // set if previous match exists
312     uInt strstart_;                 // start of string to insert
313     uInt match_start_;              // start of matching string
314     uInt lookahead_;                // number of valid bytes ahead in window
315 
316     /*  Length of the best match at previous step. Matches not greater
317         than this are discarded. This is used in the lazy match evaluation.
318     */
319     uInt prev_length_;
320 
321     /*  To speed up deflation, hash chains are never searched beyond
322         this length. A higher limit improves compression ratio but
323         degrades the speed.
324     */
325     uInt max_chain_length_;
326 
327     /*  Attempt to find a better match only when the current match is strictly
328         smaller than this value. This mechanism is used only for compression
329         levels >= 4.
330 
331         OR Insert new strings in the hash table only if the match length is not
332         greater than this length. This saves time but degrades compression.
333         used only for compression levels <= 3.
334     */
335     uInt max_lazy_match_;
336 
337     int level_;                     // compression level (1..9)
338     Strategy strategy_;             // favor or force Huffman coding
339 
340     // Use a faster search when the previous match is longer than this
341     uInt good_match_;
342 
343     int nice_match_;                // Stop searching when current match exceeds this
344 
345     ct_data dyn_ltree_[
346         HEAP_SIZE];                 // literal and length tree
347     ct_data dyn_dtree_[
348         2*dCodes+1];                // distance tree
349     ct_data bl_tree_[
350         2*blCodes+1];               // Huffman tree for bit lengths
351 
352     tree_desc l_desc_;              // desc. for literal tree
353     tree_desc d_desc_;              // desc. for distance tree
354     tree_desc bl_desc_;             // desc. for bit length tree
355 
356     // number of codes at each bit length for an optimal tree
357     std::uint16_t bl_count_[maxBits+1];
358 
359     // Index within the heap array of least frequent node in the Huffman tree
360     static std::size_t constexpr kSmallest = 1;
361 
362     /*  The sons of heap[n] are heap[2*n] and heap[2*n+1].
363         heap[0] is not used. The same heap array is used to build all trees.
364     */
365 
366     int heap_[2*lCodes+1];          // heap used to build the Huffman trees
367     int heap_len_;                  // number of elements in the heap
368     int heap_max_;                  // element of largest frequency
369 
370     // Depth of each subtree used as tie breaker for trees of equal frequency
371     std::uint8_t depth_[2*lCodes+1];
372 
373     std::uint8_t *l_buf_;           // buffer for literals or lengths
374 
375     /*  Size of match buffer for literals/lengths.
376         There are 4 reasons for limiting lit_bufsize to 64K:
377           - frequencies can be kept in 16 bit counters
378           - if compression is not successful for the first block, all input
379             data is still in the window so we can still emit a stored block even
380             when input comes from standard input.  (This can also be done for
381             all blocks if lit_bufsize is not greater than 32K.)
382           - if compression is not successful for a file smaller than 64K, we can
383             even emit a stored file instead of a stored block (saving 5 bytes).
384             This is applicable only for zip (not gzip or zlib).
385           - creating new Huffman trees less frequently may not provide fast
386             adaptation to changes in the input data statistics. (Take for
387             example a binary file with poorly compressible code followed by
388             a highly compressible string table.) Smaller buffer sizes give
389             fast adaptation but have of course the overhead of transmitting
390             trees more frequently.
391           - I can't count above 4
392     */
393     uInt lit_bufsize_;
394     uInt last_lit_;                 // running index in l_buf_
395 
396     /*  Buffer for distances. To simplify the code, d_buf_ and l_buf_
397         have the same number of elements. To use different lengths, an
398         extra flag array would be necessary.
399     */
400     std::uint16_t* d_buf_;
401 
402     std::uint32_t opt_len_;         // bit length of current block with optimal trees
403     std::uint32_t static_len_;      // bit length of current block with static trees
404     uInt matches_;                  // number of string matches in current block
405     uInt insert_;                   // bytes at end of window left to insert
406 
407     /*  Output buffer.
408         Bits are inserted starting at the bottom (least significant bits).
409      */
410     std::uint16_t bi_buf_;
411 
412     /*  Number of valid bits in bi_buf._  All bits above the last valid
413         bit are always zero.
414     */
415     int bi_valid_;
416 
417     /*  High water mark offset in window for initialized bytes -- bytes
418         above this are set to zero in order to avoid memory check warnings
419         when longest match routines access bytes past the input.  This is
420         then updated to the new high water mark.
421     */
422     std::uint32_t high_water_;
423 
424     //--------------------------------------------------------------------------
425 
deflate_stream()426     deflate_stream()
427         : lut_(get_lut())
428     {
429     }
430 
431     /*  In order to simplify the code, particularly on 16 bit machines, match
432         distances are limited to MAX_DIST instead of WSIZE.
433     */
434     std::size_t
max_dist() const435     max_dist() const
436     {
437         return w_size_ - kMinLookahead;
438     }
439 
440     void
put_byte(std::uint8_t c)441     put_byte(std::uint8_t c)
442     {
443         pending_buf_[pending_++] = c;
444     }
445 
446     void
put_short(std::uint16_t w)447     put_short(std::uint16_t w)
448     {
449         put_byte(w & 0xff);
450         put_byte(w >> 8);
451     }
452 
453     /*  Send a value on a given number of bits.
454         IN assertion: length <= 16 and value fits in length bits.
455     */
456     void
send_bits(int value,int length)457     send_bits(int value, int length)
458     {
459         if(bi_valid_ > (int)Buf_size - length)
460         {
461             bi_buf_ |= (std::uint16_t)value << bi_valid_;
462             put_short(bi_buf_);
463             bi_buf_ = (std::uint16_t)value >> (Buf_size - bi_valid_);
464             bi_valid_ += length - Buf_size;
465         }
466         else
467         {
468             bi_buf_ |= (std::uint16_t)(value) << bi_valid_;
469             bi_valid_ += length;
470         }
471     }
472 
473     // Send a code of the given tree
474     void
send_code(int value,ct_data const * tree)475     send_code(int value, ct_data const* tree)
476     {
477         send_bits(tree[value].fc, tree[value].dl);
478     }
479 
480     /*  Mapping from a distance to a distance code. dist is the
481         distance - 1 and must not have side effects. _dist_code[256]
482         and _dist_code[257] are never used.
483     */
484     std::uint8_t
d_code(unsigned dist)485     d_code(unsigned dist)
486     {
487         if(dist < 256)
488             return lut_.dist_code[dist];
489         return lut_.dist_code[256+(dist>>7)];
490     }
491 
492     /*  Update a hash value with the given input byte
493         IN  assertion: all calls to to update_hash are made with
494             consecutive input characters, so that a running hash
495             key can be computed from the previous key instead of
496             complete recalculation each time.
497     */
498     void
update_hash(uInt & h,std::uint8_t c)499     update_hash(uInt& h, std::uint8_t c)
500     {
501         h = ((h << hash_shift_) ^ c) & hash_mask_;
502     }
503 
504     /*  Initialize the hash table (avoiding 64K overflow for 16
505         bit systems). prev[] will be initialized on the fly.
506     */
507     void
clear_hash()508     clear_hash()
509     {
510         head_[hash_size_-1] = 0;
511         std::memset((Byte *)head_, 0,
512             (unsigned)(hash_size_-1)*sizeof(*head_));
513     }
514 
515     /*  Compares two subtrees, using the tree depth as tie breaker
516         when the subtrees have equal frequency. This minimizes the
517         worst case length.
518     */
519     bool
smaller(ct_data const * tree,int n,int m)520     smaller(ct_data const* tree, int n, int m)
521     {
522         return tree[n].fc < tree[m].fc ||
523             (tree[n].fc == tree[m].fc &&
524                 depth_[n] <= depth_[m]);
525     }
526 
527     /*  Insert string str in the dictionary and set match_head to the
528         previous head of the hash chain (the most recent string with
529         same hash key). Return the previous length of the hash chain.
530         If this file is compiled with -DFASTEST, the compression level
531         is forced to 1, and no hash chains are maintained.
532         IN  assertion: all calls to to INSERT_STRING are made with
533             consecutive input characters and the first minMatch
534             bytes of str are valid (except for the last minMatch-1
535             bytes of the input file).
536     */
537     void
insert_string(IPos & hash_head)538     insert_string(IPos& hash_head)
539     {
540         update_hash(ins_h_, window_[strstart_ + (minMatch-1)]);
541         hash_head = prev_[strstart_ & w_mask_] = head_[ins_h_];
542         head_[ins_h_] = (std::uint16_t)strstart_;
543     }
544 
545     //--------------------------------------------------------------------------
546 
547     /* Values for max_lazy_match, good_match and max_chain_length, depending on
548      * the desired pack level (0..9). The values given below have been tuned to
549      * exclude worst case performance for pathological files. Better values may be
550      * found for specific files.
551      */
552     struct config
553     {
554        std::uint16_t good_length; /* reduce lazy search above this match length */
555        std::uint16_t max_lazy;    /* do not perform lazy search above this match length */
556        std::uint16_t nice_length; /* quit search above this match length */
557        std::uint16_t max_chain;
558        compress_func func;
559 
configboost::beast::zlib::detail::deflate_stream::config560        config(
561                std::uint16_t good_length_,
562                std::uint16_t max_lazy_,
563                std::uint16_t nice_length_,
564                std::uint16_t max_chain_,
565                compress_func func_)
566            : good_length(good_length_)
567            , max_lazy(max_lazy_)
568            , nice_length(nice_length_)
569            , max_chain(max_chain_)
570            , func(func_)
571        {
572        }
573     };
574 
575     static
576     config
get_config(std::size_t level)577     get_config(std::size_t level)
578     {
579         switch(level)
580         {
581         //              good lazy nice chain
582         case 0: return {  0,   0,   0,    0, &self::deflate_stored}; // store only
583         case 1: return {  4,   4,   8,    4, &self::deflate_fast};   // max speed, no lazy matches
584         case 2: return {  4,   5,  16,    8, &self::deflate_fast};
585         case 3: return {  4,   6,  32,   32, &self::deflate_fast};
586         case 4: return {  4,   4,  16,   16, &self::deflate_slow};   // lazy matches
587         case 5: return {  8,  16,  32,   32, &self::deflate_slow};
588         case 6: return {  8,  16, 128,  128, &self::deflate_slow};
589         case 7: return {  8,  32, 128,  256, &self::deflate_slow};
590         case 8: return { 32, 128, 258, 1024, &self::deflate_slow};
591         default:
592         case 9: return { 32, 258, 258, 4096, &self::deflate_slow};    // max compression
593         }
594     }
595 
596     void
maybe_init()597     maybe_init()
598     {
599         if(! inited_)
600             init();
601     }
602 
603     template<class Unsigned>
604     static
605     Unsigned
606     bi_reverse(Unsigned code, unsigned len);
607 
608     BOOST_BEAST_DECL
609     static
610     void
611     gen_codes(ct_data *tree, int max_code, std::uint16_t *bl_count);
612 
613     BOOST_BEAST_DECL
614     static
615     lut_type const&
616     get_lut();
617 
618     BOOST_BEAST_DECL void doReset             (int level, int windowBits, int memLevel, Strategy strategy);
619     BOOST_BEAST_DECL void doReset             ();
620     BOOST_BEAST_DECL void doClear             ();
621     BOOST_BEAST_DECL std::size_t doUpperBound (std::size_t sourceLen) const;
622     BOOST_BEAST_DECL void doTune              (int good_length, int max_lazy, int nice_length, int max_chain);
623     BOOST_BEAST_DECL void doParams            (z_params& zs, int level, Strategy strategy, error_code& ec);
624     BOOST_BEAST_DECL void doWrite             (z_params& zs, boost::optional<Flush> flush, error_code& ec);
625     BOOST_BEAST_DECL void doDictionary        (Byte const* dict, uInt dictLength, error_code& ec);
626     BOOST_BEAST_DECL void doPrime             (int bits, int value, error_code& ec);
627     BOOST_BEAST_DECL void doPending           (unsigned* value, int* bits);
628 
629     BOOST_BEAST_DECL void init                ();
630     BOOST_BEAST_DECL void lm_init             ();
631     BOOST_BEAST_DECL void init_block          ();
632     BOOST_BEAST_DECL void pqdownheap          (ct_data const* tree, int k);
633     BOOST_BEAST_DECL void pqremove            (ct_data const* tree, int& top);
634     BOOST_BEAST_DECL void gen_bitlen          (tree_desc *desc);
635     BOOST_BEAST_DECL void build_tree          (tree_desc *desc);
636     BOOST_BEAST_DECL void scan_tree           (ct_data *tree, int max_code);
637     BOOST_BEAST_DECL void send_tree           (ct_data *tree, int max_code);
638     BOOST_BEAST_DECL int  build_bl_tree       ();
639     BOOST_BEAST_DECL void send_all_trees      (int lcodes, int dcodes, int blcodes);
640     BOOST_BEAST_DECL void compress_block      (ct_data const* ltree, ct_data const* dtree);
641     BOOST_BEAST_DECL int  detect_data_type    ();
642     BOOST_BEAST_DECL void bi_windup           ();
643     BOOST_BEAST_DECL void bi_flush            ();
644     BOOST_BEAST_DECL void copy_block          (char *buf, unsigned len, int header);
645 
646     BOOST_BEAST_DECL void tr_init             ();
647     BOOST_BEAST_DECL void tr_align            ();
648     BOOST_BEAST_DECL void tr_flush_bits       ();
649     BOOST_BEAST_DECL void tr_stored_block     (char *bu, std::uint32_t stored_len, int last);
650     BOOST_BEAST_DECL void tr_tally_dist       (std::uint16_t dist, std::uint8_t len, bool& flush);
651     BOOST_BEAST_DECL void tr_tally_lit        (std::uint8_t c, bool& flush);
652 
653     BOOST_BEAST_DECL void tr_flush_block      (z_params& zs, char *buf, std::uint32_t stored_len, int last);
654     BOOST_BEAST_DECL void fill_window         (z_params& zs);
655     BOOST_BEAST_DECL void flush_pending       (z_params& zs);
656     BOOST_BEAST_DECL void flush_block         (z_params& zs, bool last);
657     BOOST_BEAST_DECL int  read_buf            (z_params& zs, Byte *buf, unsigned size);
658     BOOST_BEAST_DECL uInt longest_match       (IPos cur_match);
659 
660     BOOST_BEAST_DECL block_state f_stored     (z_params& zs, Flush flush);
661     BOOST_BEAST_DECL block_state f_fast       (z_params& zs, Flush flush);
662     BOOST_BEAST_DECL block_state f_slow       (z_params& zs, Flush flush);
663     BOOST_BEAST_DECL block_state f_rle        (z_params& zs, Flush flush);
664     BOOST_BEAST_DECL block_state f_huff       (z_params& zs, Flush flush);
665 
666     block_state
deflate_stored(z_params & zs,Flush flush)667     deflate_stored(z_params& zs, Flush flush)
668     {
669         return f_stored(zs, flush);
670     }
671 
672     block_state
deflate_fast(z_params & zs,Flush flush)673     deflate_fast(z_params& zs, Flush flush)
674     {
675         return f_fast(zs, flush);
676     }
677 
678     block_state
deflate_slow(z_params & zs,Flush flush)679     deflate_slow(z_params& zs, Flush flush)
680     {
681         return f_slow(zs, flush);
682     }
683 
684     block_state
deflate_rle(z_params & zs,Flush flush)685     deflate_rle(z_params& zs, Flush flush)
686     {
687         return f_rle(zs, flush);
688     }
689 
690     block_state
deflate_huff(z_params & zs,Flush flush)691     deflate_huff(z_params& zs, Flush flush)
692     {
693         return f_huff(zs, flush);
694     }
695 };
696 
697 //--------------------------------------------------------------------------
698 
699 // Reverse the first len bits of a code
700 template<class Unsigned>
701 Unsigned
702 deflate_stream::
bi_reverse(Unsigned code,unsigned len)703 bi_reverse(Unsigned code, unsigned len)
704 {
705     BOOST_STATIC_ASSERT(std::is_unsigned<Unsigned>::value);
706     BOOST_ASSERT(len <= 8 * sizeof(unsigned));
707     Unsigned res = 0;
708     do
709     {
710         res |= code & 1;
711         code >>= 1;
712         res <<= 1;
713     }
714     while(--len > 0);
715     return res >> 1;
716 }
717 
718 } // detail
719 } // zlib
720 } // beast
721 } // boost
722 
723 #ifdef BOOST_BEAST_HEADER_ONLY
724 #include <boost/beast/zlib/detail/deflate_stream.ipp>
725 #endif
726 
727 #endif
728