4 * Header for decompression code shared by multiple compression formats.
6 * The following copying information applies to this specific source code file:
8 * Written in 2012-2016 by Eric Biggers <ebiggers3@gmail.com>
10 * To the extent possible under law, the author(s) have dedicated all copyright
11 * and related and neighboring rights to this software to the public domain
12 * worldwide via the Creative Commons Zero 1.0 Universal Public Domain
13 * Dedication (the "CC0").
15 * This software is distributed in the hope that it will be useful, but WITHOUT
16 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17 * FOR A PARTICULAR PURPOSE. See the CC0 for more details.
19 * You should have received a copy of the CC0 along with this software; if not
20 * see <http://creativecommons.org/publicdomain/zero/1.0/>.
23 #ifndef _WIMLIB_DECOMPRESS_COMMON_H
24 #define _WIMLIB_DECOMPRESS_COMMON_H
28 #include "wimlib/compiler.h"
29 #include "wimlib/types.h"
30 #include "wimlib/unaligned.h"
32 /* Structure that encapsulates a block of in-memory data being interpreted as a
33 * stream of bits, optionally with interwoven literal bytes. Bits are assumed
34 * to be stored in little endian 16-bit coding units, with the bits ordered high
36 struct input_bitstream {
38 /* Bits that have been read from the input buffer. The bits are
39 * left-justified; the next bit is always bit 31. */
42 /* Number of bits currently held in @bitbuf. */
45 /* Pointer to the next byte to be retrieved from the input buffer. */
48 /* Pointer past the end of the input buffer. */
52 /* Initialize a bitstream to read from the specified input buffer. */
54 init_input_bitstream(struct input_bitstream *is, const void *buffer, u32 size)
59 is->end = is->next + size;
62 /* Note: for performance reasons, the following methods don't return error codes
63 * to the caller if the input buffer is overrun. Instead, they just assume that
64 * all overrun data is zeroes. This has no effect on well-formed compressed
65 * data. The only disadvantage is that bad compressed data may go undetected,
66 * but even this is irrelevant if higher level code checksums the uncompressed
69 /* Ensure the bit buffer variable for the bitstream contains at least @num_bits
70 * bits. Following this, bitstream_peek_bits() and/or bitstream_remove_bits()
71 * may be called on the bitstream to peek or remove up to @num_bits bits. */
73 bitstream_ensure_bits(struct input_bitstream *is, const unsigned num_bits)
75 /* This currently works for at most 17 bits. */
77 if (is->bitsleft >= num_bits)
80 if (unlikely(is->end - is->next < 2))
83 is->bitbuf |= (u32)get_unaligned_le16(is->next) << (16 - is->bitsleft);
87 if (unlikely(num_bits == 17 && is->bitsleft == 16)) {
88 if (unlikely(is->end - is->next < 2))
91 is->bitbuf |= (u32)get_unaligned_le16(is->next);
102 /* Return the next @num_bits bits from the bitstream, without removing them.
103 * There must be at least @num_bits remaining in the buffer variable, from a
104 * previous call to bitstream_ensure_bits(). */
106 bitstream_peek_bits(const struct input_bitstream *is, const unsigned num_bits)
108 return (is->bitbuf >> 1) >> (sizeof(is->bitbuf) * 8 - num_bits - 1);
111 /* Remove @num_bits from the bitstream. There must be at least @num_bits
112 * remaining in the buffer variable, from a previous call to
113 * bitstream_ensure_bits(). */
115 bitstream_remove_bits(struct input_bitstream *is, unsigned num_bits)
117 is->bitbuf <<= num_bits;
118 is->bitsleft -= num_bits;
121 /* Remove and return @num_bits bits from the bitstream. There must be at least
122 * @num_bits remaining in the buffer variable, from a previous call to
123 * bitstream_ensure_bits(). */
125 bitstream_pop_bits(struct input_bitstream *is, unsigned num_bits)
127 u32 bits = bitstream_peek_bits(is, num_bits);
128 bitstream_remove_bits(is, num_bits);
132 /* Read and return the next @num_bits bits from the bitstream. */
134 bitstream_read_bits(struct input_bitstream *is, unsigned num_bits)
136 bitstream_ensure_bits(is, num_bits);
137 return bitstream_pop_bits(is, num_bits);
140 /* Read and return the next literal byte embedded in the bitstream. */
142 bitstream_read_byte(struct input_bitstream *is)
144 if (unlikely(is->end == is->next))
149 /* Read and return the next 16-bit integer embedded in the bitstream. */
151 bitstream_read_u16(struct input_bitstream *is)
155 if (unlikely(is->end - is->next < 2))
157 v = get_unaligned_le16(is->next);
162 /* Read and return the next 32-bit integer embedded in the bitstream. */
164 bitstream_read_u32(struct input_bitstream *is)
168 if (unlikely(is->end - is->next < 4))
170 v = get_unaligned_le32(is->next);
175 /* Read into @dst_buffer an array of literal bytes embedded in the bitstream.
176 * Return either a pointer to the byte past the last written, or NULL if the
177 * read overflows the input buffer. */
179 bitstream_read_bytes(struct input_bitstream *is, void *dst_buffer, size_t count)
181 if (unlikely(is->end - is->next < count))
183 memcpy(dst_buffer, is->next, count);
185 return (u8 *)dst_buffer + count;
188 /* Align the input bitstream on a coding-unit boundary. */
190 bitstream_align(struct input_bitstream *is)
196 /* Needed alignment of decode_table parameter to make_huffman_decode_table().
198 * Reason: We may fill the entries with SSE instructions without worrying
199 * about dealing with the unaligned case. */
200 #define DECODE_TABLE_ALIGNMENT 16
202 /* Maximum supported symbol count for make_huffman_decode_table().
204 * Reason: In direct mapping entries, we store the symbol in 11 bits. */
205 #define DECODE_TABLE_MAX_SYMBOLS 2048
207 /* Maximum supported table bits for make_huffman_decode_table().
209 * Reason: In internal binary tree nodes, offsets are encoded in 14 bits.
210 * But the real limit is 13, because we allocate entries past the end of
211 * the direct lookup part of the table for binary tree nodes. (Note: if
212 * needed this limit could be removed by encoding the offsets relative to
213 * &decode_table[1 << table_bits].) */
214 #define DECODE_TABLE_MAX_TABLE_BITS 13
216 /* Maximum supported codeword length for make_huffman_decode_table().
218 * Reason: In direct mapping entries, we encode the codeword length in 5
219 * bits, and the top 2 bits can't both be set because that has special
221 #define DECODE_TABLE_MAX_CODEWORD_LEN 23
223 /* Reads and returns the next Huffman-encoded symbol from a bitstream. If the
224 * input data is exhausted, the Huffman symbol is decoded as if the missing bits
227 * XXX: This is mostly duplicated in lzms_decode_huffman_symbol() in
228 * lzms_decompress.c. */
229 static inline unsigned
230 read_huffsym(struct input_bitstream *istream, const u16 decode_table[],
231 unsigned table_bits, unsigned max_codeword_len)
236 bitstream_ensure_bits(istream, max_codeword_len);
238 /* Index the decode table by the next table_bits bits of the input. */
239 key_bits = bitstream_peek_bits(istream, table_bits);
240 entry = decode_table[key_bits];
241 if (likely(entry < 0xC000)) {
242 /* Fast case: The decode table directly provided the
243 * symbol and codeword length. The low 11 bits are the
244 * symbol, and the high 5 bits are the codeword length. */
245 bitstream_remove_bits(istream, entry >> 11);
246 return entry & 0x7FF;
248 /* Slow case: The codeword for the symbol is longer than
249 * table_bits, so the symbol does not have an entry
250 * directly in the first (1 << table_bits) entries of the
251 * decode table. Traverse the appropriate binary tree
252 * bit-by-bit to decode the symbol. */
253 bitstream_remove_bits(istream, table_bits);
255 key_bits = (entry & 0x3FFF) + bitstream_pop_bits(istream, 1);
256 } while ((entry = decode_table[key_bits]) >= 0xC000);
262 make_huffman_decode_table(u16 decode_table[], unsigned num_syms,
263 unsigned num_bits, const u8 lens[],
264 unsigned max_codeword_len);
267 copy_word_unaligned(const void *src, void *dst)
269 store_word_unaligned(load_word_unaligned(src), dst);
272 static inline machine_word_t
277 STATIC_ASSERT(WORDSIZE == 4 || WORDSIZE == 8);
282 v |= v << ((WORDSIZE == 8) ? 32 : 0);
287 * Copy an LZ77 match at (dst - offset) to dst.
289 * The length and offset must be already validated --- that is, (dst - offset)
290 * can't underrun the output buffer, and (dst + length) can't overrun the output
291 * buffer. Also, the length cannot be 0.
293 * @winend points to the byte past the end of the output buffer.
294 * This function won't write any data beyond this position.
297 lz_copy(u8 *dst, u32 length, u32 offset, const u8 *winend, u32 min_length)
299 const u8 *src = dst - offset;
300 const u8 * const end = dst + length;
303 * Try to copy one machine word at a time. On i386 and x86_64 this is
304 * faster than copying one byte at a time, unless the data is
305 * near-random and all the matches have very short lengths. Note that
306 * since this requires unaligned memory accesses, it won't necessarily
307 * be faster on every architecture.
309 * Also note that we might copy more than the length of the match. For
310 * example, if a word is 8 bytes and the match is of length 5, then
311 * we'll simply copy 8 bytes. This is okay as long as we don't write
312 * beyond the end of the output buffer, hence the check for (winend -
313 * end >= WORDSIZE - 1).
315 if (UNALIGNED_ACCESS_IS_FAST &&
316 likely(winend - end >= WORDSIZE - 1))
319 if (offset >= WORDSIZE) {
320 /* The source and destination words don't overlap. */
322 /* To improve branch prediction, one iteration of this
323 * loop is unrolled. Most matches are short and will
324 * fail the first check. But if that check passes, then
325 * it becomes increasing likely that the match is long
326 * and we'll need to continue copying. */
328 copy_word_unaligned(src, dst);
334 copy_word_unaligned(src, dst);
340 } else if (offset == 1) {
342 /* Offset 1 matches are equivalent to run-length
343 * encoding of the previous byte. This case is common
344 * if the data contains many repeated bytes. */
346 machine_word_t v = repeat_byte(*(dst - 1));
348 store_word_unaligned(v, dst);
355 * We don't bother with special cases for other 'offset <
356 * WORDSIZE', which are usually rarer than 'offset == 1'. Extra
357 * checks will just slow things down. Actually, it's possible
358 * to handle all the 'offset < WORDSIZE' cases using the same
359 * code, but it still becomes more complicated doesn't seem any
360 * faster overall; it definitely slows down the more common
361 * 'offset == 1' case.
365 /* Fall back to a bytewise copy. */
367 if (min_length >= 2) {
371 if (min_length >= 3) {
375 if (min_length >= 4) {
384 #endif /* _WIMLIB_DECOMPRESS_COMMON_H */