lzfse_rust 0.2.1

A pure Rust LZFSE library.
Documentation
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
use crate::base::MagicBytes;
use crate::error::Error;
use crate::lmd::{self, Lmd};
use crate::ops::{PatchInto, Skip, WriteShort};
use crate::test_utils;
use crate::types::Idx;

use test_kit::{Rng, Seq};

use super::backend::VnBackend;
use super::block::VnBlock;
use super::constants::*;
use super::object::Vn;
use super::vn_core::VnCore;

use std::io;

// A series of tests designed to validate VN block encoding/ decoding. Although VN opcode
// encoding/ decoding code is also stressed, this is covered comprehensively by it's own unit tests.

/// Test buddy.
#[derive(Default)]
struct Buddy {
    backend: VnBackend,
    enc: Vec<u8>,
    dec: Vec<u8>,
}

impl Buddy {
    fn encode_lmds(&mut self, literals: &[u8], lmds: &[Lmd<Vn>]) -> io::Result<(u32, u32)> {
        test_utils::encode_lmds(&mut self.enc, &mut self.backend, literals, lmds)
    }

    fn decode(&mut self) -> crate::Result<(u32, u32)> {
        self.dec.clear();
        let mut src = self.enc.as_slice();
        let mut block = VnBlock::default();
        let n_header_bytes = block.load(src)?;
        src.skip(n_header_bytes as usize);
        let mut core = VnCore::from(block);
        let n_payload_bytes = core.decode(&mut self.dec, &mut src)?;
        let n_raw_bytes = self.dec.len() as u32;
        Ok((n_header_bytes + n_payload_bytes, n_raw_bytes))
    }

    fn decode_n(&mut self, n: u32) -> crate::Result<(u32, u32)> {
        self.dec.clear();
        let mut src = self.enc.as_slice();
        let mut block = VnBlock::default();
        let n_header_bytes = block.load(src)?;
        src.skip(n_header_bytes as usize);
        let mut core = VnCore::from(block);
        while core.decode_n(&mut self.dec, &mut src, n)? {}
        let n_payload_bytes = self.enc.len() as u32;
        let n_raw_bytes = self.dec.len() as u32;
        Ok((n_payload_bytes, n_raw_bytes))
    }

    fn check_encode_decode(&mut self, literals: &[u8], lmds: &[Lmd<Vn>]) -> crate::Result<bool> {
        let (e_raw_bytes, e_payload_bytes) = self.encode_lmds(literals, lmds)?;
        let (d_payload_bytes, d_raw_bytes) = self.decode()?;
        Ok(e_raw_bytes == d_raw_bytes
            && e_payload_bytes == d_payload_bytes
            && self.check_lmds(literals, lmds))
    }

    fn check_encode_decode_n(
        &mut self,
        literals: &[u8],
        lmds: &[Lmd<Vn>],
        n: u32,
    ) -> crate::Result<bool> {
        let (e_raw_bytes, e_payload_bytes) = self.encode_lmds(literals, lmds)?;
        let (d_payload_bytes, d_raw_bytes) = self.decode_n(n)?;
        Ok(e_raw_bytes == d_raw_bytes
            && e_payload_bytes == d_payload_bytes
            && self.check_lmds(literals, lmds))
    }

    fn mutate_n_raw_bytes(&mut self, delta: i32) -> crate::Result<bool> {
        let mut block = VnBlock::default();
        block.load(&self.enc)?;
        let n_raw_bytes = (block.n_raw_bytes() as i32 + delta) as u32;
        let n_payload_bytes = block.n_payload_bytes();
        if let Ok(block) = VnBlock::new(n_raw_bytes, n_payload_bytes) {
            let bytes = self.enc.patch_into(Idx::default(), VN_HEADER_SIZE as usize);
            block.store(bytes);
            Ok(true)
        } else {
            Ok(false)
        }
    }

    fn mutate_n_payload_bytes(&mut self, delta: i32) -> crate::Result<bool> {
        let mut block = VnBlock::default();
        block.load(&self.enc)?;
        let n_raw_bytes = block.n_raw_bytes();
        let n_payload_bytes = (block.n_payload_bytes() as i32 + delta) as u32;
        if let Ok(block) = VnBlock::new(n_raw_bytes, n_payload_bytes) {
            let bytes = self.enc.patch_into(Idx::default(), VN_HEADER_SIZE as usize);
            block.store(bytes);
            Ok(true)
        } else {
            Ok(false)
        }
    }

    fn check_lmds(&self, literals: &[u8], lmds: &[Lmd<Vn>]) -> bool {
        test_utils::check_lmds(&self.dec, literals, lmds)
    }
}

