unityrs-testkit 1.0.0

Synthetic Unity files built in code, for unityrs's own tests and the CLI's test hooks; not a stable API. Never game data.
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
//! The fuzz targets' input layouts (`fuzz/`, the fuzz plan of
//! `docs/plans/core.md` section 6), in one place: the targets read their
//! inputs through these, and the seed command (`examples/fuzz_seeds.rs`)
//! writes the builders' files, trees, objects and blocks through them, so
//! the two cannot drift.
//!
//! - [`TreeCase`]: a typetree and the bytes of one value, for the targets
//!   that read and write values (`boost_read`, `python_read`,
//!   `write_after_read`). The rows are what the readers and the tree
//!   compiler read of a node (level, meta flag, type, name), so a mutation
//!   of a type name or a level is one byte away, not an offset into a
//!   string buffer.
//! - [`blob_case`]: a stored typetree, the bytes `TypeTreeNode.parse_blob`
//!   or `TypeTreeNode.parse` read, for the `typetree` target.
//! - [`lz4_case`]: one LZ4 block and its declared size, for the `lz4`
//!   target.
//! - [`TextureCase`]: a `Texture2D`'s fields, the meter its decode runs
//!   under and its data, for the `texture` target.
//! - [`MeshCase`]: a Mesh's or a Sprite's value, its file's version and
//!   byte order, its resource and the meter, for the `meshdecode` target.
//! - [`ShaderCase`]: a shader program blob, its Unity version and the meter,
//!   for the `shader` target.
//! - [`anim_humanoid_cases`]: [`SceneCase`] humanoid rigs, for the
//!   `anim_humanoid` target.
//!
//! Every decoder here takes any bytes: a field the input does not reach is
//! empty (a row, a reference, the data), never an error.

mod anim;
mod humanoid;
mod scene;
pub use anim::{anim_clip_cases, anim_gltf_cases};
pub use humanoid::anim_humanoid_cases;
pub use scene::scene_cases;

/// A synthetic serialized scene and strict export profile for the 3D targets.
/// Layout: meter and flags (one byte each), a little-endian u16 profile
/// length, that many profile bytes, then the serialized file to the end.
/// Flag 1 selects a prefab graph, flag 2 the `CorePbr` mapper. Nonzero meters
/// also run the export under `meter² × 64` bytes.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct SceneCase {
    /// The operation's additional small-meter selector; zero runs only full.
    pub meter: u8,
    /// Graph and material policy bits.
    pub flags: u8,
    /// Strict profile JSON; empty means the default profile.
    pub profile: Vec<u8>,
    /// A serialized file, with embedded hand-built trees in the seeds.
    pub data: Vec<u8>,
}
impl SceneCase {
    /// Encode the profile before the mutable scene bytes.
    #[must_use]
    pub fn encode(&self) -> Vec<u8> {
        let len = self.profile.len().min(usize::from(u16::MAX));
        let mut out = vec![self.meter, self.flags];
        out.extend_from_slice(&u16::try_from(len).unwrap_or(u16::MAX).to_le_bytes());
        out.extend_from_slice(&self.profile[..len]);
        out.extend_from_slice(&self.data);
        out
    }
    /// Decode arbitrary bytes; a truncated profile retains only its prefix.
    #[must_use]
    pub fn decode(input: &[u8]) -> Self {
        let mut case = Self {
            meter: input.first().copied().unwrap_or(0),
            flags: input.get(1).copied().unwrap_or(0),
            ..Self::default()
        };
        if let Some(header) = input.get(2..4) {
            let len = usize::from(u16::from_le_bytes([header[0], header[1]]));
            let end = 4usize.saturating_add(len).min(input.len());
            case.profile = input[4..end].to_vec();
            case.data = input[end..].to_vec();
        }
        case
    }
}

/// A typetree row: what the readers and the compiler read of a node.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Row {
    /// `m_Level`.
    pub level: u8,
    /// `m_MetaFlag` (`0x4000` aligns).
    pub meta_flag: i32,
    /// `m_Type`.
    pub ty: Vec<u8>,
    /// `m_Name`.
    pub name: Vec<u8>,
}

