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
use super::*;
/// Construction helpers for `ZstdFseTable`.
impl ZstdFseTable {
/// Builds a 1-state constant RLE FSE table that always outputs `symbol` consuming 0 bits.
///
/// # Arguments
///
/// - `u8` - Constant symbol emitted on every step.
///
/// # Returns
///
/// - `Self` - Single-entry RLE FSE table.
#[must_use]
pub(crate) fn from_rle(symbol: u8) -> Self {
Self {
accuracy_log: 0,
entries: vec![ZstdFseEntry::new(symbol, 0, 0)],
}
}
/// Builds a flat FSE decoding table from a normalized RFC 8878 probability distribution.
///
/// # Arguments
///
/// - `&[i16]` - Normalized probability counts (`-1` means less-than-1 probability).
/// - `u8` - Table accuracy log (`0..=9`).
///
/// # Returns
///
/// - `Result<Self, String>` - Ready flat FSE decoding table or distribution error.
pub(crate) fn from_distribution(probs: &[i16], accuracy_log: u8) -> Result<Self, String> {
let table_size: usize = 1usize << usize::from(accuracy_log);
let table_mask: usize = table_size - 1;
let step: usize = (table_size >> 1) + (table_size >> 3) + 3;
let mut high_threshold: usize = table_size - 1;
let mut symbols: Vec<u8> = vec![0u8; table_size];
let mut symbol_next: Vec<u16> = vec![0u16; probs.len()];
let mut total_prob: usize = 0;
for (sym, &prob) in probs.iter().enumerate() {
if prob == -1 {
if high_threshold >= table_size {
return Err(ERR_BLEND_ZSTD_FSE.to_string());
}
symbols[high_threshold] = sym as u8;
high_threshold = high_threshold.wrapping_sub(1);
symbol_next[sym] = 1;
total_prob += 1;
} else if prob > 0 {
symbol_next[sym] = prob as u16;
total_prob += prob as usize;
}
}
if total_prob != table_size {
return Err(ERR_BLEND_ZSTD_FSE.to_string());
}
let mut pos: usize = 0;
for (sym, &prob) in probs.iter().enumerate() {
if prob <= 0 {
continue;
}
for _ in 0..(prob as usize) {
symbols[pos] = sym as u8;
loop {
pos = (pos + step) & table_mask;
if high_threshold == usize::MAX || pos <= high_threshold {
break;
}
}
}
}
if pos != 0 {
return Err(ERR_BLEND_ZSTD_FSE.to_string());
}
let mut entries: Vec<ZstdFseEntry> = Vec::with_capacity(table_size);
for &sym_u8 in symbols.iter() {
let sym: usize = usize::from(sym_u8);
let next_state: u16 = symbol_next[sym];
if next_state == 0 {
return Err(ERR_BLEND_ZSTD_FSE.to_string());
}
symbol_next[sym] = next_state.saturating_add(1);
let high_bit: u8 = (15u32.saturating_sub(next_state.leading_zeros())) as u8;
let num_bits: u8 = accuracy_log.saturating_sub(high_bit);
let baseline_full: usize =
(usize::from(next_state) << usize::from(num_bits)).saturating_sub(table_size);
entries.push(ZstdFseEntry::new(sym_u8, num_bits, baseline_full as u16));
}
Ok(Self {
accuracy_log,
entries,
})
}
}
/// Construction helpers for `ZstdFrameState`.
impl ZstdFrameState {
/// Creates fresh per-frame decoder state with RFC 8878 initial repeat offsets `[1, 4, 8]`.
///
/// # Returns
///
/// - `Self` - Initialized per-frame Zstandard decoder state.
#[must_use]
pub(crate) fn new_frame() -> Self {
Self {
huffman: None,
ll_table: None,
of_table: None,
ml_table: None,
repeat_offsets: ZSTD_INITIAL_REPEAT_OFFSETS,
}
}
}
/// Reverse bitstream reader primitives for RFC 8878 Huffman and FSE decoding.
impl<'a> ZstdReverseBitReader<'a> {
/// Initializes a reverse bitstream reader by locating the mandatory sentinel `1` bit in the final byte.
///
/// # Arguments
///
/// - `&'a [u8]` - Compressed bitstream slice terminated with a sentinel `1` bit.
///
/// # Returns
///
/// - `Result<Self, String>` - Initialized reverse bit reader or framing error.
pub(crate) fn new(data: &'a [u8]) -> Result<Self, String> {
let last: u8 = *data
.last()
.ok_or_else(|| ERR_BLEND_ZSTD_TRUNCATED.to_string())?;
if last == 0 {
return Err(ERR_BLEND_ZSTD_FSE.to_string());
}
let padding_bits: usize = (last.leading_zeros() as usize) + 1;
let total_bits: usize = data.len().saturating_mul(8).saturating_sub(padding_bits);
Ok(Self {
data,
total_bits,
bits_consumed: 0,
})
}
/// Returns the number of unread bits remaining (`0` if exact end or overflowed).
///
/// # Returns
///
/// - `usize` - Remaining unread bit count.
#[must_use]
pub(crate) fn bits_remaining(&self) -> usize {
self.get_total_bits()
.saturating_sub(self.get_bits_consumed())
}
/// Returns `true` when consumption has passed `total_bits` (RFC 8878 `BIT_DStream_overflow`).
///
/// # Returns
///
/// - `bool` - Whether the reader has overflowed past bit 0.
#[must_use]
pub(crate) fn is_overflow(&self) -> bool {
self.get_bits_consumed() > self.get_total_bits()
}
/// Peeks `num_bits` MSB-first bits (`0..=32`), zero-padding past bit 0 when fewer bits remain.
///
/// # Arguments
///
/// - `u8` - Number of bits to peek (`0..=32`).
///
/// # Returns
///
/// - `u32` - Peeked bits aligned to the least-significant `num_bits` positions.
#[must_use]
pub(crate) fn peek_bits(&self, num_bits: u8) -> u32 {
let count: usize = usize::from(num_bits);
if count == 0 {
return 0;
}
let consumed: usize = self.get_bits_consumed();
let total: usize = self.get_total_bits();
let bytes: &[u8] = self.get_data();
let mut acc: u32 = 0;
for step in 0..count {
acc <<= 1;
let bit_from_top: usize = consumed + step;
if bit_from_top < total {
let bit_index: usize = total - 1 - bit_from_top;
let byte_val: u8 = bytes[bit_index >> 3];
let bit_val: u32 = u32::from((byte_val >> (bit_index & 7)) & 1);
acc |= bit_val;
}
}
acc
}
/// Consumes and returns `num_bits` MSB-first bits (`0..=32`), zero-padding past bit 0 and recording overflow if past `total_bits`.
///
/// # Arguments
///
/// - `u8` - Number of bits to read (`0..=32`).
///
/// # Returns
///
/// - `u32` - Read bit value.
pub(crate) fn read_bits(&mut self, num_bits: u8) -> u32 {
let val: u32 = self.peek_bits(num_bits);
let next: usize = self
.get_bits_consumed()
.saturating_add(usize::from(num_bits));
let _: &mut Self = self.set_bits_consumed(next);
val
}
/// Consumes `num_bits` bits after peeking.
///
/// # Arguments
///
/// - `u8` - Number of bits to advance.
pub(crate) fn consume_bits(&mut self, num_bits: u8) {
let next: usize = self
.get_bits_consumed()
.saturating_add(usize::from(num_bits));
let _: &mut Self = self.set_bits_consumed(next);
}
}