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