impl Row {
    /// A row of `level`, `ty` and `name`, with meta flag `meta_flag`.
    #[must_use]
    pub fn new(level: u8, ty: &[u8], name: &[u8], meta_flag: i32) -> Self {
        Self {
            level,
            meta_flag,
            ty: ty.to_vec(),
            name: name.to_vec(),
        }
    }
}

/// A ref type: its class, namespace and assembly, and its tree, if stored.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct RefType {
    /// `m_ClassName`.
    pub class: Vec<u8>,
    /// `m_NameSpace`.
    pub namespace: Vec<u8>,
    /// `m_AssemblyName`.
    pub assembly: Vec<u8>,
    /// The stored tree; `None` is a ref type with none.
    pub rows: Option<Vec<Row>>,
}

/// A tree, the ref types it may reach, and the bytes of one value.
///
/// Layout: `flags` (a byte of [`TreeCase`]'s bits), `start` (an `i8`), the
/// rows, the count of ref types (a byte) and each ref type, then the value's
/// bytes, which run to the end. Rows are a `u16` count (little-endian) and
/// each row's level (a byte), meta flag (an `i32`, little-endian), type and
/// name; a string is a byte of length and its bytes. A ref type is its
/// class, namespace and assembly, a byte whose low bit says a tree follows,
/// and that tree's rows.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct TreeCase {
    /// The bits below.
    pub flags: u8,
    /// Where the pure-Python reader starts, from the start of the data.
    pub start: i8,
    /// The value's tree.
    pub rows: Vec<Row>,
    /// The file's ref types, in order.
    pub refs: Vec<RefType>,
    /// The value's bytes.
    pub data: Vec<u8>,
}

impl TreeCase {
    /// The data is big-endian.
    pub const BIG_ENDIAN: u8 = 1;
    /// The file has no `ref_types` (format below 20), whatever `refs` holds.
    pub const REFS_ABSENT: u8 = 2;
    /// There is no file at all, whatever `refs` holds (wins over
    /// [`Self::REFS_ABSENT`]).
    pub const REFS_NO_FILE: u8 = 4;
    /// The pure-Python reader reads by the stream reader's rules (a file
    /// loaded from a path).
    pub const STREAM: u8 = 8;
    /// Float32 signalling NaNs keep their bits.
    pub const LOSSLESS: u8 = 16;
    /// `write_after_read` reads with the pure-Python reader, not
    /// UnityPyBoost's.
    pub const PYTHON: u8 = 32;
    /// The run bounds memory at the fuzz crate's small bound
    /// (`SMALL_MEMORY` in `fuzz/src/lib.rs`), which a read of many small
    /// values reaches before the work bound, not at the large one, which
    /// no value read reaches. Without it the code that grows a charged
    /// buffer at the memory bound never runs in the value targets.
    pub const SMALL_MEMORY: u8 = 64;
    /// With [`Self::STREAM`], the stream reader is backed by `io.BytesIO`,
    /// where a negative read size reads to the end.
    pub const BYTES_IO: u8 = 128;

    /// Whether `flags` holds `bit`.
    #[must_use]
    pub fn has(&self, bit: u8) -> bool {
        self.flags & bit != 0
    }

    /// The case's bytes.
    #[must_use]
    pub fn encode(&self) -> Vec<u8> {
        let mut out = vec![self.flags, self.start.to_le_bytes()[0]];
        put_rows(&mut out, &self.rows);
        let refs = &self.refs[..self.refs.len().min(usize::from(u8::MAX))];
        out.push(u8::try_from(refs.len()).unwrap_or(u8::MAX));
        for r in refs {
            put_str(&mut out, &r.class);
            put_str(&mut out, &r.namespace);
            put_str(&mut out, &r.assembly);
            match &r.rows {
                Some(rows) => {
                    out.push(1);
                    put_rows(&mut out, rows);
                }
                None => out.push(0),
            }
        }
        out.extend_from_slice(&self.data);
        out
    }

