unityrs-core 1.0.0

Read and write Unity asset bundles, serialized files and typetrees.
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
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
// Ported from UnityPy 1.25.2 (MIT): UnityPy/helpers/TypeTreeHelper.py, UnityPy/streams/EndianBinaryReader.py. See THIRD_PARTY_LICENSES.
//! UnityPy's pure-Python reader (`helpers/TypeTreeHelper.py:182-361`), for
//! objects with `byte_size == 0`. It starts at `byte_start` in the whole
//! `SerializedFile` and may read on past the object, with Python's reader
//! rules at any position ([`crate::stream`]'s helpers; the position may go
//! negative). **Alignment is relative to the file**, not the object:
//! `align_stream` rounds the absolute position. Its differences from
//! UnityPyBoost are `docs/CANONICAL_DUMP.md` section 7's list: aligned
//! primitive arrays become tuples, with 16-bit signedness swapped; an
//! aligned `SInt8` array raises at every length (`read_byte_array(reader,
//! size)` before any loop), and an array of aligned `TypelessData` raises
//! only when its length is above 0 (`read_bytes()` inside the loop; an empty
//! one reads as `[]`); a negative or out-of-range string
//! length reads as `""`, and a string of length 0 or read as `""` that way
//! is not aligned after (`read_aligned_string` returns before
//! `align_stream`: the base reader's, `streams/EndianBinaryReader.py:146-153`,
//! which `FUNCTION_READ_MAP` holds for a `string` node and a `pair` run's
//! child, and for an array's elements read from bytes the memoryview
//! reader's override, `:266-273`, the same body); in an array whose aligned
//! element is a vector, a negative inner length reads as `[]`, unless the
//! inner element is an aligned primitive, whose `struct` format rejects it
//! (`struct.error`, `other`); arrays of aligned classes align once and skip the
//! registry check; `TypelessData` length -1 reads to the end of the file and
//! other negative lengths follow Python slice semantics (so `bytes_read` can
//! be negative), on the memory reader: a file loaded from a path is read by
//! the stream reader's rules ([`read_with_reader`]), where such a length
//! raises and no read passes the end; a `pair` with three or more children reads its first two,
//! and an `Array` with three or more reads its elements through
//! `m_Children[1]` (`:216`, `:309`), where UnityPyBoost raises both;
//! an aligned `pair` array reads a child whose type is a key of
//! `FUNCTION_READ_MAP` (every primitive, `string`, `TypelessData`) through
//! that function, without the child's own align flag (a non-empty `string`
//! still aligns itself, as `read_aligned_string` does), and any other child
//! (a class, a vector, a `pair`) through `read_value`, which keeps its flag
//! (`TypeTreeHelper.py:285-293`); a `ReferencedObject` reads `type` before anything else (a
//! missing key is `KeyError`, `other`; a `type` with no `class`, `ns` or
//! `asm` is `KeyError` and a non-dict `type` `AttributeError`, `:89-97`, both
//! `other` where UnityPyBoost reports `ref_type`) and raises `SerializedFile has no
//! ref_types` for an empty or absent list *before* the empty-class skip (no
//! `ref_types` attribute is an `AttributeError` whose message the dump maps
//! to `ref_type`); an aligned `pair` element with fewer than two children
//! raises `IndexError` (`other`) at every length, since `m_Children[0]` and
//! `[1]` are read before the loop (`:282-283`), while an empty array of
//! non-aligned malformed `pair`s, or of three-child `pair`s, reads as `[]`
//! (the probes: `CANONICAL_DUMP.md` section 7); likewise an aligned vector
//! element whose `Array` has fewer than two children raises `IndexError` at
//! every length, the empty one included, since `m_Children[0].m_Children[1]`
//! is read before the loop (`:309`), where UnityPyBoost reads an empty one
//! as `[]` (`read_value_array` reads an aligned element's `pair` children
//! and its vector's element before its loop, and indexes everywhere else
//! inside it); outside an array, a vector reads its length, and refuses a
//! negative one, before it indexes its `Array`'s element (`:213-216`), and a
//! `pair` reads its first child before it indexes its second (`:194-195`),
//! so a malformed one fails with whatever those reads raise first (a vector
//! whose `Array` has fewer than two children is `negative_length` at length
//! -1 and `IndexError`, `other`, at 0), where UnityPyBoost checks each arity
//! first and reports `other`: this reader never fails a compiled
//! `BadVector` or `BadPair` on entry; and an
//! aligned `ReferencedObject` array element whose class is empty or whose ref
//! type has no tree raises ([`super::ReadDetail::RefTypeNoTree`]). Each
//! difference is an oracle fixture of package B (plan section 7.3).
//!
//! Owner: package B.