// Quote.
#[test]
fn quote() -> crate::Result<()> {
    let bytes = b"Full fathom five thy father lies; \
                 Of his bones are coral made; \
                 Those are pearls that were his eyes: \
                 Nothing of him that doth fade; \
                 But doth suffer a sea-change; \
                 Into something rich and strange."; // William Shakespeare. The Tempest.
    let mut buddy = Buddy::default();
    let mut lmds = Vec::default();
    lmd::split_lmd(&mut lmds, bytes.len() as u32, 0, 1);
    assert!(buddy.check_encode_decode(bytes.as_ref(), &lmds)?);
    Ok(())
}

// Incremental literal len.
#[test]
#[ignore = "expensive"]
fn literals() -> crate::Result<()> {
    let bytes = Seq::default().take(0x1_0000).collect::<Vec<_>>();
    let mut buddy = Buddy::default();
    let mut lmds = Vec::default();
    for literal_len in 1..bytes.len() {
        lmds.clear();
        lmd::split_lmd(&mut lmds, literal_len as u32, 0, 1);
        assert!(buddy.check_encode_decode(&bytes[..literal_len], &lmds)?);
    }
    Ok(())
}

// Small literal len, match len and match distance.
#[test]
#[ignore = "expensive"]
fn matches_1() -> crate::Result<()> {
    let bytes = Seq::default().take(0x0100).collect::<Vec<_>>();
    let mut buddy = Buddy::default();
    let mut lmds = Vec::default();
    for literal_len in 1..bytes.len() {
        for match_len in 3..literal_len as u32 {
            for match_distance in 1..literal_len as u32 {
                lmds.clear();
                lmd::split_lmd(&mut lmds, literal_len as u32, match_len, match_distance);
                assert!(buddy.check_encode_decode(&bytes[..literal_len], &lmds)?);
            }
        }
    }
    Ok(())
}

// Small match len, all match distance.
#[test]
#[ignore = "expensive"]
fn matches_2() -> crate::Result<()> {
    let bytes = Seq::default().take(0x1_0000).collect::<Vec<_>>();
    let mut buddy = Buddy::default();
    let mut lmds = Vec::default();
    for match_len in 3..0x40 {
        for match_distance in 1..=0xFFFF {
            let literal_len = match_distance;
            lmds.clear();
            lmd::split_lmd(&mut lmds, literal_len, match_len, match_distance);
            assert!(buddy.check_encode_decode(&bytes[..literal_len as usize], &lmds)?);
        }
    }
    Ok(())
}

// Coarse match len, all match distance.
#[test]
#[ignore = "expensive"]
fn matches_3() -> crate::Result<()> {
    let bytes = Seq::default().take(0x1_0000).collect::<Vec<_>>();
    let mut buddy = Buddy::default();
    let mut lmds = Vec::default();
    for match_len in (0x40..0x400).step_by(0x10) {
        for match_distance in 1..=0xFFFF {
            let literal_len = match_distance;
            lmds.clear();
            lmd::split_lmd(&mut lmds, literal_len, match_len, match_distance);
            assert!(buddy.check_encode_decode(&bytes[..literal_len as usize], &lmds)?);
        }
    }
    Ok(())
}

// Random LMD generation.
#[test]
#[ignore = "expensive"]
#[allow(clippy::unnecessary_cast)]
fn fuzz_lmd() -> crate::Result<()> {
    let bytes = Seq::default().take(0x8_0000).collect::<Vec<_>>();
    let mut buddy = Buddy::default();
    let mut lmds = Vec::default();
    for i in 0..0x8000 {
        let mut rng = Rng::new(i);
        lmds.clear();
        lmds.push(Lmd::new(1, 0, 1));
        let mut index = 1;
        let mut n_raw_bytes = index as u32;
        loop {
            let l = ((rng.gen() & 0x0000_FFFF) * (MAX_L_VALUE as u32 + 1)) >> 16;
            let m = ((rng.gen() & 0x0000_FFFF) * (MAX_M_VALUE as u32 + 1)) >> 16;
            let d = ((rng.gen() & 0x0000_FFFF) * (MAX_D_VALUE as u32 + 1)) >> 16;
            if bytes.len() < index + l as usize {
                break;
            }
            let m = m.max(3);
            let d = d.clamp(1, n_raw_bytes);
            lmds.push(Lmd::new(l, m, d));
            index += l as usize;
            n_raw_bytes += m;
        }
        assert!(buddy.check_encode_decode(&bytes[..index as usize], &lmds)?);
    }
    Ok(())
}

