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