use std::sync::Arc;

use bytes::Bytes;

use super::dict::{Dict, FindError, RefIndex, RefNode, Trees, ref_tree, visit};
use super::{
    FloatMode, Out, ReadCtx, ReadDetail, ReadError, ReadErrorKind, RefTypes, Work, charge_error,
    f32_bits, int, limit_refused, stream_refused, uint,
};
use crate::raw::RawStr;
use crate::stream::{Endian, ReaderKind};
use crate::typetree::{Kind, NodeId, Tree};
use crate::value::{ListIx, Parsed, ReadBy, Value, ValueBuilder};

/// Reads one value from `file` by the memory reader's rules (bytes),
/// starting at `start` (any Python position). `bytes_read` counts from
/// `start` and may be negative. Its work is the open's, counted on
/// `ctx.meter` whatever the outcome (the module docs of [`super`], "Work").
pub fn read(
    file: &Bytes,
    start: i128,
    tree: &Arc<Tree>,
    ctx: &ReadCtx<'_>,
) -> Result<Parsed, ReadError> {
    read_with_reader(file, start, tree, ctx, ReaderKind::Memory)
}

/// [`read`] by the rules of the file's reader: on the stream reader (a file
/// loaded from a path) `start` is a position its `seek` took (never
/// negative), a read stops at the end, a fixed-width read is
/// `unpack(read(n))`, a `TypelessData` length below -1 raises, and an
/// alignment to 2^63 or more raises as the `seek` it makes does
/// ([`crate::stream::ReaderKind`]), so `bytes_read` is never negative.
pub fn read_with_reader(
    file: &Bytes,
    start: i128,
    tree: &Arc<Tree>,
    ctx: &ReadCtx<'_>,
    kind: ReaderKind,
) -> Result<Parsed, ReadError> {
    read_with_mode(file, start, tree, ctx, kind, (false, false))
}

pub(crate) fn read_with_mode(
    file: &Bytes,
    start: i128,
    tree: &Arc<Tree>,
    ctx: &ReadCtx<'_>,
    kind: ReaderKind,
    (head, object_mode): (bool, bool),
) -> Result<Parsed, ReadError> {
    read_with_fields(file, start, tree, ctx, kind, (head, object_mode), None)
}

pub(crate) fn read_with_fields(
    file: &Bytes,
    start: i128,
    tree: &Arc<Tree>,
    ctx: &ReadCtx<'_>,
    kind: ReaderKind,
    (head, object_mode): (bool, bool),
    progress: Option<&mut super::FieldProgress>,
) -> Result<Parsed, ReadError> {
    let work = Work::start(ctx.options.limits, ctx.meter)?;
    let builder =
        ValueBuilder::new(ctx.meter, tree.list().clone()).map_err(|e| charge_error(0, e))?;
    let trees = Trees::new(&builder, tree)?;
    let mut r = Reader {
        data: file,
        bytes: file.as_ref(),
        pos: start,
        start,
        kind,
        head,
        object_mode,
        progress,
        big: ctx.endian == Endian::Big,
        floats: ctx.options.floats,
        ref_types: ctx.ref_types,
        refs: RefIndex::new(ctx.ref_types),
        builder,
        trees,
        work,
        has_registry: false,
    };
    let value = r.value(tree, 0, tree.root());
    let at = r.at();
    let ended = r.work.finish(at);
    let value = value?;
    ended?;
    let built = value.into_built(&r.builder, at)?;
    // UnityPy TypeTreeHelper.py:153: `bytes_read = reader.Position - pos`.
    let read = r.pos.saturating_sub(start);
    let bytes_read = i64::try_from(read).unwrap_or(if read < 0 { i64::MIN } else { i64::MAX });
    let Reader { builder, .. } = r;
    Ok(builder
        .finish(built, bytes_read)
        .with_read_by(ReadBy::Python))
}

