]> wimlib.net Git - wimlib/blob - include/wimlib/decompress_common.h
2b5d4f65672631c7ba698152096cd470da793851
[wimlib] / include / wimlib / decompress_common.h
1 /*
2  * decompress_common.h
3  *
4  * Header for decompression code shared by multiple compression formats.
5  *
6  * The author dedicates this file to the public domain.
7  * You can do whatever you want with this file.
8  */
9
10 #ifndef _WIMLIB_DECOMPRESS_COMMON_H
11 #define _WIMLIB_DECOMPRESS_COMMON_H
12
13 #include "wimlib/assert.h"
14 #include "wimlib/compiler.h"
15 #include "wimlib/endianness.h"
16 #include "wimlib/types.h"
17
18 /* Structure to encapsulate a block of in-memory data that is being interpreted
19  * as a stream of bits.
20  *
21  * This is geared specifically towards the XPRESS and LZX compression formats
22  * with regards to the actual ordering the bits within the byte sequence.  */
23 struct input_bitstream {
24
25         /* A variable of length at least 32 bits that is used to hold bits that
26          * have been read from the stream.  The bits are ordered from high-order
27          * to low-order, and the next bit is always the high-order bit.  */
28         u32 bitbuf;
29
30         /* Number of bits in @bitbuf that are valid.  */
31         unsigned bitsleft;
32
33         /* Pointer to the next byte to be retrieved from the input.  */
34         const u8 *data;
35
36         /* Number of bytes of data that are left.  */
37         u32 data_bytes_left;
38 };
39
40 /* Initializes a bitstream to receive its input from @data. */
41 static inline void
42 init_input_bitstream(struct input_bitstream *istream,
43                      const void *data, u32 num_data_bytes)
44 {
45         istream->bitbuf          = 0;
46         istream->bitsleft        = 0;
47         istream->data            = data;
48         istream->data_bytes_left = num_data_bytes;
49 }
50
51 /* Ensures the bit buffer variable for the bitstream contains at least @num_bits
52  * bits.  Following this, bitstream_peek_bits() and/or bitstream_remove_bits()
53  * may be called on the bitstream to peek or remove up to @num_bits bits.
54  *
55  * If the input data is exhausted, any further bits are assumed to be 0.  */
56 static inline void
57 bitstream_ensure_bits(struct input_bitstream *istream, const unsigned num_bits)
58 {
59         u16 nextword;
60         unsigned shift;
61
62         /* This currently works for at most 17 bits.  */
63         wimlib_assert2(num_bits <= 17);
64
65         if (istream->bitsleft >= num_bits)
66                 return;
67
68         if (unlikely(istream->data_bytes_left < 2)) {
69                 istream->bitsleft = num_bits;
70                 return;
71         }
72
73         nextword = le16_to_cpu(*(const le16*)istream->data);
74         shift = sizeof(istream->bitbuf) * 8 - 16 - istream->bitsleft;
75         istream->bitbuf |= (u32)nextword << shift;
76         istream->data += 2;
77         istream->bitsleft += 16;
78         istream->data_bytes_left -= 2;
79
80         /* Help the compiler: If it's known at compile-time that num_bits <= 16,
81          * a second word will never be needed.  */
82         if (!(is_constant(num_bits) && num_bits <= 16) &&
83             unlikely(istream->bitsleft < num_bits))
84         {
85                 if (unlikely(istream->data_bytes_left < 2)) {
86                         istream->bitsleft = num_bits;
87                         return;
88                 }
89                 nextword = le16_to_cpu(*(const le16*)istream->data);
90                 shift = sizeof(istream->bitbuf) * 8 - 16 - istream->bitsleft;
91                 istream->bitbuf |= (u32)nextword << shift;
92                 istream->data += 2;
93                 istream->bitsleft += 16;
94                 istream->data_bytes_left -= 2;
95         }
96 }
97
98 /* Returns the next @num_bits bits from the bitstream, without removing them.
99  * There must be at least @num_bits remaining in the buffer variable, from a
100  * previous call to bitstream_ensure_bits().  */
101 static inline u32
102 bitstream_peek_bits(const struct input_bitstream *istream, unsigned num_bits)
103 {
104         if (unlikely(num_bits == 0))
105                 return 0;
106         return istream->bitbuf >> (sizeof(istream->bitbuf) * 8 - num_bits);
107 }
108
109 /* Removes @num_bits from the bitstream.  There must be at least @num_bits
110  * remaining in the buffer variable, from a previous call to
111  * bitstream_ensure_bits().  */
112 static inline void
113 bitstream_remove_bits(struct input_bitstream *istream, unsigned num_bits)
114 {
115         istream->bitbuf <<= num_bits;
116         istream->bitsleft -= num_bits;
117 }
118
119 /* Removes and returns @num_bits bits from the bitstream.  There must be at
120  * least @num_bits remaining in the buffer variable, from a previous call to
121  * bitstream_ensure_bits().  */
122 static inline u32
123 bitstream_pop_bits(struct input_bitstream *istream, unsigned num_bits)
124 {
125         u32 n = bitstream_peek_bits(istream, num_bits);
126         bitstream_remove_bits(istream, num_bits);
127         return n;
128 }
129
130 /* Reads and returns the next @num_bits bits from the bitstream.
131  * If the input data is exhausted, the bits are assumed to be 0.  */
132 static inline u32
133 bitstream_read_bits(struct input_bitstream *istream, unsigned num_bits)
134 {
135         bitstream_ensure_bits(istream, num_bits);
136         return bitstream_pop_bits(istream, num_bits);
137 }
138
139 /* Reads and returns the next literal byte embedded in the bitstream.
140  * If the input data is exhausted, the byte is assumed to be 0.  */
141 static inline u8
142 bitstream_read_byte(struct input_bitstream *istream)
143 {
144         if (unlikely(istream->data_bytes_left == 0))
145                 return 0;
146         istream->data_bytes_left--;
147         return *istream->data++;
148 }
149
150
151 /* Needed alignment of decode_table parameter to make_huffman_decode_table().
152  *
153  * Reason: We may fill the entries with SSE instructions without worrying
154  * about dealing with the unaligned case.  */
155 #define DECODE_TABLE_ALIGNMENT 16
156
157 /* Maximum supported symbol count for make_huffman_decode_table().
158  *
159  * Reason: In direct mapping entries, we store the symbol in 11 bits.  */
160 #define DECODE_TABLE_MAX_SYMBOLS 2048
161
162 /* Maximum supported table bits for make_huffman_decode_table().
163  *
164  * Reason: In internal binary tree nodes, offsets are encoded in 14 bits.
165  * But the real limit is 13, because we allocate entries past the end of
166  * the direct lookup part of the table for binary tree nodes.  (Note: if
167  * needed this limit could be removed by encoding the offsets relative to
168  * &decode_table[1 << table_bits].)  */
169 #define DECODE_TABLE_MAX_TABLE_BITS 13
170
171 /* Maximum supported codeword length for make_huffman_decode_table().
172  *
173  * Reason: In direct mapping entries, we encode the codeword length in 5
174  * bits, and the top 2 bits can't both be set because that has special
175  * meaning.  */
176 #define DECODE_TABLE_MAX_CODEWORD_LEN 23
177
178 /* Reads and returns the next Huffman-encoded symbol from a bitstream.  If the
179  * input data is exhausted, the Huffman symbol is decoded as if the missing bits
180  * are all zeroes.
181  *
182  * XXX: This is mostly duplicated in lzms_huffman_decode_symbol() in
183  * lzms-decompress.c.  */
184 static inline u16
185 read_huffsym(struct input_bitstream *istream, const u16 decode_table[],
186              unsigned table_bits, unsigned max_codeword_len)
187 {
188         u16 entry;
189         u16 key_bits;
190
191         bitstream_ensure_bits(istream, max_codeword_len);
192
193         /* Index the decode table by the next table_bits bits of the input.  */
194         key_bits = bitstream_peek_bits(istream, table_bits);
195         entry = decode_table[key_bits];
196         if (likely(entry < 0xC000)) {
197                 /* Fast case: The decode table directly provided the
198                  * symbol and codeword length.  The low 11 bits are the
199                  * symbol, and the high 5 bits are the codeword length.  */
200                 bitstream_remove_bits(istream, entry >> 11);
201                 return entry & 0x7FF;
202         } else {
203                 /* Slow case: The codeword for the symbol is longer than
204                  * table_bits, so the symbol does not have an entry
205                  * directly in the first (1 << table_bits) entries of the
206                  * decode table.  Traverse the appropriate binary tree
207                  * bit-by-bit to decode the symbol.  */
208                 bitstream_remove_bits(istream, table_bits);
209                 do {
210                         key_bits = (entry & 0x3FFF) + bitstream_pop_bits(istream, 1);
211                 } while ((entry = decode_table[key_bits]) >= 0xC000);
212                 return entry;
213         }
214 }
215
216 extern int
217 make_huffman_decode_table(u16 decode_table[], unsigned num_syms,
218                           unsigned num_bits, const u8 lens[],
219                           unsigned max_codeword_len);
220
221
222 /*
223  * Copy a LZ77 match at (dst - offset) to dst.
224  *
225  * The length and offset must be already validated --- that is, (dst - offset)
226  * can't underrun the output buffer, and (dst + length) can't overrun the output
227  * buffer.  Also, the length cannot be 0.
228  *
229  * @winend points to the byte past the end of the output buffer.
230  * This function won't write any data beyond this position.
231  */
232 static inline void
233 lz_copy(u8 *dst, unsigned length, unsigned offset, const u8 *winend)
234 {
235         const u8 *src = dst - offset;
236 #if defined(__x86_64__) || defined(__i386__)
237         /* Copy one 'unsigned long' at a time.  On i386 and x86_64 this is
238          * faster than copying one byte at a time, unless the data is
239          * near-random and all the matches have very short lengths.  Note that
240          * since this requires unaligned memory accesses, it won't necessarily
241          * be faster on every architecture.
242          *
243          * Also note that we might copy more than the length of the match.  For
244          * example, if an 'unsigned long' is 8 bytes and the match is of length
245          * 5, then we'll simply copy 8 bytes.  This is okay as long as we don't
246          * write beyond the end of the output buffer, hence the check for
247          * (winend - (dst + length) >= sizeof(unsigned long) - 1).  */
248         if (offset >= sizeof(unsigned long) &&
249                         winend - (dst + length) >= sizeof(unsigned long) - 1)
250         {
251                 /* Access memory through a packed struct.  This tricks the
252                  * compiler into allowing unaligned memory accesses.  */
253                 struct ulong_wrapper {
254                         unsigned long v;
255                 } _packed_attribute;
256
257                 const u8 *end = dst + length;
258                 do {
259                         unsigned long v = ((struct ulong_wrapper *)src)->v;
260                         ((struct ulong_wrapper *)dst)->v = v;
261                         dst += sizeof(unsigned long);
262                         src += sizeof(unsigned long);
263                 } while (dst < end);
264
265                 return;
266         }
267 #endif
268         do {
269                 *dst++ = *src++;
270         } while (--length);
271 }
272
273 #endif /* _WIMLIB_DECOMPRESS_COMMON_H */