    /// The case `input` holds; what it does not reach is empty.
    #[must_use]
    pub fn decode(input: &[u8]) -> Self {
        let mut c = Cursor(input);
        let mut case = Self {
            flags: c.u8().unwrap_or(0),
            start: c.u8().map_or(0, |b| i8::from_le_bytes([b])),
            ..Self::default()
        };
        let Some(rows) = c.rows() else {
            return case;
        };
        case.rows = rows;
        let Some(n) = c.u8() else {
            return case;
        };
        for _ in 0..n {
            let Some(r) = c.ref_type() else {
                return case;
            };
            case.refs.push(r);
        }
        case.data = c.0.to_vec();
        case
    }
}

/// The `typetree` target's input: the format (a byte), a byte whose low bit
/// says big-endian, then the stored tree.
#[must_use]
pub fn blob_case(format: u8, big_endian: bool, tree: &[u8]) -> Vec<u8> {
    let mut out = vec![format, u8::from(big_endian)];
    out.extend_from_slice(tree);
    out
}

/// The `lz4` target's input: the declared size (a `u32`, little-endian),
/// then the block.
#[must_use]
pub fn lz4_case(declared: u32, block: &[u8]) -> Vec<u8> {
    let mut out = declared.to_le_bytes().to_vec();
    out.extend_from_slice(block);
    out
}

/// A `Texture2D`'s fields, the meter its decode runs under and its data,
/// for the `texture` target (`unityrs-texture`'s `select` and `decode`).
///
/// Layout: `m_TextureFormat`, `m_Width`, `m_Height` and the platform, each
/// an `i32`, little-endian; the meter (a byte); the platform blob, a byte of
/// length ([`Self::NO_BLOB`] for none) and its bytes; then the data, which
/// runs to the end. An input that stops inside the header is the default
/// case, and one that stops inside the blob keeps the header alone.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct TextureCase {
    /// `m_TextureFormat`.
    pub format: i32,
    /// `m_Width`.
    pub width: i32,
    /// `m_Height`.
    pub height: i32,
    /// The platform of the file that holds it (a `BuildTarget`).
    pub platform: i32,
    /// The meter, by its low two bits: 0 is the fuzz memory bound; 1, 2
    /// and 3 the decode's charge less 1, the charge, and the charge plus 1.
    pub meter: u8,
    /// `m_PlatformBlob`, at most 254 bytes, or none.
    pub blob: Option<Vec<u8>>,
    /// The image data, mip 0 first.
    pub data: Vec<u8>,
}

impl TextureCase {
    /// The blob length that says there is no blob.
    pub const NO_BLOB: u8 = u8::MAX;

    /// The case's bytes.
    #[must_use]
    pub fn encode(&self) -> Vec<u8> {
        let mut out = Vec::new();
        for v in [self.format, self.width, self.height, self.platform] {
            out.extend_from_slice(&v.to_le_bytes());
        }
        out.push(self.meter);
        match &self.blob {
            Some(b) => {
                let b = &b[..b.len().min(usize::from(Self::NO_BLOB - 1))];
                out.push(u8::try_from(b.len()).unwrap_or(0));
                out.extend_from_slice(b);
            }
            None => out.push(Self::NO_BLOB),
        }
        out.extend_from_slice(&self.data);
        out
    }

    /// The case `input` holds; what it does not reach is empty.
    #[must_use]
    pub fn decode(input: &[u8]) -> Self {
        let mut c = Cursor(input);
        let (Some(format), Some(width), Some(height), Some(platform), Some(meter)) =
            (c.i32(), c.i32(), c.i32(), c.i32(), c.u8())
        else {
            return Self::default();
        };
        let mut case = Self {
            format,
            width,
            height,
            platform,
            meter,
            ..Self::default()
        };
        case.blob = match c.u8() {
            None => return case,
            Some(Self::NO_BLOB) => None,
            Some(n) => match c.take(usize::from(n)) {
                Some(b) => Some(b.to_vec()),
                None => return case,
            },
        };
        case.data = c.0.to_vec();
        case
    }
}