/// `EndianBinaryReader_Memoryview` over the whole file
/// (`streams/EndianBinaryReader.py:231-284`), or `_Streamable` (`:287-324`)
/// for a file loaded from a path, and `TypeTreeConfig`
/// (`helpers/TypeTreeHelper.py:78-85`).
#[allow(clippy::struct_excessive_bools)] // Endian, tier, object mode and registry are independent.
struct Reader<'a, 'c, 'p> {
    data: &'a Bytes,
    bytes: &'a [u8],
    /// `reader.Position`: any Python integer on the memory reader (plan
    /// 3.3); never negative on the stream reader.
    pos: i128,
    start: i128,
    /// Which reader's rules.
    kind: ReaderKind,
    /// SF 23+ selects HEAD's aligned byte-array behavior.
    head: bool,
    object_mode: bool,
    progress: Option<&'p mut super::FieldProgress>,
    big: bool,
    floats: FloatMode,
    ref_types: RefTypes<'c>,
    /// The ref types' search, one per read ([`RefIndex`]).
    refs: RefIndex<'c>,
    builder: ValueBuilder,
    trees: Trees,
    work: Work<'c>,
    /// `config.has_registry`.
    has_registry: bool,
}

/// A fixed-width number from its bytes in the file's order.
macro_rules! num {
    ($big:expr, $t:ty, $b:expr) => {
        if $big {
            <$t>::from_be_bytes($b)
        } else {
            <$t>::from_le_bytes($b)
        }
    };
}

// Declared after `num!`, which it reads with.
mod array;

/// A Python exception the reader raises.
#[derive(Clone, Copy)]
enum Py {
    /// `struct.error`: an unpack past the buffer, a negative count.
    Struct(u64),
    /// `IndexError` on a node's `m_Children`.
    Index,
    /// A `TypeError` or `KeyError`/`AttributeError` (kind `other`).
    Other(&'static str),
    /// No Python exception: the open's work passed its allowance.
    Limit(crate::error::LimitError),
}

impl Reader<'_, '_, '_> {
    fn at(&self) -> u64 {
        u64::try_from(self.pos.saturating_sub(self.start)).unwrap_or(0)
    }

    fn fail(&self, kind: ReadErrorKind, detail: ReadDetail) -> ReadError {
        ReadError {
            kind,
            at: self.at(),
            detail,
        }
    }

    fn raise(&self, e: Py) -> ReadError {
        match e {
            // The dump maps none of these messages to a kind of its own.
            Py::Struct(need) => self.fail(
                ReadErrorKind::Other,
                ReadDetail::Eof {
                    need,
                    exception: "error",
                },
            ),
            Py::Index => self.fail(ReadErrorKind::Other, ReadDetail::Python("IndexError")),
            Py::Other(m) => self.fail(ReadErrorKind::Other, ReadDetail::Python(m)),
            Py::Limit(l) => limit_refused(self.at(), l),
        }
    }

    /// `read(size)` by the reader's rules ([`ReaderKind::read`]): the range
    /// it returns, the position moved; the stream reader refuses a size
    /// below -1. A read that takes the position back (the memory reader's
    /// negative size, its -1 past the end) is work the read will repeat
    /// ([`Work::discard`]).
    fn read(&mut self, size: i64) -> Result<std::ops::Range<usize>, ReadError> {
        let (range, next) = self
            .kind
            .read(self.bytes.len(), self.pos, size)
            .map_err(|e| stream_refused(self.at(), e))?;
        if next < self.pos {
            self.work.discard();
        }
        self.pos = next;
        Ok(range)
    }

