]> wimlib.net Git - wimlib/blob - include/wimlib/decompress_common.h
lz_copy(): Unroll first iteration
[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
18 /* Structure that encapsulates a block of in-memory data being interpreted as a
19  * stream of bits, optionally with interwoven literal bytes.  Bits are assumed
20  * to be stored in little endian 16-bit coding units, with the bits ordered high
21  * to low.  */
22 struct input_bitstream {
23
24         /* Bits that have been read from the input buffer.  The bits are
25          * left-justified; the next bit is always bit 31.  */
26         u32 bitbuf;
27
28         /* Number of bits currently held in @bitbuf.  */
29         u32 bitsleft;
30
31         /* Pointer to the next byte to be retrieved from the input buffer.  */
32         const u8 *next;
33
34         /* Pointer past the end of the input buffer.  */
35         const u8 *end;
36 };
37
38 /* Initialize a bitstream to read from the specified input buffer.  */
39 static inline void
40 init_input_bitstream(struct input_bitstream *is, const void *buffer, u32 size)
41 {
42         is->bitbuf = 0;
43         is->bitsleft = 0;
44         is->next = buffer;
45         is->end = is->next + size;
46 }
47
48 /* Note: for performance reasons, the following methods don't return error codes
49  * to the caller if the input buffer is overrun.  Instead, they just assume that
50  * all overrun data is zeroes.  This has no effect on well-formed compressed
51  * data.  The only disadvantage is that bad compressed data may go undetected,
52  * but even this is irrelevant if higher level code checksums the uncompressed
53  * data anyway.  */
54
55 /* Ensure the bit buffer variable for the bitstream contains at least @num_bits
56  * bits.  Following this, bitstream_peek_bits() and/or bitstream_remove_bits()
57  * may be called on the bitstream to peek or remove up to @num_bits bits.  */
58 static inline void
59 bitstream_ensure_bits(struct input_bitstream *is, const unsigned num_bits)
60 {
61         /* This currently works for at most 17 bits.  */
62         wimlib_assert2(num_bits <= 17);
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)le16_to_cpu(*(const le16 *)is->next)
71                         << (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)le16_to_cpu(*(const le16 *)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 < 1))
135                 return 0;
136         return *is->next++;
137 }
138
139 /* Read and return the next 32-bit integer embedded in the bitstream.  */
140 static inline u32
141 bitstream_read_u32(struct input_bitstream *is)
142 {
143         u32 v;
144
145         if (unlikely(is->end - is->next < 4))
146                 return 0;
147         v = le32_to_cpu(*(const le32 *)is->next);
148         is->next += 4;
149         return v;
150 }
151
152 /* Read an array of literal bytes embedded in the bitstream.  Return a pointer
153  * to the resulting array, or NULL if the read overflows the input buffer.  */
154 static inline const u8 *
155 bitstream_read_bytes(struct input_bitstream *is, size_t count)
156 {
157         const u8 *p;
158
159         if (unlikely(is->end - is->next < count))
160                 return NULL;
161         p = is->next;
162         is->next += count;
163         return p;
164 }
165
166 /* Align the input bitstream on a coding-unit boundary.  */
167 static inline void
168 bitstream_align(struct input_bitstream *is)
169 {
170         is->bitsleft = 0;
171         is->bitbuf = 0;
172 }
173
174 /* Needed alignment of decode_table parameter to make_huffman_decode_table().
175  *
176  * Reason: We may fill the entries with SSE instructions without worrying
177  * about dealing with the unaligned case.  */
178 #define DECODE_TABLE_ALIGNMENT 16
179
180 /* Maximum supported symbol count for make_huffman_decode_table().
181  *
182  * Reason: In direct mapping entries, we store the symbol in 11 bits.  */
183 #define DECODE_TABLE_MAX_SYMBOLS 2048
184
185 /* Maximum supported table bits for make_huffman_decode_table().
186  *
187  * Reason: In internal binary tree nodes, offsets are encoded in 14 bits.
188  * But the real limit is 13, because we allocate entries past the end of
189  * the direct lookup part of the table for binary tree nodes.  (Note: if
190  * needed this limit could be removed by encoding the offsets relative to
191  * &decode_table[1 << table_bits].)  */
192 #define DECODE_TABLE_MAX_TABLE_BITS 13
193
194 /* Maximum supported codeword length for make_huffman_decode_table().
195  *
196  * Reason: In direct mapping entries, we encode the codeword length in 5
197  * bits, and the top 2 bits can't both be set because that has special
198  * meaning.  */
199 #define DECODE_TABLE_MAX_CODEWORD_LEN 23
200
201 /* Reads and returns the next Huffman-encoded symbol from a bitstream.  If the
202  * input data is exhausted, the Huffman symbol is decoded as if the missing bits
203  * are all zeroes.
204  *
205  * XXX: This is mostly duplicated in lzms_huffman_decode_symbol() in
206  * lzms-decompress.c.  */
207 static inline u16
208 read_huffsym(struct input_bitstream *istream, const u16 decode_table[],
209              unsigned table_bits, unsigned max_codeword_len)
210 {
211         u16 entry;
212         u16 key_bits;
213
214         bitstream_ensure_bits(istream, max_codeword_len);
215
216         /* Index the decode table by the next table_bits bits of the input.  */
217         key_bits = bitstream_peek_bits(istream, table_bits);
218         entry = decode_table[key_bits];
219         if (likely(entry < 0xC000)) {
220                 /* Fast case: The decode table directly provided the
221                  * symbol and codeword length.  The low 11 bits are the
222                  * symbol, and the high 5 bits are the codeword length.  */
223                 bitstream_remove_bits(istream, entry >> 11);
224                 return entry & 0x7FF;
225         } else {
226                 /* Slow case: The codeword for the symbol is longer than
227                  * table_bits, so the symbol does not have an entry
228                  * directly in the first (1 << table_bits) entries of the
229                  * decode table.  Traverse the appropriate binary tree
230                  * bit-by-bit to decode the symbol.  */
231                 bitstream_remove_bits(istream, table_bits);
232                 do {
233                         key_bits = (entry & 0x3FFF) + bitstream_pop_bits(istream, 1);
234                 } while ((entry = decode_table[key_bits]) >= 0xC000);
235                 return entry;
236         }
237 }
238
239 extern int
240 make_huffman_decode_table(u16 decode_table[], unsigned num_syms,
241                           unsigned num_bits, const u8 lens[],
242                           unsigned max_codeword_len);
243
244
245 /*
246  * Copy a LZ77 match at (dst - offset) to dst.
247  *
248  * The length and offset must be already validated --- that is, (dst - offset)
249  * can't underrun the output buffer, and (dst + length) can't overrun the output
250  * buffer.  Also, the length cannot be 0.
251  *
252  * @winend points to the byte past the end of the output buffer.
253  * This function won't write any data beyond this position.
254  */
255 static inline void
256 lz_copy(u8 *dst, u32 length, u32 offset, const u8 *winend)
257 {
258         const u8 *src = dst - offset;
259 #if defined(__x86_64__) || defined(__i386__)
260         /* Copy one 'unsigned long' at a time.  On i386 and x86_64 this is
261          * faster than copying one byte at a time, unless the data is
262          * near-random and all the matches have very short lengths.  Note that
263          * since this requires unaligned memory accesses, it won't necessarily
264          * be faster on every architecture.
265          *
266          * Also note that we might copy more than the length of the match.  For
267          * example, if an 'unsigned long' is 8 bytes and the match is of length
268          * 5, then we'll simply copy 8 bytes.  This is okay as long as we don't
269          * write beyond the end of the output buffer, hence the check for
270          * (winend - (dst + length) >= sizeof(unsigned long) - 1).  */
271         if (offset >= sizeof(unsigned long) &&
272                         winend - (dst + length) >= sizeof(unsigned long) - 1)
273         {
274                 /* Access memory through a packed struct.  This tricks the
275                  * compiler into allowing unaligned memory accesses.  */
276                 struct ulong_wrapper {
277                         unsigned long v;
278                 } _packed_attribute;
279
280                 const u8 * const end = dst + length;
281                 unsigned long v;
282
283                 v = ((struct ulong_wrapper *)src)->v;
284                 ((struct ulong_wrapper *)dst)->v = v;
285                 dst += sizeof(unsigned long);
286                 src += sizeof(unsigned long);
287
288                 if (dst < end) {
289                         do {
290                                 v = ((struct ulong_wrapper *)src)->v;
291                                 ((struct ulong_wrapper *)dst)->v = v;
292                                 dst += sizeof(unsigned long);
293                                 src += sizeof(unsigned long);
294                         } while (dst < end);
295                 }
296
297                 return;
298         }
299 #endif
300         do {
301                 *dst++ = *src++;
302         } while (--length);
303 }
304
305 #endif /* _WIMLIB_DECOMPRESS_COMMON_H */