fn put_str(out: &mut Vec<u8>, s: &[u8]) {
    let s = &s[..s.len().min(usize::from(u8::MAX))];
    out.push(u8::try_from(s.len()).unwrap_or(u8::MAX));
    out.extend_from_slice(s);
}

fn put_rows(out: &mut Vec<u8>, rows: &[Row]) {
    let rows = &rows[..rows.len().min(usize::from(u16::MAX))];
    out.extend_from_slice(&u16::try_from(rows.len()).unwrap_or(u16::MAX).to_le_bytes());
    for r in rows {
        out.push(r.level);
        out.extend_from_slice(&r.meta_flag.to_le_bytes());
        put_str(out, &r.ty);
        put_str(out, &r.name);
    }
}

/// A Mesh's or a Sprite's value, the version and byte order its file has,
/// the bytes its `m_StreamData` reads and the meter, for the `meshdecode`
/// target (`unityrs-meshdecode`'s `MeshHandler`).
///
/// Layout: the flags (a byte of [`MeshCase`]'s bits), the meter (a byte),
/// the version (major, minor and build, each a `u16`, little-endian, then
/// the type and its number, a byte each), the resource (a `u16` of length,
/// little-endian, and its bytes), then the value, a [`TreeCase`], which runs
/// to the end. An input that stops inside the header is the default case,
/// and one that stops inside the resource keeps the header alone.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct MeshCase {
    /// The bits below.
    pub flags: u8,
    /// The meter: 0 runs the handler under the case's limits alone; any
    /// other value runs it again under a meter of `meter² × 64` bytes.
    pub meter: u8,
    /// The version's major, minor and build.
    pub version: [u16; 3],
    /// The version's type (a `UnityVersionType` byte, any value).
    pub version_type: u8,
    /// The number after the type.
    pub version_number: u8,
    /// What a resource read returns, at most 65,535 bytes.
    pub resource: Vec<u8>,
    /// The value's tree and bytes.
    pub value: TreeCase,
}

impl MeshCase {
    /// The value is a Sprite's (its `m_RD` is the source), not a Mesh's.
    pub const SPRITE: u8 = 1;
    /// The file is big-endian (the handler swaps the vertex data's bytes).
    pub const BIG_ENDIAN: u8 = 2;
    /// The handler has a resource reader (`MeshHandler::process`'s
    /// `Resources`), returning [`Self::resource`].
    pub const RESOURCES: u8 = 4;

    /// Whether `flags` holds `bit`.
    #[must_use]
    pub fn has(&self, bit: u8) -> bool {
        self.flags & bit != 0
    }

    /// The case's bytes.
    #[must_use]
    pub fn encode(&self) -> Vec<u8> {
        let mut out = vec![self.flags, self.meter];
        for v in self.version {
            out.extend_from_slice(&v.to_le_bytes());
        }
        out.extend_from_slice(&[self.version_type, self.version_number]);
        let r = &self.resource[..self.resource.len().min(usize::from(u16::MAX))];
        out.extend_from_slice(&u16::try_from(r.len()).unwrap_or(u16::MAX).to_le_bytes());
        out.extend_from_slice(r);
        out.extend_from_slice(&self.value.encode());
        out
    }

    /// The case `input` holds; what it does not reach is empty.
    #[must_use]
    pub fn decode(input: &[u8]) -> Self {
        let mut c = Cursor(input);
        let (Some(flags), Some(meter), Some(major), Some(minor), Some(build)) =
            (c.u8(), c.u8(), c.u16(), c.u16(), c.u16())
        else {
            return Self::default();
        };
        let (Some(version_type), Some(version_number)) = (c.u8(), c.u8()) else {
            return Self::default();
        };
        let mut case = Self {
            flags,
            meter,
            version: [major, minor, build],
            version_type,
            version_number,
            ..Self::default()
        };
        let Some(resource) = c.u16().and_then(|n| c.take(usize::from(n))) else {
            return case;
        };
        case.resource = resource.to_vec();
        case.value = TreeCase::decode(c.0);
        case
    }
}