    /// `unpack(fmt, self.read(N))`, the base class's `read_byte`, `read_int`,
    /// `read_float`... (`EndianBinaryReader.py:93-127`): `FUNCTION_READ_MAP`
    /// holds these base functions (`TypeTreeHelper.py:29-52`), so every
    /// primitive node read through it takes this path. On the memory reader
    /// `read` is a Python slice that moves the position by `N` whatever it
    /// returns, and `unpack` raises unless it has exactly `N` bytes: so at
    /// position `-N` (`view[-N:0]`, empty) it raises where `unpack_from`
    /// reads the last `N` bytes ([`Self::unpack_from`]). On the stream
    /// reader `read` stops at the end.
    fn read_n<const N: usize>(&mut self) -> Result<[u8; N], ReadError> {
        let range = self.read(i64::try_from(N).unwrap_or(i64::MAX))?;
        self.bytes
            .get(range)
            .and_then(|s| <[u8; N]>::try_from(s).ok())
            .ok_or_else(|| self.raise(Py::Struct(N as u64)))
    }

    /// `read(1)` then `unpack` ([`Self::read_n`]).
    fn read1(&mut self) -> Result<u8, ReadError> {
        let [b] = self.read_n::<1>()?;
        Ok(b)
    }

    /// The reader's own `read_int` of `N` bytes, set on the instance by the
    /// `endian` setter (`EndianBinaryReader.py:75-82`, `:335-349`): the
    /// lengths the reader reads with `reader.read_int()` (a vector's, a
    /// string's, a `TypelessData`'s). On the memory reader
    /// `struct.unpack_from(view, Position)`, the position moving on success
    /// only; on the stream reader `unpack(stream.read(N))`
    /// ([`ReaderKind::unpack`]).
    fn unpack_from<const N: usize>(&mut self) -> Result<[u8; N], ReadError> {
        let (at, next) = self.kind.unpack(self.bytes.len(), self.pos, N);
        let b = at
            .and_then(|at| self.bytes.get(at..at.checked_add(N)?))
            .and_then(|s| <[u8; N]>::try_from(s).ok());
        let Some(b) = b else {
            let e = self.raise(Py::Struct(N as u64));
            self.pos = next;
            return Err(e);
        };
        self.pos = next;
        Ok(b)
    }

    /// `reader.read_int()`: the instance's [`Self::unpack_from`].
    fn read_int(&mut self) -> Result<i32, ReadError> {
        let big = self.big;
        Ok(num!(big, i32, self.unpack_from()?))
    }

    /// One frame UnityPy's reader pushes on its way down (plan 3.10,
    /// "Bounds"): a `read_value` or `read_value_array` call, a list or dict
    /// comprehension, the lambda a `pair` array reads a non-primitive child
    /// through. Each counts one level against `max_value_depth`, so the count
    /// is the depth of Python frames UnityPy's reader reaches (less the two
    /// or fewer of its leaf reads, `read_int` and the like). Python raises
    /// `RecursionError` past 1,000 frames less its caller's, so every object
    /// it refuses that way passes `max_value_depth` (512) here first.
    fn frame<R>(
        &mut self,
        f: impl FnOnce(&mut Self) -> Result<R, ReadError>,
    ) -> Result<R, ReadError> {
        self.work.enter(self.at())?;
        let out = f(self);
        self.work.leave();
        out
    }

    /// `align_stream` (`EndianBinaryReader.py:155-156`): Python's floor modulo
    /// on the file-absolute position, assigned through the `Position`
    /// setter, which the stream reader refuses at 2^63 or more
    /// ([`ReaderKind::align`]).
    fn align(&mut self) -> Result<(), ReadError> {
        self.pos = self
            .kind
            .align(self.pos, 4)
            .map_err(|e| stream_refused(self.at(), e))?;
        Ok(())
    }

