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
354
355
356
357
358
359
360
361
362
363
//! Streaming LZFSE decoder.
//!
//! Buffers input until a whole block (magic + header + payload) can be
//! decoded, then drains the decoded payload into the caller's output slice
//! across as many `decode` calls as the caller needs.
use alloc::vec::Vec;
use crate::error::Error;
use crate::lzfse::{lzfse_v2, lzvn};
use crate::traits::{RawDecoder, RawProgress};
/// 4-byte block magics.
const MAGIC_UNCOMPRESSED: [u8; 4] = *b"bvx-";
const MAGIC_LZVN: [u8; 4] = *b"bvxn";
const MAGIC_V1: [u8; 4] = *b"bvx1";
const MAGIC_V2: [u8; 4] = *b"bvx2";
const MAGIC_EOS: [u8; 4] = *b"bvx$";
/// Streaming decoder state machine.
pub struct Decoder {
/// Bytes the caller has fed us that we haven't yet consumed.
input_buf: Vec<u8>,
/// Decoded bytes pending delivery to the caller.
output_buf: Vec<u8>,
/// Read cursor into `output_buf`. We keep the buffer around so we don't
/// have to shift bytes on every partial drain; once `output_pos ==
/// output_buf.len()`, we clear both.
output_pos: usize,
/// State.
state: State,
/// Once we hit the end-of-stream marker (or have signalled it once), we
/// short-circuit further calls.
eos: bool,
/// Set on any decode error so callers don't accidentally resume.
poisoned: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum State {
/// Waiting for the next 4-byte block magic.
AwaitMagic,
/// Read magic; waiting for the block-specific header bytes.
AwaitHeader(BlockKind),
/// Header parsed; waiting for the rest of the payload, then decode + drain.
AwaitPayload {
kind: BlockKind,
/// For uncompressed blocks: bytes to copy. For LZVN: compressed bytes
/// to decode.
payload_len: usize,
/// For LZVN: expected decoded size from the header.
decoded_size: usize,
},
/// Stream is finished.
Done,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum BlockKind {
Uncompressed,
Lzvn,
/// `bvx2` returns Unsupported once we've parsed its header far enough
/// to know we hit it; this variant exists so the state machine can
/// surface that decision uniformly with the other block kinds.
V2,
V1,
}
impl Decoder {
pub fn new() -> Self {
Self {
input_buf: Vec::new(),
output_buf: Vec::new(),
output_pos: 0,
state: State::AwaitMagic,
eos: false,
poisoned: false,
}
}
fn raw_decode_inner(&mut self, input: &[u8], output: &mut [u8]) -> Result<RawProgress, Error> {
if self.poisoned {
return Err(Error::Corrupt);
}
let mut consumed = 0usize;
let mut written = 0usize;
loop {
// 1. Drain any pending decoded output first.
if self.output_pos < self.output_buf.len() {
let want = (self.output_buf.len() - self.output_pos).min(output.len() - written);
output[written..written + want]
.copy_from_slice(&self.output_buf[self.output_pos..self.output_pos + want]);
self.output_pos += want;
written += want;
if self.output_pos == self.output_buf.len() {
// Fully drained; reset.
self.output_buf.clear();
self.output_pos = 0;
}
if written == output.len() {
return Ok(RawProgress {
consumed,
written,
done: false,
});
}
// If we just drained and output still has room, loop to
// try to make more progress.
}
// 2. If we've already hit end-of-stream, signal done.
if self.eos {
return Ok(RawProgress {
consumed,
written,
done: true,
});
}
// 3. Pull from caller's `input` into `input_buf`. We pull lazily:
// only as much as the current state needs.
if consumed < input.len() {
self.input_buf.extend_from_slice(&input[consumed..]);
consumed = input.len();
}
// 4. Advance the state machine.
match self.state {
State::AwaitMagic => {
if self.input_buf.len() < 4 {
return Ok(RawProgress {
consumed,
written,
done: false,
});
}
let mut magic = [0u8; 4];
magic.copy_from_slice(&self.input_buf[..4]);
// Drop the magic.
self.input_buf.drain(..4);
match magic {
MAGIC_EOS => {
self.state = State::Done;
self.eos = true;
// loop to emit done on next iteration
}
MAGIC_UNCOMPRESSED => {
self.state = State::AwaitHeader(BlockKind::Uncompressed);
}
MAGIC_LZVN => {
self.state = State::AwaitHeader(BlockKind::Lzvn);
}
MAGIC_V1 => {
self.state = State::AwaitHeader(BlockKind::V1);
}
MAGIC_V2 => {
self.state = State::AwaitHeader(BlockKind::V2);
}
_ => {
self.poisoned = true;
return Err(Error::BadHeader);
}
}
}
State::AwaitHeader(kind) => match kind {
BlockKind::Uncompressed => {
// 4-byte LE n_raw_bytes.
if self.input_buf.len() < 4 {
return Ok(RawProgress {
consumed,
written,
done: false,
});
}
let n_raw = u32::from_le_bytes([
self.input_buf[0],
self.input_buf[1],
self.input_buf[2],
self.input_buf[3],
]) as usize;
self.input_buf.drain(..4);
self.state = State::AwaitPayload {
kind: BlockKind::Uncompressed,
payload_len: n_raw,
decoded_size: n_raw,
};
}
BlockKind::Lzvn => {
// 8-byte header: n_raw_bytes (u32 LE) + n_payload_bytes (u32 LE).
if self.input_buf.len() < 8 {
return Ok(RawProgress {
consumed,
written,
done: false,
});
}
let n_raw = u32::from_le_bytes([
self.input_buf[0],
self.input_buf[1],
self.input_buf[2],
self.input_buf[3],
]) as usize;
let n_payload = u32::from_le_bytes([
self.input_buf[4],
self.input_buf[5],
self.input_buf[6],
self.input_buf[7],
]) as usize;
self.input_buf.drain(..8);
self.state = State::AwaitPayload {
kind: BlockKind::Lzvn,
payload_len: n_payload,
decoded_size: n_raw,
};
}
BlockKind::V2 => {
// We don't decode v2 in this build, but we need to
// skip past the block cleanly so callers don't
// confuse "block we can't decode" with "garbage".
// Parse the n_payload_bytes field from the header.
if self.input_buf.len() < lzfse_v2::V2_HEADER_FIXED_BYTES {
return Ok(RawProgress {
consumed,
written,
done: false,
});
}
// We *could* skip past the v2 block, but the spec is
// explicit that the encoder may mix block types
// freely. Returning Unsupported here is the
// documented behaviour for v2 in this build.
self.poisoned = true;
return Err(Error::Unsupported);
}
BlockKind::V1 => {
self.poisoned = true;
return Err(Error::Unsupported);
}
},
State::AwaitPayload {
kind,
payload_len,
decoded_size,
} => {
if self.input_buf.len() < payload_len {
return Ok(RawProgress {
consumed,
written,
done: false,
});
}
match kind {
BlockKind::Uncompressed => {
// Copy payload_len bytes into output_buf for drain.
self.output_buf
.extend_from_slice(&self.input_buf[..payload_len]);
self.input_buf.drain(..payload_len);
self.state = State::AwaitMagic;
}
BlockKind::Lzvn => {
// Decode in one shot into output_buf.
//
// Bound the capacity hint by what the payload could
// plausibly produce so an attacker-controlled
// `decoded_size` (n_raw_bytes) cannot force a huge
// up-front allocation (DoS / OOM): a single 1-byte
// LZVN opcode expands to at most ~16 output bytes.
// `decode_block` still enforces the real output size
// against `decoded_size`, so under-hinting only makes
// the Vec grow as actual bytes are produced.
let capacity_hint =
decoded_size.min(payload_len.saturating_mul(16).saturating_add(64));
let mut block_out = Vec::with_capacity(capacity_hint);
if let Err(e) = lzvn::decode_block(
&self.input_buf[..payload_len],
payload_len,
decoded_size,
&mut block_out,
) {
self.poisoned = true;
return Err(e);
}
self.output_buf.append(&mut block_out);
self.input_buf.drain(..payload_len);
self.state = State::AwaitMagic;
}
BlockKind::V2 | BlockKind::V1 => {
// Unreachable — header step would have errored.
self.poisoned = true;
return Err(Error::Unsupported);
}
}
}
State::Done => {
self.eos = true;
return Ok(RawProgress {
consumed,
written,
done: true,
});
}
}
}
}
}
impl Default for Decoder {
fn default() -> Self {
Self::new()
}
}
impl RawDecoder for Decoder {
fn raw_decode(&mut self, input: &[u8], output: &mut [u8]) -> Result<RawProgress, Error> {
self.raw_decode_inner(input, output)
}
fn raw_finish(&mut self, output: &mut [u8]) -> Result<RawProgress, Error> {
// finish drains any pending output and, if the stream has reached
// the end-of-stream marker, returns `done`. Otherwise we surface
// an UnexpectedEnd to signal truncation.
if self.poisoned {
return Err(Error::Corrupt);
}
let p = self.raw_decode_inner(&[], output)?;
if p.done {
return Ok(p);
}
// No more input is coming. If we haven't seen the EOS marker but
// we have nothing buffered and nothing pending, treat as
// unexpected-end. If we still have decoded bytes to drain, signal
// OutputFull-style (done=false, written>0).
if p.written > 0 || !self.output_buf.is_empty() {
return Ok(p);
}
if self.state == State::AwaitMagic && self.input_buf.is_empty() {
// No partial block in flight. Empty input followed by finish on
// a fresh decoder is fine — return StreamEnd.
self.eos = true;
return Ok(RawProgress {
consumed: 0,
written: 0,
done: true,
});
}
// Mid-block at EOI — truncated.
self.poisoned = true;
Err(Error::UnexpectedEnd)
}
fn raw_reset(&mut self) {
self.input_buf.clear();
self.output_buf.clear();
self.output_pos = 0;
self.state = State::AwaitMagic;
self.eos = false;
self.poisoned = false;
}
}