/// A shader program blob and the Unity version selecting its entry table.
///
/// Layout: major and minor version, each a little-endian `u32`, the meter
/// selector (one byte), then the blob through the end. A header cut short
/// decodes to the default case.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ShaderCase {
    /// Unity's major and minor version (the table changes at 2019.3).
    pub version: (u32, u32),
    /// 0 uses the fuzz memory bound; another value uses `meter² × 64` bytes.
    pub meter: u8,
    /// The little-endian shader program blob.
    pub blob: Vec<u8>,
}

impl ShaderCase {
    /// The case's bytes.
    #[must_use]
    pub fn encode(&self) -> Vec<u8> {
        let mut out = self.version.0.to_le_bytes().to_vec();
        out.extend_from_slice(&self.version.1.to_le_bytes());
        out.push(self.meter);
        out.extend_from_slice(&self.blob);
        out
    }

    /// The case `input` holds; a missing header is the default case.
    #[must_use]
    pub fn decode(input: &[u8]) -> Self {
        let mut c = Cursor(input);
        let (Some(major), Some(minor), Some(meter)) = (c.u32(), c.u32(), c.u8()) else {
            return Self::default();
        };
        Self {
            version: (major, minor),
            meter,
            blob: c.0.to_vec(),
        }
    }
}

/// The bytes not yet read.
struct Cursor<'a>(&'a [u8]);