    /// `FUNCTION_READ_MAP` (`TypeTreeHelper.py:29-52`) for a primitive
    /// kind: the base class's `unpack(fmt, read(n))` ([`Self::read_n`]).
    fn prim(&mut self, kind: Kind) -> Result<Value, ReadError> {
        let big = self.big;
        Ok(match kind {
            Kind::S8 => int(i64::from(self.read1()?.cast_signed())),
            Kind::U8 => int(i64::from(self.read1()?)),
            Kind::Bool => Value::Bool(self.read1()? != 0),
            Kind::S16 => int(i64::from(num!(big, i16, self.read_n()?))),
            Kind::U16 => int(i64::from(num!(big, u16, self.read_n()?))),
            Kind::S32 => int(i64::from(num!(big, i32, self.read_n()?))),
            Kind::U32 => int(i64::from(num!(big, u32, self.read_n()?))),
            Kind::S64 => int(num!(big, i64, self.read_n()?)),
            Kind::U64 => uint(num!(big, u64, self.read_n()?)),
            // `struct.unpack('f')` widens as UnityPyBoost does (probed: a
            // signalling NaN comes back quiet).
            Kind::F32 => Value::F32(f32_bits(num!(big, u32, self.read_n()?), self.floats)),
            Kind::F64 => Value::F64(num!(big, u64, self.read_n()?)),
            _ => return Err(self.raise(Py::Other("not a primitive"))),
        })
    }

    /// `read_aligned_string` (`EndianBinaryReader.py:146-153`, the base
    /// reader's, which `FUNCTION_READ_MAP` holds, and for an array's elements
    /// read from bytes the memoryview reader's override, `:266-273`, the same
    /// body): a length of 0, or one that is negative or past the end, is `""`
    /// and does not align.
    fn string(&mut self) -> Result<Value, ReadError> {
        let len = self.read_int()?;
        let room = i128::try_from(self.bytes.len())
            .unwrap_or(i128::MAX)
            .saturating_sub(self.pos);
        if len > 0 && i128::from(len) <= room {
            let range = self.read(i64::from(len))?;
            let s = RawStr::from_shared(self.data.slice(range));
            self.align()?;
            return Ok(Value::Str(s));
        }
        Ok(Value::Str(RawStr::default()))
    }

    /// `read_byte_array` (`EndianBinaryReader.py:158-159`): `read(read_int())`:
    /// 0 is empty and -1 reads to the end; on the memory reader a Python
    /// slice, so any other negative length moves the position back; on the
    /// stream reader one below -1 raises (`ValueError` "read length must be
    /// non-negative or -1") and a read past the end stops there.
    fn typeless(&mut self) -> Result<Value, ReadError> {
        let len = self.read_int()?;
        let range = self.read(i64::from(len))?;
        Ok(Value::Bytes(self.data.slice(range)))
    }

    fn value(&mut self, t: &Arc<Tree>, lx: ListIx, node: NodeId) -> Result<Out, ReadError> {
        if self.progress.as_ref().is_some_and(|p| p.error.is_some()) {
            return Ok(Out::Plain(Value::Int(0)));
        }
        let at = self.at();
        self.work.enter(at)?;
        let out = self.value_inner(t, lx, node);
        self.work.leave();
        self.recover(out)
    }

    fn recover(&mut self, out: Result<Out, ReadError>) -> Result<Out, ReadError> {
        match (out, &mut self.progress) {
            (Err(error), Some(progress)) => progress.recover(error),
            (out, _) => out,
        }
    }

    fn child(t: &Tree, node: NodeId, i: usize) -> Result<NodeId, Py> {
        t.list().children(node).get(i).copied().ok_or(Py::Index)
    }

    /// The vector's `Array` child, when the node reads as one: its first
    /// child's `m_Type` is `"Array"` (`TypeTreeHelper.py:208`, `:306`).
    fn array_child(t: &Tree, node: NodeId) -> Option<NodeId> {
        let first = *t.list().children(node).first()?;
        (t.py_kind(first) == Kind::Array).then_some(first)
    }

