]> wimlib.net Git - wimlib/blob - include/wimlib/decompress_common.h
d6c9089909864b87b98ea753a74fcfe6dcbb6dfe
[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 #ifndef INPUT_IDX_T_DEFINED
19 #define INPUT_IDX_T_DEFINED
20 typedef u32 input_idx_t;
21 #endif
22
23 /* Structure to encapsulate a block of in-memory data that is being interpreted
24  * as a stream of bits.
25  *
26  * This is geared specifically towards the XPRESS and LZX compression formats
27  * with regards to the actual ordering the bits within the byte sequence.  */
28 struct input_bitstream {
29
30         /* A variable of length at least 32 bits that is used to hold bits that
31          * have been read from the stream.  The bits are ordered from high-order
32          * to low-order, and the next bit is always the high-order bit.  */
33         u32 bitbuf;
34
35         /* Number of bits in @bitbuf that are valid.  */
36         unsigned bitsleft;
37
38         /* Pointer to the next byte to be retrieved from the input.  */
39         const u8 *data;
40
41         /* Number of bytes of data that are left.  */
42         input_idx_t data_bytes_left;
43 };
44
45 /* Initializes a bitstream to receive its input from @data. */
46 static inline void
47 init_input_bitstream(struct input_bitstream *istream,
48                      const void *data, input_idx_t num_data_bytes)
49 {
50         istream->bitbuf          = 0;
51         istream->bitsleft        = 0;
52         istream->data            = data;
53         istream->data_bytes_left = num_data_bytes;
54 }
55
56 /* Ensures 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  *
60  * If the input data is exhausted, any further bits are assumed to be 0.  */
61 static inline void
62 bitstream_ensure_bits(struct input_bitstream *istream, unsigned num_bits)
63 {
64         for (int nbits = num_bits; (int)istream->bitsleft < nbits; nbits -= 16) {
65                 u16 nextword;
66                 unsigned shift;
67
68                 if (unlikely(istream->data_bytes_left < 2)) {
69                         istream->bitsleft = num_bits;
70                         return;
71                 }
72
73                 nextword = le16_to_cpu(*(const le16*)istream->data);
74                 shift = sizeof(istream->bitbuf) * 8 - 16 - istream->bitsleft;
75                 istream->bitbuf |= (u32)nextword << shift;
76                 istream->data += 2;
77                 istream->bitsleft += 16;
78                 istream->data_bytes_left -= 2;
79         }
80 }
81
82 /* Returns the next @num_bits bits from the bitstream, without removing them.
83  * There must be at least @num_bits remaining in the buffer variable, from a
84  * previous call to bitstream_ensure_bits().  */
85 static inline u32
86 bitstream_peek_bits(const struct input_bitstream *istream, unsigned num_bits)
87 {
88         if (unlikely(num_bits == 0))
89                 return 0;
90         return istream->bitbuf >> (sizeof(istream->bitbuf) * 8 - num_bits);
91 }
92
93 /* Removes @num_bits from the bitstream.  There must be at least @num_bits
94  * remaining in the buffer variable, from a previous call to
95  * bitstream_ensure_bits().  */
96 static inline void
97 bitstream_remove_bits(struct input_bitstream *istream, unsigned num_bits)
98 {
99         istream->bitbuf <<= num_bits;
100         istream->bitsleft -= num_bits;
101 }
102
103 /* Removes and returns @num_bits bits from the bitstream.  There must be at
104  * least @num_bits remaining in the buffer variable, from a previous call to
105  * bitstream_ensure_bits().  */
106 static inline u32
107 bitstream_pop_bits(struct input_bitstream *istream, unsigned num_bits)
108 {
109         u32 n = bitstream_peek_bits(istream, num_bits);
110         bitstream_remove_bits(istream, num_bits);
111         return n;
112 }
113
114 /* Reads and returns the next @num_bits bits from the bitstream.
115  * If the input data is exhausted, the bits are assumed to be 0.  */
116 static inline u32
117 bitstream_read_bits(struct input_bitstream *istream, unsigned num_bits)
118 {
119         bitstream_ensure_bits(istream, num_bits);
120         return bitstream_pop_bits(istream, num_bits);
121 }
122
123 /* Reads and returns the next literal byte embedded in the bitstream.
124  * If the input data is exhausted, the byte is assumed to be 0.  */
125 static inline u8
126 bitstream_read_byte(struct input_bitstream *istream)
127 {
128         if (unlikely(istream->data_bytes_left == 0))
129                 return 0;
130         istream->data_bytes_left--;
131         return *istream->data++;
132 }
133
134
135 /* Needed alignment of decode_table parameter to make_huffman_decode_table().
136  *
137  * Reason: We may fill the entries with SSE instructions without worrying
138  * about dealing with the unaligned case.  */
139 #define DECODE_TABLE_ALIGNMENT 16
140
141 /* Maximum supported symbol count for make_huffman_decode_table().
142  *
143  * Reason: In direct mapping entries, we store the symbol in 11 bits.  */
144 #define DECODE_TABLE_MAX_SYMBOLS 2048
145
146 /* Maximum supported table bits for make_huffman_decode_table().
147  *
148  * Reason: In internal binary tree nodes, offsets are encoded in 14 bits.
149  * But the real limit is 13, because we allocate entries past the end of
150  * the direct lookup part of the table for binary tree nodes.  (Note: if
151  * needed this limit could be removed by encoding the offsets relative to
152  * &decode_table[1 << table_bits].)  */
153 #define DECODE_TABLE_MAX_TABLE_BITS 13
154
155 /* Maximum supported codeword length for make_huffman_decode_table().
156  *
157  * Reason: In direct mapping entries, we encode the codeword length in 5
158  * bits, and the top 2 bits can't both be set because that has special
159  * meaning.  */
160 #define DECODE_TABLE_MAX_CODEWORD_LEN 23
161
162 /* Reads and returns the next Huffman-encoded symbol from a bitstream.  If the
163  * input data is exhausted, the Huffman symbol is decoded as if the missing bits
164  * are all zeroes.
165  *
166  * XXX: This is mostly duplicated in lzms_huffman_decode_symbol() in
167  * lzms-decompress.c.  */
168 static inline u16
169 read_huffsym(struct input_bitstream *istream, const u16 decode_table[],
170              unsigned table_bits, unsigned max_codeword_len)
171 {
172         u16 entry;
173         u16 key_bits;
174
175         bitstream_ensure_bits(istream, max_codeword_len);
176
177         /* Index the decode table by the next table_bits bits of the input.  */
178         key_bits = bitstream_peek_bits(istream, table_bits);
179         entry = decode_table[key_bits];
180         if (likely(entry < 0xC000)) {
181                 /* Fast case: The decode table directly provided the
182                  * symbol and codeword length.  The low 11 bits are the
183                  * symbol, and the high 5 bits are the codeword length.  */
184                 bitstream_remove_bits(istream, entry >> 11);
185                 return entry & 0x7FF;
186         } else {
187                 /* Slow case: The codeword for the symbol is longer than
188                  * table_bits, so the symbol does not have an entry
189                  * directly in the first (1 << table_bits) entries of the
190                  * decode table.  Traverse the appropriate binary tree
191                  * bit-by-bit to decode the symbol.  */
192                 bitstream_remove_bits(istream, table_bits);
193                 do {
194                         key_bits = (entry & 0x3FFF) + bitstream_pop_bits(istream, 1);
195                 } while ((entry = decode_table[key_bits]) >= 0xC000);
196                 return entry;
197         }
198 }
199
200 extern int
201 make_huffman_decode_table(u16 decode_table[], unsigned num_syms,
202                           unsigned num_bits, const u8 lens[],
203                           unsigned max_codeword_len);
204
205
206 /*
207  * Copy a LZ77 match at (dst - offset) to dst.
208  *
209  * The length and offset must be already validated --- that is, (dst - offset)
210  * can't underrun the output buffer, and (dst + length) can't overrun the output
211  * buffer.  Also, the length cannot be 0.
212  *
213  * @winend points to the byte past the end of the output buffer.
214  * This function won't write any data beyond this position.
215  */
216 static inline void
217 lz_copy(u8 *dst, unsigned length, unsigned offset, const u8 *winend)
218 {
219         const u8 *src = dst - offset;
220 #if defined(__x86_64__) || defined(__i386__)
221         /* Copy one 'unsigned long' at a time.  On i386 and x86_64 this is
222          * faster than copying one byte at a time, unless the data is
223          * near-random and all the matches have very short lengths.  Note that
224          * since this requires unaligned memory accesses, it won't necessarily
225          * be faster on every architecture.
226          *
227          * Also note that we might copy more than the length of the match.  For
228          * example, if an 'unsigned long' is 8 bytes and the match is of length
229          * 5, then we'll simply copy 8 bytes.  This is okay as long as we don't
230          * write beyond the end of the output buffer, hence the check for
231          * (winend - (dst + length) >= sizeof(unsigned long) - 1).  */
232         if (offset >= sizeof(unsigned long) &&
233                         winend - (dst + length) >= sizeof(unsigned long) - 1)
234         {
235                 /* Access memory through a packed struct.  This tricks the
236                  * compiler into allowing unaligned memory accesses.  */
237                 struct ulong_wrapper {
238                         unsigned long v;
239                 } _packed_attribute;
240
241                 const u8 *end = dst + length;
242                 do {
243                         unsigned long v = ((struct ulong_wrapper *)src)->v;
244                         ((struct ulong_wrapper *)dst)->v = v;
245                         dst += sizeof(unsigned long);
246                         src += sizeof(unsigned long);
247                 } while (dst < end);
248
249                 return;
250         }
251 #endif
252         do {
253                 *dst++ = *src++;
254         } while (--length);
255 }
256
257 #endif /* _WIMLIB_DECOMPRESS_COMMON_H */