4 * Header for decompression code shared by multiple compression formats.
6 * The author dedicates this file to the public domain.
7 * You can do whatever you want with this file.
10 #ifndef _WIMLIB_DECOMPRESS_COMMON_H
11 #define _WIMLIB_DECOMPRESS_COMMON_H
13 #include "wimlib/compiler.h"
14 #include "wimlib/types.h"
15 #include "wimlib/unaligned.h"
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
21 struct input_bitstream {
23 /* Bits that have been read from the input buffer. The bits are
24 * left-justified; the next bit is always bit 31. */
27 /* Number of bits currently held in @bitbuf. */
30 /* Pointer to the next byte to be retrieved from the input buffer. */
33 /* Pointer past the end of the input buffer. */
37 /* Initialize a bitstream to read from the specified input buffer. */
39 init_input_bitstream(struct input_bitstream *is, const void *buffer, u32 size)
44 is->end = is->next + size;
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
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. */
58 bitstream_ensure_bits(struct input_bitstream *is, const unsigned num_bits)
60 /* This currently works for at most 17 bits. */
62 if (is->bitsleft >= num_bits)
65 if (unlikely(is->end - is->next < 2))
68 is->bitbuf |= (u32)get_unaligned_u16_le(is->next) << (16 - is->bitsleft);
72 if (unlikely(num_bits == 17 && is->bitsleft == 16)) {
73 if (unlikely(is->end - is->next < 2))
76 is->bitbuf |= (u32)get_unaligned_u16_le(is->next);
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(). */
91 bitstream_peek_bits(const struct input_bitstream *is, const unsigned num_bits)
93 if (unlikely(num_bits == 0))
95 return is->bitbuf >> (32 - num_bits);
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(). */
102 bitstream_remove_bits(struct input_bitstream *is, unsigned num_bits)
104 is->bitbuf <<= num_bits;
105 is->bitsleft -= num_bits;
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(). */
112 bitstream_pop_bits(struct input_bitstream *is, unsigned num_bits)
114 u32 bits = bitstream_peek_bits(is, num_bits);
115 bitstream_remove_bits(is, num_bits);
119 /* Read and return the next @num_bits bits from the bitstream. */
121 bitstream_read_bits(struct input_bitstream *is, unsigned num_bits)
123 bitstream_ensure_bits(is, num_bits);
124 return bitstream_pop_bits(is, num_bits);
127 /* Read and return the next literal byte embedded in the bitstream. */
129 bitstream_read_byte(struct input_bitstream *is)
131 if (unlikely(is->end == is->next))
136 /* Read and return the next 16-bit integer embedded in the bitstream. */
138 bitstream_read_u16(struct input_bitstream *is)
142 if (unlikely(is->end - is->next < 2))
144 v = get_unaligned_u16_le(is->next);
149 /* Read and return the next 32-bit integer embedded in the bitstream. */
151 bitstream_read_u32(struct input_bitstream *is)
155 if (unlikely(is->end - is->next < 4))
157 v = get_unaligned_u32_le(is->next);
162 /* Read an array of literal bytes embedded in the bitstream. Return a pointer
163 * to the resulting array, or NULL if the read overflows the input buffer. */
164 static inline const u8 *
165 bitstream_read_bytes(struct input_bitstream *is, size_t count)
169 if (unlikely(is->end - is->next < count))
176 /* Align the input bitstream on a coding-unit boundary. */
178 bitstream_align(struct input_bitstream *is)
184 /* Needed alignment of decode_table parameter to make_huffman_decode_table().
186 * Reason: We may fill the entries with SSE instructions without worrying
187 * about dealing with the unaligned case. */
188 #define DECODE_TABLE_ALIGNMENT 16
190 /* Maximum supported symbol count for make_huffman_decode_table().
192 * Reason: In direct mapping entries, we store the symbol in 11 bits. */
193 #define DECODE_TABLE_MAX_SYMBOLS 2048
195 /* Maximum supported table bits for make_huffman_decode_table().
197 * Reason: In internal binary tree nodes, offsets are encoded in 14 bits.
198 * But the real limit is 13, because we allocate entries past the end of
199 * the direct lookup part of the table for binary tree nodes. (Note: if
200 * needed this limit could be removed by encoding the offsets relative to
201 * &decode_table[1 << table_bits].) */
202 #define DECODE_TABLE_MAX_TABLE_BITS 13
204 /* Maximum supported codeword length for make_huffman_decode_table().
206 * Reason: In direct mapping entries, we encode the codeword length in 5
207 * bits, and the top 2 bits can't both be set because that has special
209 #define DECODE_TABLE_MAX_CODEWORD_LEN 23
211 /* Reads and returns the next Huffman-encoded symbol from a bitstream. If the
212 * input data is exhausted, the Huffman symbol is decoded as if the missing bits
215 * XXX: This is mostly duplicated in lzms_decode_huffman_symbol() in
216 * lzms_decompress.c. */
218 read_huffsym(struct input_bitstream *istream, const u16 decode_table[],
219 unsigned table_bits, unsigned max_codeword_len)
224 bitstream_ensure_bits(istream, max_codeword_len);
226 /* Index the decode table by the next table_bits bits of the input. */
227 key_bits = bitstream_peek_bits(istream, table_bits);
228 entry = decode_table[key_bits];
229 if (likely(entry < 0xC000)) {
230 /* Fast case: The decode table directly provided the
231 * symbol and codeword length. The low 11 bits are the
232 * symbol, and the high 5 bits are the codeword length. */
233 bitstream_remove_bits(istream, entry >> 11);
234 return entry & 0x7FF;
236 /* Slow case: The codeword for the symbol is longer than
237 * table_bits, so the symbol does not have an entry
238 * directly in the first (1 << table_bits) entries of the
239 * decode table. Traverse the appropriate binary tree
240 * bit-by-bit to decode the symbol. */
241 bitstream_remove_bits(istream, table_bits);
243 key_bits = (entry & 0x3FFF) + bitstream_pop_bits(istream, 1);
244 } while ((entry = decode_table[key_bits]) >= 0xC000);
250 make_huffman_decode_table(u16 decode_table[], unsigned num_syms,
251 unsigned num_bits, const u8 lens[],
252 unsigned max_codeword_len);
255 copy_word_unaligned(const void *src, void *dst)
257 store_word_unaligned(load_word_unaligned(src), dst);
260 static inline machine_word_t
265 BUILD_BUG_ON(WORDSIZE != 4 && WORDSIZE != 8);
270 v |= v << ((WORDSIZE == 8) ? 32 : 0);
275 * Copy an LZ77 match at (dst - offset) to dst.
277 * The length and offset must be already validated --- that is, (dst - offset)
278 * can't underrun the output buffer, and (dst + length) can't overrun the output
279 * buffer. Also, the length cannot be 0.
281 * @winend points to the byte past the end of the output buffer.
282 * This function won't write any data beyond this position.
285 lz_copy(u8 *dst, u32 length, u32 offset, const u8 *winend, u32 min_length)
287 const u8 *src = dst - offset;
288 const u8 * const end = dst + length;
291 * Try to copy one machine word at a time. On i386 and x86_64 this is
292 * faster than copying one byte at a time, unless the data is
293 * near-random and all the matches have very short lengths. Note that
294 * since this requires unaligned memory accesses, it won't necessarily
295 * be faster on every architecture.
297 * Also note that we might copy more than the length of the match. For
298 * example, if a word is 8 bytes and the match is of length 5, then
299 * we'll simply copy 8 bytes. This is okay as long as we don't write
300 * beyond the end of the output buffer, hence the check for (winend -
301 * end >= WORDSIZE - 1).
303 if (UNALIGNED_ACCESS_IS_VERY_FAST &&
304 likely(winend - end >= WORDSIZE - 1))
307 if (offset >= WORDSIZE) {
308 /* The source and destination words don't overlap. */
310 /* To improve branch prediction, one iteration of this
311 * loop is unrolled. Most matches are short and will
312 * fail the first check. But if that check passes, then
313 * it becomes increasing likely that the match is long
314 * and we'll need to continue copying. */
316 copy_word_unaligned(src, dst);
322 copy_word_unaligned(src, dst);
328 } else if (offset == 1) {
330 /* Offset 1 matches are equivalent to run-length
331 * encoding of the previous byte. This case is common
332 * if the data contains many repeated bytes. */
334 machine_word_t v = repeat_byte(*(dst - 1));
336 store_word_unaligned(v, dst);
343 * We don't bother with special cases for other 'offset <
344 * WORDSIZE', which are usually rarer than 'offset == 1'. Extra
345 * checks will just slow things down. Actually, it's possible
346 * to handle all the 'offset < WORDSIZE' cases using the same
347 * code, but it still becomes more complicated doesn't seem any
348 * faster overall; it definitely slows down the more common
349 * 'offset == 1' case.
353 /* Fall back to a bytewise copy. */
355 if (min_length >= 2) {
359 if (min_length >= 3) {
363 if (min_length >= 4) {
372 #endif /* _WIMLIB_DECOMPRESS_COMMON_H */