    /// `read_value` (`TypeTreeHelper.py:182-263`).
    fn value_inner(&mut self, t: &Arc<Tree>, lx: ListIx, node: NodeId) -> Result<Out, ReadError> {
        self.work.values(1, self.at())?;
        let mut align = t.info(node).is_some_and(|i| i.align);
        let kind = t.py_kind(node);
        let out = if kind.prim_size().is_some() {
            Out::Plain(self.prim(kind)?)
        } else if kind == Kind::Str {
            Out::Plain(self.string()?)
        } else if kind == Kind::Bytes {
            Out::Plain(self.typeless()?)
        } else if kind == Kind::Pair {
            // `:193-196`: the first child is read before the second is indexed.
            let a = Self::child(t, node, 0).map_err(|e| self.raise(e))?;
            let first = self.value(t, lx, a)?;
            let second = match Self::child(t, node, 1) {
                Ok(b) => self.value(t, lx, b)?,
                Err(error) => {
                    let error = self.raise(error);
                    self.recover(Err(error))?;
                    return self.tuple([first]);
                }
            };
            self.tuple(vec_of2(first, second))?
        } else if kind == Kind::ReferencedObject {
            self.ref_object(t, lx, node, false)?
        } else if let Some(array) = Self::array_child(t, node) {
            // `:208-220`.
            align |= t.info(array).is_some_and(|i| i.align);
            let size = self.read_int()?;
            let Ok(count) = usize::try_from(size) else {
                return Err(self.fail(
                    ReadErrorKind::NegativeLength,
                    ReadDetail::NegativeLength(i64::from(size)),
                ));
            };
            let elem = Self::child(t, array, 1).map_err(|e| self.raise(e))?;
            if t.info(elem).is_some_and(|i| i.align) {
                self.array(t, lx, elem, i64::from(size))?
            } else {
                // `[read_value(subtype, ...) for _ in range(size)]`: a frame.
                self.frame(|r| r.list(t, lx, elem, count))?
            }
        } else {
            self.class(t, lx, node)?
        };
        if align {
            self.align()?;
        }
        Ok(out)
    }

    fn tuple<const N: usize>(&mut self, items: [Out; N]) -> Result<Out, ReadError> {
        let at = self.at();
        let mut v = self.builder.vec();
        v.reserve_exact(N).map_err(|e| charge_error(at, e))?;
        for item in items {
            item.push_to(&mut v).map_err(|e| charge_error(at, e))?;
        }
        let built = self.builder.tuple(v).map_err(|e| charge_error(at, e))?;
        Ok(Out::Built(built))
    }

    fn remaining(&self) -> usize {
        let len = i128::try_from(self.bytes.len()).unwrap_or(i128::MAX);
        usize::try_from(len.saturating_sub(self.pos).max(0)).unwrap_or(usize::MAX)
    }

    /// The class branch of `read_value` (`TypeTreeHelper.py:222-231`): children in order, a
    /// `ManagedReferencesRegistry` skipped once one is in scope.
    fn class(&mut self, t: &Arc<Tree>, lx: ListIx, node: NodeId) -> Result<Out, ReadError> {
        self.dict(t, lx, node, true)
    }

    /// An aligned class element's `{child.m_Name: read_value(child) ...}`
    /// (`TypeTreeHelper.py:316-318`), a dict comprehension and so a frame: no registry check.
    fn plain_class(&mut self, t: &Arc<Tree>, lx: ListIx, node: NodeId) -> Result<Out, ReadError> {
        self.frame(|r| r.dict(t, lx, node, false))
    }