impl Cursor<'_> {
    fn take(&mut self, n: usize) -> Option<&[u8]> {
        let (head, rest) = self.0.split_at_checked(n)?;
        self.0 = rest;
        Some(head)
    }

    fn u8(&mut self) -> Option<u8> {
        self.take(1)?.first().copied()
    }

    fn u16(&mut self) -> Option<u16> {
        Some(u16::from_le_bytes(self.take(2)?.try_into().ok()?))
    }

    fn i32(&mut self) -> Option<i32> {
        Some(i32::from_le_bytes(self.take(4)?.try_into().ok()?))
    }

    fn u32(&mut self) -> Option<u32> {
        Some(u32::from_le_bytes(self.take(4)?.try_into().ok()?))
    }

    fn str(&mut self) -> Option<Vec<u8>> {
        let n = self.u8()?;
        Some(self.take(usize::from(n))?.to_vec())
    }

    fn rows(&mut self) -> Option<Vec<Row>> {
        let n = u16::from_le_bytes(self.take(2)?.try_into().ok()?);
        let mut rows = Vec::new();
        for _ in 0..n {
            let level = self.u8()?;
            let meta_flag = i32::from_le_bytes(self.take(4)?.try_into().ok()?);
            let ty = self.str()?;
            let name = self.str()?;
            rows.push(Row {
                level,
                meta_flag,
                ty,
                name,
            });
        }
        Some(rows)
    }

    fn ref_type(&mut self) -> Option<RefType> {
        let class = self.str()?;
        let namespace = self.str()?;
        let assembly = self.str()?;
        let rows = if self.u8()? & 1 == 1 {
            Some(self.rows()?)
        } else {
            None
        };
        Some(RefType {
            class,
            namespace,
            assembly,
            rows,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::{MeshCase, RefType, Row, TextureCase, TreeCase, blob_case, lz4_case};

    fn case() -> TreeCase {
        TreeCase {
            flags: TreeCase::BIG_ENDIAN | TreeCase::PYTHON,
            start: -3,
            rows: vec![
                Row::new(0, b"Base", b"Base", 0),
                Row::new(1, b"int", b"x", 0x4000),
            ],
            refs: vec![
                RefType {
                    class: b"A".to_vec(),
                    namespace: b"n".to_vec(),
                    assembly: b"a".to_vec(),
                    rows: Some(vec![Row::new(0, b"A", b"Base", 0)]),
                },
                RefType::default(),
            ],
            data: vec![1, 2, 3, 4],
        }
    }

    #[test]
    fn a_case_decodes_to_what_was_encoded() {
        let c = case();
        assert_eq!(TreeCase::decode(&c.encode()), c);
        assert!(c.has(TreeCase::PYTHON) && !c.has(TreeCase::STREAM));
    }

    #[test]
    fn a_cut_case_keeps_what_it_reaches_and_empties_the_rest() {
        let c = case();
        let bytes = c.encode();
        // Every cut decodes, and past the rows and the ref types only the
        // data is cut.
        for n in 0..bytes.len() {
            let d = TreeCase::decode(&bytes[..n]);
            assert!(d.data.len() <= c.data.len());
        }
        let cut = TreeCase::decode(&bytes[..bytes.len() - 1]);
        assert_eq!((cut.rows, cut.refs), (c.rows.clone(), c.refs.clone()));
        assert_eq!(cut.data, [1, 2, 3]);
        let rows_only = TreeCase::decode(&bytes[..bytes.len() - 20]);
        assert_eq!(rows_only.rows, c.rows);
        assert!(rows_only.refs.is_empty() && rows_only.data.is_empty());
        assert_eq!(TreeCase::decode(&[]), TreeCase::default());
    }

    #[test]
    fn long_strings_and_lists_are_cut_to_what_their_lengths_hold() {
        let c = TreeCase {
            rows: vec![Row::new(0, &[b'x'; 300], b"Base", 0)],
            ..TreeCase::default()
        };
        let d = TreeCase::decode(&c.encode());
        assert_eq!(d.rows[0].ty.len(), 255);
        assert_eq!(d.rows[0].name, b"Base");
    }

    #[test]
    fn a_texture_case_decodes_to_what_was_encoded_and_a_cut_one_to_less() {
        let c = TextureCase {
            format: 25,
            width: -3,
            height: 16384,
            platform: 38,
            meter: 2,
            blob: Some(vec![0; 12]),
            data: vec![1, 2, 3],
        };
        let bytes = c.encode();
        assert_eq!(bytes.len(), 17 + 1 + 12 + 3);
        assert_eq!(TextureCase::decode(&bytes), c);
        let none = TextureCase {
            blob: None,
            ..c.clone()
        };
        assert_eq!(TextureCase::decode(&none.encode()), none);
        // Cut in the header: the default; in the blob: the header alone.
        assert_eq!(TextureCase::decode(&bytes[..16]), TextureCase::default());
        let header = TextureCase::decode(&bytes[..20]);
        assert_eq!(
            (header.width, header.blob, header.data),
            (-3, None, Vec::new())
        );
        assert_eq!(TextureCase::decode(&bytes[..31]).data, [1]);
    }

    #[test]
    fn a_mesh_case_decodes_to_what_was_encoded_and_a_cut_one_to_less() {
        let c = MeshCase {
            flags: MeshCase::SPRITE | MeshCase::RESOURCES,
            meter: 9,
            version: [2019, 4, 40],
            version_type: 3,
            version_number: 1,
            resource: vec![5; 3],
            value: case(),
        };
        let bytes = c.encode();
        assert_eq!(bytes.len(), 10 + 2 + 3 + c.value.encode().len());
        assert_eq!(MeshCase::decode(&bytes), c);
        assert!(c.has(MeshCase::SPRITE) && !c.has(MeshCase::BIG_ENDIAN));
        // Cut in the header: the default; in the resource: the header alone;
        // in the value: the value as far as it reaches.
        assert_eq!(MeshCase::decode(&bytes[..9]), MeshCase::default());
        let header = MeshCase::decode(&bytes[..13]);
        assert_eq!(
            (header.version, header.resource, header.value),
            ([2019, 4, 40], Vec::new(), TreeCase::default())
        );
        let cut = MeshCase::decode(&bytes[..bytes.len() - 1]);
        assert_eq!((cut.resource, cut.value.data), (vec![5; 3], vec![1, 2, 3]));
    }

    #[test]
    fn the_blob_and_lz4_cases_put_their_header_first() {
        assert_eq!(blob_case(19, true, &[9]), [19, 1, 9]);
        assert_eq!(lz4_case(0x0102_0304, &[7]), [4, 3, 2, 1, 7]);
    }
}