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