    /// A class's dict, grown as its children are read ([`Dict`]): no pass
    /// over them first (review round 7, as in UnityPyBoost's reader).
    fn dict(
        &mut self,
        t: &Arc<Tree>,
        lx: ListIx,
        node: NodeId,
        registry: bool,
    ) -> Result<Out, ReadError> {
        let at = self.at();
        let kids = t.list().children(node);
        let is_registry = |c: NodeId| registry && t.py_kind(c) == Kind::ManagedReferencesRegistry;
        let dup = t.info(node).is_some_and(|i| i.dup_names);
        let mut d = Dict::new(
            &self.builder,
            kids.len(),
            dup && self.progress.is_none(),
            at,
        )?;
        let outer = self.has_registry;
        for c in kids {
            visit();
            if is_registry(*c) {
                if self.has_registry {
                    // A skipped child counts as a value (plan 3.10, "Bounds").
                    self.work.skipped(self.at())?;
                    continue;
                }
                // `config = config.copy(); config.has_registry = True`: for
                // the rest of this class only.
                self.has_registry = true;
            }
            let v = self.value(t, lx, *c)?;
            let (key, slot) = t.info(*c).map_or((*c, 0), |i| (i.key, i.slot));
            let at = self.at();
            d.set(
                &mut self.work,
                if self.progress.is_some() { *c } else { key },
                slot,
                v,
                at,
            )?;
            if self.progress.as_ref().is_some_and(|p| p.error.is_some()) {
                break;
            }
        }
        self.has_registry = outer;
        if self.object_mode
            && self.progress.is_none()
            && t.list().type_name(node).starts_with(b"PPtr<")
        {
            self.work
                .open
                .steps(kids.len())
                .map_err(|e| limit_refused(self.at(), e))?;
            let has = |name: &[u8]| {
                kids.iter().any(|&c| {
                    if registry {
                        crate::walk::write::cleans_to(t.list().name(c), name)
                    } else {
                        t.list().name(c) == name
                    }
                })
            };
            if !has(b"m_FileID") || !has(b"m_PathID") {
                return Err(self.raise(Py::Other(if !registry {
                    "TypeError"
                } else if !has(b"m_FileID") {
                    "KeyError: m_FileID"
                } else {
                    "KeyError: m_PathID"
                })));
            }
            if !registry
                && kids
                    .iter()
                    .any(|&c| !matches!(t.list().name(c), b"m_FileID" | b"m_PathID"))
            {
                return Err(self.raise(Py::Other("TypeError")));
            }
        }
        let result = d.finish(&self.builder, lx, self.at())?;
        if let Some(progress) = &mut self.progress {
            progress.finish_class();
        }
        Ok(result)
    }

    /// A `ReferencedObject` (`TypeTreeHelper.py:197-206`), or an aligned array's element
    /// (`:294-304`, `in_array`), where a ref type with no node is read as
    /// `read_value(None)` and raises. Its dict grows as its children are
    /// read and keeps each name's position ([`Dict`]), and its `type` is the
    /// entry of the first child named `type` read so far, as in the Boost
    /// reader: no pass over its children first (review round 7).
    fn ref_object(
        &mut self,
        t: &Arc<Tree>,
        lx: ListIx,
        node: NodeId,
        in_array: bool,
    ) -> Result<Out, ReadError> {
        let at = self.at();
        let kids = t.list().children(node);
        let mut d = Dict::new(&self.builder, kids.len(), true, at)?;
        d.preserve_fields(self.progress.is_some());
        // The slot of the children named `type`, once one is visited.
        let mut type_slot = None;
        let mut object_type = false;
        // The current `type`'s resolution, kept until a child sets `type`
        // again, as the Boost reader keeps it.
        let mut resolved: Option<Option<RefNode>> = None;
        for c in kids {
            visit();
            let (key, slot) = t.info(*c).map_or((*c, 0), |i| (i.key, i.slot));
            if type_slot.is_none() && t.info(*c).is_some() && t.list().name(*c) == b"type" {
                type_slot = Some(slot);
            }
            if t.list().name(*c) == b"type" {
                object_type = self.object_mode && t.py_kind(*c) != Kind::ReferencedObject;
            }
            let v = if t.py_kind(*c) == Kind::ReferencedObjectData {
                let node = if let Some(r) = &resolved {
                    r.clone()
                } else {
                    let ty = type_slot
                        .and_then(|s| d.position(s))
                        .and_then(|p| d.entries.as_slice().get(p))
                        .map(|(_, v)| v);
                    let found = match self.ref_node(ty, object_type) {
                        Ok(found) => found,
                        Err(error) => {
                            if let Some(progress) = &mut self.progress {
                                progress.recover(error)?;
                                break;
                            }
                            return Err(error);
                        }
                    };
                    resolved.insert(found).clone()
                };
                match (node, in_array) {
                    (Some(RefNode::Tree(rt)), _) => {
                        let at = self.at();
                        let rlx = self.trees.index(&mut self.builder, &rt, at)?;
                        self.value(&rt, rlx, rt.root())?
                    }
                    (None | Some(RefNode::NoTree), false) => {
                        // A skipped child counts as a value (plan 3.10, "Bounds").
                        self.work.skipped(self.at())?;
                        continue;
                    }
                    (None | Some(RefNode::NoTree), true) => {
                        let error = self.fail(ReadErrorKind::Other, ReadDetail::RefTypeNoTree);
                        if let Some(progress) = &mut self.progress {
                            progress.recover(error)?;
                            break;
                        }
                        return Err(error);
                    }
                }
            } else {
                self.value(t, lx, *c)?
            };
            let at = self.at();
            d.set(
                &mut self.work,
                if self.progress.is_some() { *c } else { key },
                slot,
                v,
                at,
            )?;
            if self.progress.as_ref().is_some_and(|p| p.error.is_some()) {
                break;
            }
            if Some(slot) == type_slot {
                resolved = None;
            }
        }
        let result = d.finish(&self.builder, lx, self.at())?;
        if let Some(progress) = &mut self.progress {
            progress.finish_class();
        }
        Ok(result)
    }

