]> wimlib.net Git - wimlib/blob - include/wimlib/decompress_common.h
Misc. cleanups
[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/compiler.h"
14 #include "wimlib/endianness.h"
15 #include "wimlib/types.h"
16 #include "wimlib/unaligned.h"
17
18 /* Structure that encapsulates a block of in-memory data being interpreted as a
19  * stream of bits, optionally with interwoven literal bytes.  Bits are assumed
20  * to be stored in little endian 16-bit coding units, with the bits ordered high
21  * to low.  */
22 struct input_bitstream {
23
24         /* Bits that have been read from the input buffer.  The bits are
25          * left-justified; the next bit is always bit 31.  */
26         u32 bitbuf;
27
28         /* Number of bits currently held in @bitbuf.  */
29         u32 bitsleft;
30
31         /* Pointer to the next byte to be retrieved from the input buffer.  */
32         const u8 *next;
33
34         /* Pointer past the end of the input buffer.  */
35         const u8 *end;
36 };
37
38 /* Initialize a bitstream to read from the specified input buffer.  */
39 static inline void
40 init_input_bitstream(struct input_bitstream *is, const void *buffer, u32 size)
41 {
42         is->bitbuf = 0;
43         is->bitsleft = 0;
44         is->next = buffer;
45         is->end = is->next + size;
46 }
47
48 /* Note: for performance reasons, the following methods don't return error codes
49  * to the caller if the input buffer is overrun.  Instead, they just assume that
50  * all overrun data is zeroes.  This has no effect on well-formed compressed
51  * data.  The only disadvantage is that bad compressed data may go undetected,
52  * but even this is irrelevant if higher level code checksums the uncompressed
53  * data anyway.  */
54
55 /* Ensure the bit buffer variable for the bitstream contains at least @num_bits
56  * bits.  Following this, bitstream_peek_bits() and/or bitstream_remove_bits()
57  * may be called on the bitstream to peek or remove up to @num_bits bits.  */
58 static inline void
59 bitstream_ensure_bits(struct input_bitstream *is, const unsigned num_bits)
60 {
61         /* This currently works for at most 17 bits.  */
62
63         if (is->bitsleft >= num_bits)
64                 return;
65
66         if (unlikely(is->end - is->next < 2))
67                 goto overflow;
68
69         is->bitbuf |= (u32)get_unaligned_u16_le(is->next) << (16 - is->bitsleft);
70         is->next += 2;
71         is->bitsleft += 16;
72
73         if (unlikely(num_bits == 17 && is->bitsleft == 16)) {
74                 if (unlikely(is->end - is->next < 2))
75                         goto overflow;
76
77                 is->bitbuf |= (u32)get_unaligned_u16_le(is->next);
78                 is->next += 2;
79                 is->bitsleft = 32;
80         }
81
82         return;
83
84 overflow:
85         is->bitsleft = 32;
86 }
87
88 /* Return the next @num_bits bits from the bitstream, without removing them.
89  * There must be at least @num_bits remaining in the buffer variable, from a
90  * previous call to bitstream_ensure_bits().  */
91 static inline u32
92 bitstream_peek_bits(const struct input_bitstream *is, const unsigned num_bits)
93 {
94         if (unlikely(num_bits == 0))
95                 return 0;
96         return is->bitbuf >> (32 - num_bits);
97 }
98
99 /* Remove @num_bits from the bitstream.  There must be at least @num_bits
100  * remaining in the buffer variable, from a previous call to
101  * bitstream_ensure_bits().  */
102 static inline void
103 bitstream_remove_bits(struct input_bitstream *is, unsigned num_bits)
104 {
105         is->bitbuf <<= num_bits;
106         is->bitsleft -= num_bits;
107 }
108
109 /* Remove and return @num_bits bits from the bitstream.  There must be at least
110  * @num_bits remaining in the buffer variable, from a previous call to
111  * bitstream_ensure_bits().  */
112 static inline u32
113 bitstream_pop_bits(struct input_bitstream *is, unsigned num_bits)
114 {
115         u32 bits = bitstream_peek_bits(is, num_bits);
116         bitstream_remove_bits(is, num_bits);
117         return bits;
118 }
119
120 /* Read and return the next @num_bits bits from the bitstream.  */
121 static inline u32
122 bitstream_read_bits(struct input_bitstream *is, unsigned num_bits)
123 {
124         bitstream_ensure_bits(is, num_bits);
125         return bitstream_pop_bits(is, num_bits);
126 }
127
128 /* Read and return the next literal byte embedded in the bitstream.  */
129 static inline u8
130 bitstream_read_byte(struct input_bitstream *is)
131 {
132         if (unlikely(is->end == is->next))
133                 return 0;
134         return *is->next++;
135 }
136
137 /* Read and return the next 16-bit integer embedded in the bitstream.  */
138 static inline u16
139 bitstream_read_u16(struct input_bitstream *is)
140 {
141         u16 v;
142
143         if (unlikely(is->end - is->next < 2))
144                 return 0;
145         v = get_unaligned_u16_le(is->next);
146         is->next += 2;
147         return v;
148 }
149
150 /* Read and return the next 32-bit integer embedded in the bitstream.  */
151 static inline u32
152 bitstream_read_u32(struct input_bitstream *is)
153 {
154         u32 v;
155
156         if (unlikely(is->end - is->next < 4))
157                 return 0;
158         v = get_unaligned_u32_le(is->next);
159         is->next += 4;
160         return v;
161 }
162
163 /* Read an array of literal bytes embedded in the bitstream.  Return a pointer
164  * to the resulting array, or NULL if the read overflows the input buffer.  */
165 static inline const u8 *
166 bitstream_read_bytes(struct input_bitstream *is, size_t count)
167 {
168         const u8 *p;
169
170         if (unlikely(is->end - is->next < count))
171                 return NULL;
172         p = is->next;
173         is->next += count;
174         return p;
175 }
176
177 /* Align the input bitstream on a coding-unit boundary.  */
178 static inline void
179 bitstream_align(struct input_bitstream *is)
180 {
181         is->bitsleft = 0;
182         is->bitbuf = 0;
183 }
184
185 /* Needed alignment of decode_table parameter to make_huffman_decode_table().
186  *
187  * Reason: We may fill the entries with SSE instructions without worrying
188  * about dealing with the unaligned case.  */
189 #define DECODE_TABLE_ALIGNMENT 16
190
191 /* Maximum supported symbol count for make_huffman_decode_table().
192  *
193  * Reason: In direct mapping entries, we store the symbol in 11 bits.  */
194 #define DECODE_TABLE_MAX_SYMBOLS 2048
195
196 /* Maximum supported table bits for make_huffman_decode_table().
197  *
198  * Reason: In internal binary tree nodes, offsets are encoded in 14 bits.
199  * But the real limit is 13, because we allocate entries past the end of
200  * the direct lookup part of the table for binary tree nodes.  (Note: if
201  * needed this limit could be removed by encoding the offsets relative to
202  * &decode_table[1 << table_bits].)  */
203 #define DECODE_TABLE_MAX_TABLE_BITS 13
204
205 /* Maximum supported codeword length for make_huffman_decode_table().
206  *
207  * Reason: In direct mapping entries, we encode the codeword length in 5
208  * bits, and the top 2 bits can't both be set because that has special
209  * meaning.  */
210 #define DECODE_TABLE_MAX_CODEWORD_LEN 23
211
212 /* Reads and returns the next Huffman-encoded symbol from a bitstream.  If the
213  * input data is exhausted, the Huffman symbol is decoded as if the missing bits
214  * are all zeroes.
215  *
216  * XXX: This is mostly duplicated in lzms_decode_huffman_symbol() in
217  * lzms_decompress.c.  */
218 static inline u16
219 read_huffsym(struct input_bitstream *istream, const u16 decode_table[],
220              unsigned table_bits, unsigned max_codeword_len)
221 {
222         unsigned entry;
223         unsigned key_bits;
224
225         bitstream_ensure_bits(istream, max_codeword_len);
226
227         /* Index the decode table by the next table_bits bits of the input.  */
228         key_bits = bitstream_peek_bits(istream, table_bits);
229         entry = decode_table[key_bits];
230         if (likely(entry < 0xC000)) {
231                 /* Fast case: The decode table directly provided the
232                  * symbol and codeword length.  The low 11 bits are the
233                  * symbol, and the high 5 bits are the codeword length.  */
234                 bitstream_remove_bits(istream, entry >> 11);
235                 return entry & 0x7FF;
236         } else {
237                 /* Slow case: The codeword for the symbol is longer than
238                  * table_bits, so the symbol does not have an entry
239                  * directly in the first (1 << table_bits) entries of the
240                  * decode table.  Traverse the appropriate binary tree
241                  * bit-by-bit to decode the symbol.  */
242                 bitstream_remove_bits(istream, table_bits);
243                 do {
244                         key_bits = (entry & 0x3FFF) + bitstream_pop_bits(istream, 1);
245                 } while ((entry = decode_table[key_bits]) >= 0xC000);
246                 return entry;
247         }
248 }
249
250 extern int
251 make_huffman_decode_table(u16 decode_table[], unsigned num_syms,
252                           unsigned num_bits, const u8 lens[],
253                           unsigned max_codeword_len);
254
255 static inline void
256 copy_word_unaligned(const void *src, void *dst)
257 {
258         store_word_unaligned(load_word_unaligned(src), dst);
259 }
260
261 static inline machine_word_t
262 repeat_byte(u8 b)
263 {
264         machine_word_t v;
265
266         BUILD_BUG_ON(WORDSIZE != 4 && WORDSIZE != 8);
267
268         v = b;
269         v |= v << 8;
270         v |= v << 16;
271         v |= v << ((WORDSIZE == 8) ? 32 : 0);
272         return v;
273 }
274
275 /*
276  * Copy an LZ77 match at (dst - offset) to dst.
277  *
278  * The length and offset must be already validated --- that is, (dst - offset)
279  * can't underrun the output buffer, and (dst + length) can't overrun the output
280  * buffer.  Also, the length cannot be 0.
281  *
282  * @winend points to the byte past the end of the output buffer.
283  * This function won't write any data beyond this position.
284  */
285 static inline void
286 lz_copy(u8 *dst, u32 length, u32 offset, const u8 *winend, u32 min_length)
287 {
288         const u8 *src = dst - offset;
289         const u8 * const end = dst + length;
290
291         /*
292          * Try to copy one machine word at a time.  On i386 and x86_64 this is
293          * faster than copying one byte at a time, unless the data is
294          * near-random and all the matches have very short lengths.  Note that
295          * since this requires unaligned memory accesses, it won't necessarily
296          * be faster on every architecture.
297          *
298          * Also note that we might copy more than the length of the match.  For
299          * example, if a word is 8 bytes and the match is of length 5, then
300          * we'll simply copy 8 bytes.  This is okay as long as we don't write
301          * beyond the end of the output buffer, hence the check for (winend -
302          * end >= WORDSIZE - 1).
303          */
304         if (UNALIGNED_ACCESS_IS_VERY_FAST &&
305             likely(winend - end >= WORDSIZE - 1))
306         {
307
308                 if (offset >= WORDSIZE) {
309                         /* The source and destination words don't overlap.  */
310
311                         /* To improve branch prediction, one iteration of this
312                          * loop is unrolled.  Most matches are short and will
313                          * fail the first check.  But if that check passes, then
314                          * it becomes increasing likely that the match is long
315                          * and we'll need to continue copying.  */
316
317                         copy_word_unaligned(src, dst);
318                         src += WORDSIZE;
319                         dst += WORDSIZE;
320
321                         if (dst < end) {
322                                 do {
323                                         copy_word_unaligned(src, dst);
324                                         src += WORDSIZE;
325                                         dst += WORDSIZE;
326                                 } while (dst < end);
327                         }
328                         return;
329                 } else if (offset == 1) {
330
331                         /* Offset 1 matches are equivalent to run-length
332                          * encoding of the previous byte.  This case is common
333                          * if the data contains many repeated bytes.  */
334
335                         machine_word_t v = repeat_byte(*(dst - 1));
336                         do {
337                                 store_word_unaligned(v, dst);
338                                 src += WORDSIZE;
339                                 dst += WORDSIZE;
340                         } while (dst < end);
341                         return;
342                 }
343                 /*
344                  * We don't bother with special cases for other 'offset <
345                  * WORDSIZE', which are usually rarer than 'offset == 1'.  Extra
346                  * checks will just slow things down.  Actually, it's possible
347                  * to handle all the 'offset < WORDSIZE' cases using the same
348                  * code, but it still becomes more complicated doesn't seem any
349                  * faster overall; it definitely slows down the more common
350                  * 'offset == 1' case.
351                  */
352         }
353
354         /* Fall back to a bytewise copy.  */
355
356         if (min_length >= 2) {
357                 *dst++ = *src++;
358                 length--;
359         }
360         if (min_length >= 3) {
361                 *dst++ = *src++;
362                 length--;
363         }
364         if (min_length >= 4) {
365                 *dst++ = *src++;
366                 length--;
367         }
368         do {
369                 *dst++ = *src++;
370         } while (--length);
371 }
372
373 #endif /* _WIMLIB_DECOMPRESS_COMMON_H */