1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
use super::{BIT_MODEL_TOTAL_BITS, ByteDecoder, MOVE_BITS, RC_BIT_MODEL_OFFSET, SHIFT_BITS};
use crate::{Read, error_invalid_input};
pub(crate) struct RangeDecoder {
inner: RangeDecoderBuffer,
range: u32,
code: u32,
}
impl RangeDecoder {
pub(crate) fn new_buffer(size: usize) -> Self {
Self {
inner: RangeDecoderBuffer::new(size - 5),
code: 0,
range: 0,
}
}
}
struct RangeDecoderBuffer {
buf: Vec<u8>,
pos: usize,
}
impl RangeDecoderBuffer {
fn new(len: usize) -> Self {
Self {
buf: vec![0; len],
pos: len,
}
}
fn read_u8(&mut self) -> u8 {
// Out of bound reads return an 1, which is fine, since the
// LZMA decoder will then throw a "dist overflow" error.
// Not returning an error results in code that can be better
// optimized in the hot path and overall 10% better decoding
// performance.
let byte = *self.buf.get(self.pos).unwrap_or(&1);
self.pos += 1;
byte
}
}
impl RangeDecoder {
#[inline(always)]
pub(crate) fn normalize(&mut self) {
if self.range < 0x0100_0000 {
let b = self.inner.read_u8() as u32;
self.code = (self.code << SHIFT_BITS) | b;
self.range <<= SHIFT_BITS;
}
}
#[inline(always)]
pub(crate) fn decode_bit(&mut self, prob: &mut u16) -> i32 {
self.normalize();
let bound = (self.range >> BIT_MODEL_TOTAL_BITS) * (*prob as u32);
// This mask will be 0 for bit 0, and 0xFFFFFFFF for bit 1.
let mask = 0u32.wrapping_sub((self.code >= bound) as u32);
self.range = (bound & !mask) | ((self.range - bound) & mask);
self.code -= bound & mask;
let p = *prob as u32;
let offset = RC_BIT_MODEL_OFFSET & !mask;
*prob = p.wrapping_sub((p.wrapping_add(offset)) >> MOVE_BITS) as u16;
(mask & 1) as i32
}
pub(crate) fn decode_bit_tree(&mut self, probs: &mut [u16]) -> i32 {
let mut symbol = 1;
loop {
symbol = (symbol << 1) | self.decode_bit(&mut probs[symbol as usize]);
if symbol >= probs.len() as i32 {
break;
}
}
symbol - probs.len() as i32
}
pub(crate) fn decode_reverse_bit_tree(&mut self, probs: &mut [u16]) -> i32 {
let mut symbol = 1;
let mut i = 0;
let mut result = 0;
loop {
let bit = self.decode_bit(&mut probs[symbol as usize]);
symbol = (symbol << 1) | bit;
result |= bit << i;
i += 1;
if symbol >= probs.len() as i32 {
break;
}
}
result
}
/*
/// This was the original function, which can't be optimized well
/// by the x86_64 backend. aarch64 on the other hand optimizes it fine.
pub(crate) fn decode_direct_bits(&mut self, count: u32) -> i32 {
let mut result = 0;
for _ in 0..count {
self.normalize();
self.range >>= 1;
let t = (self.code.wrapping_sub(self.range)) >> 31;
self.code -= self.range & (t.wrapping_sub(1));
result = (result << 1) | (1u32.wrapping_sub(t));
}
result as _
}
*/
pub(crate) fn decode_direct_bits(&mut self, count: u32) -> i32 {
#[cfg(all(feature = "optimization", target_arch = "aarch64"))]
{
if count > 0 {
return self.decode_direct_bits_aarch64(count);
}
}
#[cfg(all(feature = "optimization", target_arch = "x86_64"))]
{
if count > 0 {
return self.decode_direct_bits_x86_64(count);
}
}
// The following loop is the original function structured in a way,
// that hopefully the compiler can optimize better.
let mut result = 0;
let mut count = count;
'outer: loop {
// Fast Path
while self.range >= 0x0100_0000 {
if count == 0 {
break 'outer;
}
count -= 1;
self.range >>= 1;
let t = self.code.wrapping_sub(self.range) >> 31;
self.code -= self.range & t.wrapping_sub(1);
result = (result << 1) | (1 - t);
}
if count == 0 {
break 'outer;
}
// Slow Path
let b = self.inner.read_u8() as u32;
self.code = (self.code << SHIFT_BITS) | b;
self.range <<= SHIFT_BITS;
}
result as _
}
#[cfg(all(feature = "optimization", target_arch = "aarch64"))]
#[inline(always)]
fn decode_direct_bits_aarch64(&mut self, count: u32) -> i32 {
// Safety: It is critical that we clamp the reading from the buffer inside it bounds.
// We also give the "nostack, readonly, pure" guarantees that we must not (and are not)
// violate.
unsafe {
let mut result: i32 = 0;
let mut pos = self.inner.pos;
let buf = self.inner.buf.as_slice();
let buf_ptr = buf.as_ptr();
let limit = buf.len() - 1;
core::arch::asm!(r#"
// Setup constants
mov {top_value_reg:w}, #{top_value}
2:
// Calculate result = result << 1
lsl {result:w}, {result:w}, #1
// Then, calculate the value for "bit == 1" case
orr {result_bit1:w}, {result:w}, #1
// Normalize if range is below the top value
cmp {range:w}, {top_value_reg:w}
b.hs 3f
lsl {code:w}, {code:w}, #{shift_bits}
lsl {range:w}, {range:w}, #{shift_bits}
// To prevent reading past the buffer, we clamp the read index
cmp {pos}, {limit}
csel {clamped_pos}, {limit}, {pos}, hi
// Read byte and update code using indexed addressing
ldrb {tmp:w}, [{buf_ptr}, {clamped_pos}]
orr {code:w}, {code:w}, {tmp:w}
add {pos}, {pos}, #1
3:
// Halve the range and check if code < new_range
// using a subtraction and flags
lsr {range:w}, {range:w}, #1
subs {tmp:w}, {code:w}, {range:w}
// Use CSEL to update code and result without branching
csel {code:w}, {tmp:w}, {code:w}, hs
csel {result:w}, {result_bit1:w}, {result:w}, hs
// Decrement loop counter and loop
subs {count:w}, {count:w}, #1
b.ne 2b
"#,
// Main state registers (inputs and outputs)
range = inout(reg) self.range,
code = inout(reg) self.code,
pos = inout(reg) pos,
count = inout(reg) count => _,
result = inout(reg) result,
// Read-only inputs
buf_ptr = in(reg) buf_ptr,
limit = in(reg) limit,
// Scratch registers
top_value_reg = out(reg) _,
clamped_pos = out(reg) _,
result_bit1 = out(reg) _,
tmp = out(reg) _,
// Constants
top_value = const 0x0100_0000,
shift_bits = const SHIFT_BITS,
// Compiler hints
options(nostack, readonly, pure)
);
// We clamp to the size of the buffer because `pos == buf.len()` signals
// that there is nothing more to read.
self.inner.pos = pos.min(buf.len());
result
}
}
#[cfg(all(feature = "optimization", target_arch = "x86_64"))]
#[inline(always)]
fn decode_direct_bits_x86_64(&mut self, count: u32) -> i32 {
// Safety: It is critical that we clamp the reading from the buffer inside it bounds.
// We also give the "nostack, readonly, pure" guarantees that we must not (and are not)
// violate.
unsafe {
let mut result: i32 = 0;
let mut pos = self.inner.pos;
let buf = &self.inner.buf;
let buf_ptr = buf.as_ptr();
let limit = buf.len() - 1;
core::arch::asm!(r#"
2:
// First, calculate result = result << 1
shl {result:e}, 1
// Then, calculate the value for "bit == 1" case
lea {result_bit1:e}, [{result:e} + 1]
// Normalize if range is below the top value
cmp {range:e}, {top_value}
jae 3f
shl {code:e}, {shift_bits}
shl {range:e}, {shift_bits}
// To prevent reading past the buffer, clamp the read index
mov {clamped_pos}, {pos}
cmp {clamped_pos}, {limit}
cmovg {clamped_pos}, {limit}
// Read byte and update code
movzx {tmp_byte:e}, byte ptr [{buf_ptr} + {clamped_pos}]
or {code:e}, {tmp_byte:e}
inc {pos}
3:
// Halve the range and check if code < new_range
// using a subtraction and the sign flag (SF).
shr {range:e}, 1
mov {tmp_code:e}, {code:e}
sub {code:e}, {range:e}
// Use CMOV to update code and result without branching
cmovs {code:e}, {tmp_code:e}
cmovns {result:e}, {result_bit1:e}
// Decrement loop counter and loop
dec {count:e}
jnz 2b
"#,
// Main state registers (inputs and outputs)
range = inout(reg) self.range,
code = inout(reg) self.code,
pos = inout(reg) pos,
count = inout(reg) count => _,
result = inout(reg) result,
// Read-only inputs
buf_ptr = in(reg) buf_ptr,
limit = in(reg) limit,
// Scratch registers for temporaries
tmp_code = out(reg) _,
result_bit1 = out(reg) _,
clamped_pos = out(reg) _,
tmp_byte = out(reg) _,
// Constants
top_value = const 0x0100_0000,
shift_bits = const SHIFT_BITS,
// Compiler hints
options(nostack, readonly, pure)
);
// We clamp to the size of the buffer because `pos == buf.len()` signals
// that there is nothing more to read.
self.inner.pos = pos.min(buf.len());
result
}
}
pub(crate) fn prepare<R: Read>(&mut self, mut decoder: R, len: usize) -> crate::Result<()> {
if len < 5 {
return Err(error_invalid_input("buffer len must >= 5"));
}
let b = decoder.read_u8()?;
if b != 0x00 {
return Err(error_invalid_input("first byte is not 0"));
}
self.code = decoder.read_u32()?;
self.range = 0xFFFFFFFFu32;
let len = len - 5;
let pos = self.inner.buf.len() - len;
let end = pos + len;
self.inner.pos = pos;
decoder.read_exact(&mut self.inner.buf[pos..end])
}
#[inline]
pub(crate) fn is_finished(&self) -> bool {
self.inner.pos == self.inner.buf.len() && self.code == 0
}
}