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