    /// `get_ref_type_node` (`TypeTreeHelper.py:88-109`) on the dict read so
    /// far: `type` first (`KeyError`), then its `class`, `ns` and `asm`
    /// (`KeyError`, or `AttributeError` when `type` is not a dict), then
    /// `ref_types` (absent or empty: `ref_type`), then the empty-class skip,
    /// then the scan.
    fn ref_node(
        &mut self,
        ty: Option<&Value>,
        object_type: bool,
    ) -> Result<Option<RefNode>, ReadError> {
        let Some(ty) = ty else {
            return Err(self.raise(Py::Other("KeyError: 'type'")));
        };
        let Value::Dict(m) = ty else {
            return Err(self.raise(Py::Other("AttributeError: no attribute 'class'")));
        };
        let at = self.at();
        let mut field = |name: &'static [u8], msg: &'static str| match self.trees.field(
            m,
            name,
            &mut self.work.open,
            object_type,
        ) {
            Ok(Some(v)) => Ok(v),
            Ok(None) if object_type => Err(Py::Other("AttributeError")),
            Ok(None) => Err(Py::Other(msg)),
            Err(l) => Err(Py::Limit(l)),
        };
        let fields = (|| {
            Ok((
                field(b"class", "KeyError: 'class'")?,
                field(b"ns", "KeyError: 'ns'")?,
                field(b"asm", "KeyError: 'asm'")?,
            ))
        })();
        let (cls, ns, asm) = fields.map_err(|e| match e {
            Py::Limit(l) => limit_refused(at, l),
            e => self.raise(e),
        })?;
        if !matches!(self.ref_types, RefTypes::List(l) if !l.is_empty()) {
            return Err(self.fail(
                ReadErrorKind::RefType,
                ReadDetail::NoRefTypes {
                    reader: ReadBy::Python,
                    absent: matches!(self.ref_types, RefTypes::Absent),
                },
            ));
        }
        if matches!(cls, Value::Str(s) if s.is_empty()) {
            return Ok(None);
        }
        let found = self
            .refs
            .find(self.builder.meter(), &mut self.work.open, cls, ns, asm)
            .map_err(|e| match e {
                FindError::Charge(e) => charge_error(at, e),
                FindError::Work(l) => limit_refused(at, l),
            })?;
        if let Some(r) = found {
            Ok(Some(ref_tree(r, &self.work.limits, at)?))
        } else {
            if let (Some(progress), Value::Str(cls), Value::Str(ns), Value::Str(asm)) =
                (&mut self.progress, cls, ns, asm)
            {
                progress.reference_names = Some([cls.clone(), ns.clone(), asm.clone()]);
            }
            Err(self.fail(ReadErrorKind::RefType, ReadDetail::RefTypeNotFound))
        }
    }
}

fn vec_of2(a: Out, b: Out) -> [Out; 2] {
    [a, b]
}