// Random LMD generation with n decoding.
#[test]
#[ignore = "expensive"]
#[allow(clippy::unnecessary_cast)]
fn fuzz_lmd_n() -> crate::Result<()> {
    let bytes = Seq::default().take(0x8_0000).collect::<Vec<_>>();
    let mut buddy = Buddy::default();
    let mut lmds = Vec::default();
    for i in 0..0x8000 {
        let mut rng = Rng::new(i);
        lmds.clear();
        lmds.push(Lmd::new(1, 0, 1));
        let mut index = 1;
        let mut n_raw_bytes = index as u32;
        loop {
            let l = ((rng.gen() & 0x0000_FFFF) * (MAX_L_VALUE as u32 + 1)) >> 16;
            let m = ((rng.gen() & 0x0000_FFFF) * (MAX_M_VALUE as u32 + 1)) >> 16;
            let d = ((rng.gen() & 0x0000_FFFF) * (MAX_D_VALUE as u32 + 1)) >> 16;
            if bytes.len() < index + l as usize {
                break;
            }
            let m = m.max(3);
            let d = d.clamp(1, n_raw_bytes);
            lmds.push(Lmd::new(l, m, d));
            index += l as usize;
            n_raw_bytes += m;
        }
        assert!(buddy.check_encode_decode_n(&bytes[..index as usize], &lmds, 1 + i)?);
    }
    Ok(())
}

// Mutate `n_payload_bytes` +1. We are looking to break the decoder. In all cases the decoder should
// reject invalid data via `Err(error)` and exit gracefully. It should not hang/ segfault/ panic/
// trip debug assertions or break in any other fashion.
#[test]
#[ignore = "expensive"]
fn edge_1() -> crate::Result<()> {
    let bytes = Seq::default().take(VN_PAYLOAD_LIMIT as usize * 2).collect::<Vec<_>>();
    let mut buddy = Buddy::default();
    let mut lmds = Vec::default();
    for literal_len in 0..bytes.len() {
        lmds.clear();
        lmd::split_lmd(&mut lmds, literal_len as u32, 0, 1);
        buddy.encode_lmds(&bytes[..literal_len], &lmds)?;
        if !buddy.mutate_n_payload_bytes(1)? {
            continue;
        }
        match buddy.decode() {
            Err(Error::PayloadOverflow) => {}
            _ => panic!(),
        }
    }
    Ok(())
}

// Mutate `n_payload_bytes` -1. We are looking to break the decoder. In all cases the decoder should
// reject invalid data via `Err(error)` and exit gracefully. It should not hang/ segfault/ panic/
// trip debug assertions or break in any other fashion.
#[test]
#[ignore = "expensive"]
fn edge_2() -> crate::Result<()> {
    let bytes = Seq::default().take(VN_PAYLOAD_LIMIT as usize * 2).collect::<Vec<_>>();
    let mut buddy = Buddy::default();
    let mut lmds = Vec::default();
    for literal_len in 0..bytes.len() {
        lmds.clear();
        lmd::split_lmd(&mut lmds, literal_len as u32, 0, 1);
        buddy.encode_lmds(&bytes[..literal_len], &lmds)?;
        if !buddy.mutate_n_payload_bytes(-1)? {
            continue;
        }
        match buddy.decode() {
            Err(Error::PayloadUnderflow) => {}
            _ => panic!(),
        }
    }
    Ok(())
}

// Mutate `n_raw_bytes` +1. We are looking to break the decoder. In all cases the decoder should
// reject invalid data via `Err(error)` and exit gracefully. It should not hang/ segfault/ panic/
// trip debug assertions or break in any other fashion.
#[test]
#[ignore = "expensive"]
fn edge_3() -> crate::Result<()> {
    let bytes = Seq::default().take(VN_PAYLOAD_LIMIT as usize * 2).collect::<Vec<_>>();
    let mut buddy = Buddy::default();
    let mut lmds = Vec::default();
    for literal_len in 0..bytes.len() {
        lmds.clear();
        lmd::split_lmd(&mut lmds, literal_len as u32, 0, 1);
        buddy.encode_lmds(&bytes[..literal_len], &lmds)?;
        if !buddy.mutate_n_raw_bytes(1)? {
            continue;
        }
        match buddy.decode() {
            Err(Error::Vn(super::VnErrorKind::BadPayload)) => {}
            _ => panic!(),
        }
    }
    Ok(())
}

// Mutate `n_raw_bytes` -1. We are looking to break the decoder. In all cases the decoder should
// reject invalid data via `Err(error)` and exit gracefully. It should not hang/ segfault/ panic/
// trip debug assertions or break in any other fashion.
#[test]
#[ignore = "expensive"]
fn edge_4() -> crate::Result<()> {
    let bytes = Seq::default().take(VN_PAYLOAD_LIMIT as usize * 2).collect::<Vec<_>>();
    let mut buddy = Buddy::default();
    let mut lmds = Vec::default();
    for literal_len in 0..bytes.len() {
        lmds.clear();
        lmd::split_lmd(&mut lmds, literal_len as u32, 0, 1);
        buddy.encode_lmds(&bytes[..literal_len], &lmds)?;
        if !buddy.mutate_n_raw_bytes(-1)? {
            continue;
        }
        match buddy.decode() {
            Err(Error::Vn(super::VnErrorKind::BadPayload)) => {}
            _ => panic!(),
        }
    }
    Ok(())
}

// Random payload generation with mutations. We are looking to break the decoder. In all cases the
// decoder should reject invalid data via `Err(error)` and exit gracefully. It should not hang/
// segfault/ panic/ trip debug assertions or break in any other fashion.
#[test]
#[ignore = "expensive"]
#[allow(clippy::unnecessary_cast)]
fn mutate_rng_1() -> crate::Result<()> {
    let bytes = Seq::default().take(0x1000).collect::<Vec<_>>();
    let mut buddy = Buddy::default();
    let mut lmds = Vec::default();
    for i in 0..0x1000 {
        let mut rng = Rng::new(i);
        lmds.clear();
        lmds.push(Lmd::new(1, 0, 1));
        let mut index = 1;
        let mut n_raw_bytes = index as u32;
        loop {
            let l = ((rng.gen() & 0x0000_FFFF) * (MAX_L_VALUE as u32 + 1)) >> 16;
            let m = ((rng.gen() & 0x0000_FFFF) * (MAX_M_VALUE as u32 + 1)) >> 16;
            let d = ((rng.gen() & 0x0000_FFFF) * (MAX_D_VALUE as u32 + 1)) >> 16;
            if bytes.len() < index + l as usize {
                break;
            }
            let m = m.max(3);
            let d = d.clamp(1, n_raw_bytes);
            lmds.push(Lmd::new(l, m, d));
            index += l as usize;
            n_raw_bytes += m;
        }
        buddy.encode_lmds(&bytes[..index], &lmds)?;
        for j in 4..buddy.enc.len() {
            buddy.enc[j] = buddy.enc[j].wrapping_add(1);
            let _ = buddy.decode();
            buddy.enc[j] = buddy.enc[j].wrapping_sub(2);
            let _ = buddy.decode();
            buddy.enc[j] = buddy.enc[j].wrapping_add(1);
        }
    }
    Ok(())
}

// Random payload generation with mutations. We are looking to break the decoder. In all cases the
// decoder should reject invalid data via `Err(error)` and exit gracefully. It should not hang/
// segfault/ panic/ trip debug assertions or break in any other fashion.
#[test]
#[ignore = "expensive"]
#[allow(clippy::unnecessary_cast)]
fn mutate_rng_2() -> crate::Result<()> {
    let bytes = Seq::default().take(0x1000).collect::<Vec<_>>();
    let mut buddy = Buddy::default();
    let mut lmds = Vec::default();
    for i in 0..0x1000 {
        let mut rng = Rng::new(i);
        lmds.clear();
        lmds.push(Lmd::new(1, 0, 1));
        let mut index = 1;
        let mut n_raw_bytes = index as u32;
        loop {
            let l = ((rng.gen() & 0x0000_FFFF) * (MAX_L_VALUE as u32 + 1)) >> 16;
            let m = ((rng.gen() & 0x0000_FFFF) * (MAX_M_VALUE as u32 + 1)) >> 16;
            let d = ((rng.gen() & 0x0000_FFFF) * (MAX_D_VALUE as u32 + 1)) >> 16;
            if bytes.len() < index + l as usize {
                break;
            }
            let m = m.max(3);
            let d = d.clamp(1, n_raw_bytes);
            lmds.push(Lmd::new(l, m, d));
            index += l as usize;
            n_raw_bytes += m;
        }
        buddy.encode_lmds(&bytes[..index], &lmds)?;
        for _ in 0..255 {
            for j in 4..buddy.enc.len() {
                buddy.enc[j] = buddy.enc[j].wrapping_add(1);
                let _ = buddy.decode();
            }
        }
    }
    Ok(())
}

// Random noise for payload. We are looking to break the decoder. In all cases the decoder should
// reject invalid data via `Err(error)` and exit gracefully. It should not hang/ segfault/ panic/
// trip debug assertions or break in any other fashion.
#[test]
#[ignore = "expensive"]
fn fuzz_noise() -> crate::Result<()> {
    let mut buddy = Buddy::default();
    for i in 0..0x0100_0000 {
        let mut seq = Seq::new(Rng::new(i));
        buddy.enc.write_short_u32(MagicBytes::Vxn.into())?;
        buddy.enc.resize(0x400, 0);
        for i in 0x0004..0x0400 {
            buddy.enc[i] = seq.next().unwrap();
        }
        let _ = buddy.decode();
    }
    Ok(())
}