Skip to main content

unityrs_core/files/serialized/
mod.rs

1// Ported from UnityPy 1.25.2 (MIT): UnityPy/files/SerializedFile.py, UnityPy/files/ObjectReader.py. See THIRD_PARTY_LICENSES.
2//! `SerializedFile` metadata (`files/SerializedFile.py:206-360`,
3//! `files/ObjectReader.py:67-130`), ported from UnityPy, bytes-native.
4//!
5//! Rules ported exactly (plan section 3.7):
6//! - the header (`SerializedFile.py:255-269`): the endian byte at offset 16
7//!   from format 9, else at `file_size - metadata_size` (absolute); the
8//!   format-22 fields replace the legacy `u32`s;
9//! - gates (`SerializedFile.py:271-288`): the version string from format 7, the target platform
10//!   from 8, `enable_type_tree` from 13 (else true), `big_id_enabled` at 7-13;
11//! - type records (`SerializedFile.py:112-149`): `is_stripped_type` from 16, `script_type_index`
12//!   from 17 (else -1), `script_id` and `old_type_hash` from 13 under
13//!   UnityPy's condition, trees only when `enable_type_tree`, blobs at format
14//!   10 and 12 and up; at 21 ref types read three names and plain types a
15//!   dependency list;
16//! - objects (`ObjectReader.py:73-130`): path id as `i64` under bigID, `i32`
17//!   below 14, else aligned `i64`; `byte_start` `u32` (or `i64` from 22) plus
18//!   `data_offset`; below 16 the type is the first whose `class_id` equals the
19//!   object's `type_id`, from 16 `types[type_id]` with Python indexing (a
20//!   negative id counts from the end; out of range fails the file); at 11-16 the
21//!   object's script index is written back into its type, the last object
22//!   winning; the `objects` dict keeps a repeated path id at its first position
23//!   with its last entry;
24//! - `read_string_to_null`'s 32,767-byte window for every metadata string;
25//! - the reader UnityPy reads the file with ([`crate::stream::ReaderKind`]):
26//!   the memory reader for bytes and every entry of a container, the stream
27//!   reader for a file loaded from a path, whose rules the metadata's reads
28//!   and every object read follow ([`SerializedFile::reader_kind`]);
29//! - every table is built with `range(count)` (`SerializedFile.py:282-308`):
30//!   a negative count is zero records, and a table grows record by record, so
31//!   no count sizes an allocation;
32//! - with [`FileContext::eager_asset_bundle`], the first AssetBundle in dict
33//!   order is read at load with `check_read`, and a failure fails the file
34//!   (`SerializedFile.py:316-324`). UnityPy reads it in object mode
35//!   (`parse_as_object`); the core reads it in dict mode, and package D's
36//!   fixtures pin that the two agree (plan section 3.7).
37//!
38//! **Memory.** Every table (types, their dependency lists and trees, objects,
39//! the dict order, scripts, externals, ref types) is built in a
40//! [`crate::limits::MeteredVec`] on the input's meter, and the file keeps the
41//! charges: two directory rows over the same bytes parse twice and pay twice.
42//! Strings are zero-copy slices of the file.
43//!
44//! **Work.** The container read ([`SerializedFile::container`]) builds the
45//! whole AssetBundle value and keeps only its rows and preload table, so
46//! two directory rows over the same bytes would repeat a read whose memory
47//! is returned: what the meter granted the read on its own thread, beyond
48//! what its [`Container`] keeps, counts as the open's work
49//! ([`crate::error::LimitKind::DecodeWork`]), and so does all it was
50//! granted when it fails with an error its cell keeps. At load, a failure
51//! fails the parse, whose grants its bundle counts instead
52//! (`files::bundle`, "Memory and work"), so they count once (round 5).
53//!
54//! Owner: package C. The accessors and [`SerializedType`]'s constructors and
55//! [`SerializedType::tree`] are implemented by the scaffold, so package B can
56//! build ref types for its tests before C lands.
57
58use std::sync::{Arc, OnceLock};
59
60use bytes::Bytes;
61
62use crate::container::{Container, read_container};
63use crate::error::Error;
64use crate::files::Parent;
65use crate::limits::{Charge, ChargeError, GrantScope, Limits, Meter};
66use crate::object::ObjectRef;
67use crate::once::{CellError, ResultCell, get_or_publish_result};
68use crate::options::FileContext;
69use crate::pin::{Copies, CopyCounts};
70use crate::raw::RawStr;
71use crate::stream::{Endian, ReaderKind, ShortArray};
72use crate::typetree::{Tree, TreeError};
73use crate::value::Parsed;
74use crate::version::ResolvedVersion;
75use crate::walk::RefTypes;
76
77mod changed;
78mod head;
79mod parse;
80mod write;
81
82pub use write::SerializedSaveSnapshot;
83
84/// The header, as read.
85#[derive(Clone, Debug, PartialEq, Eq)]
86#[non_exhaustive]
87pub struct SerializedHeader {
88    /// `metadata_size`.
89    pub metadata_size: u32,
90    /// `file_size`.
91    pub file_size: i64,
92    /// The format number (UnityPy's `header.version`).
93    pub version: u32,
94    /// `data_offset`.
95    pub data_offset: i64,
96    /// The byte order.
97    pub endian: Endian,
98    /// The three reserved bytes (format 9 and up).
99    pub reserved: Option<[u8; 3]>,
100    /// Format 22's trailing `i64` (UnityPy's `unknown`), else 0.
101    pub unknown: i64,
102}
103
104/// A type record (`SerializedType`), plain or ref type. Not `Clone`: it
105/// lives in its file's table, which paid for it.
106#[derive(Debug)]
107#[non_exhaustive]
108pub struct SerializedType {
109    /// `class_id`.
110    pub class_id: i32,
111    /// Format 16 and up.
112    pub is_stripped_type: Option<bool>,
113    /// Read from format 17, else -1; at 11-16 the last object's write-back.
114    pub script_type_index: i16,
115    /// `script_id`, under UnityPy's condition (format 13 and up): the bytes
116    /// `read_bytes(16)` returned, short at a negative position or the end.
117    pub script_id: Option<ShortArray<16>>,
118    /// `old_type_hash` (format 13 and up), as `script_id`.
119    pub old_type_hash: Option<ShortArray<16>>,
120    /// The stored tree, when type trees are enabled. Replacing it is safe
121    /// after a compile: [`Self::tree`] serves its kept compile only for the
122    /// list it was made from, and compiles a replacement on each ask, so a
123    /// caller that replaces it often builds a new record instead.
124    pub nodes: Option<crate::typetree::SharedNodes>,
125    /// Plain types, format 21 and up, type trees enabled.
126    pub type_dependencies: Option<Box<[i32]>>,
127    /// Ref types, format 21 and up, type trees enabled: `m_ClassName`.
128    pub class_name: Option<RawStr>,
129    /// `m_NameSpace`.
130    pub namespace: Option<RawStr>,
131    /// `m_AssemblyName`.
132    pub assembly: Option<RawStr>,
133    tree: OnceLock<Compiled>,
134}
135
136/// [`SerializedType::tree`]'s kept answer and the list it is of, published
137/// together once a compile ends in a value or an error its cell keeps: a
138/// refusal that keeps nothing pins no list. A later ask whose
139/// [`SerializedType::nodes`] is another list never reads it (URS-30). The
140/// list is held, so its address names it while the pair lives (no other
141/// list can be allocated there), and the check is one pointer comparison.
142#[derive(Debug)]
143struct Compiled {
144    nodes: crate::typetree::SharedNodes,
145    tree: Result<Arc<Tree>, crate::once::KeptError<TreeError>>,
146}
147
148impl Compiled {
149    /// The kept answer, when it is of `nodes`.
150    fn of(
151        &self,
152        nodes: &crate::typetree::SharedNodes,
153    ) -> Option<&Result<Arc<Tree>, crate::once::KeptError<TreeError>>> {
154        crate::typetree::SharedNodes::ptr_eq(&self.nodes, nodes).then_some(&self.tree)
155    }
156}
157
158impl SerializedType {
159    /// A plain type record: `class_id` and its stored tree, every other
160    /// field as a format below 13 leaves it (`script_type_index` -1).
161    #[must_use]
162    pub fn new(class_id: i32, nodes: Option<crate::typetree::SharedNodes>) -> Self {
163        Self {
164            class_id,
165            is_stripped_type: None,
166            script_type_index: -1,
167            script_id: None,
168            old_type_hash: None,
169            nodes,
170            type_dependencies: None,
171            class_name: None,
172            namespace: None,
173            assembly: None,
174            tree: OnceLock::new(),
175        }
176    }
177
178    /// A ref type (format 21 and up): its class, namespace and assembly
179    /// names and its stored tree.
180    #[must_use]
181    pub fn ref_type(
182        class_id: i32,
183        class_name: RawStr,
184        namespace: RawStr,
185        assembly: RawStr,
186        nodes: Option<crate::typetree::SharedNodes>,
187    ) -> Self {
188        Self {
189            class_name: Some(class_name),
190            namespace: Some(namespace),
191            assembly: Some(assembly),
192            ..Self::new(class_id, nodes)
193        }
194    }
195
196    /// The compiled tree: `Tree::compile` over [`Self::nodes`] (package B),
197    /// computed on first use and published once, so every object and every
198    /// reference of the type reuses one compile. The compile runs outside
199    /// the cell ([`get_or_publish_result`]): two first callers may both
200    /// compile, and the loser's tree is dropped. Its rows are charged to the
201    /// meter the `NodeList` was built on. A compile the meter or the budget
202    /// refuses is returned and not kept, so the next call compiles again;
203    /// a failure the rows decide (depth) is kept. `None` when the record
204    /// stores no tree.
205    pub fn tree(&self, limits: &Limits) -> Option<Result<Arc<Tree>, TreeError>> {
206        self.tree_with(|nodes| Tree::compile(nodes, limits))
207    }
208
209    /// [`Self::tree`] once it is compiled and kept, without compiling or
210    /// waiting: `None` before that, after a failed compile, or when
211    /// [`Self::nodes`] has been replaced since.
212    #[must_use]
213    pub fn compiled_tree(&self) -> Option<&Arc<Tree>> {
214        self.tree.get()?.of(self.nodes.as_ref()?)?.as_ref().ok()
215    }
216
217    /// The compile of [`Self::nodes`]. It runs in a cell of its own
218    /// ([`get_or_publish_result`], so the meter's work rules apply); what
219    /// that cell keeps is then published in the record with the list, when
220    /// the record holds nothing yet. Replaced nodes compile on each ask and
221    /// are never served the record's answer.
222    fn tree_with(
223        &self,
224        compile: impl FnOnce(crate::typetree::SharedNodes) -> Result<Arc<Tree>, TreeError>,
225    ) -> Option<Result<Arc<Tree>, TreeError>> {
226        let nodes = self.nodes.as_ref()?;
227        let answer = |kept: &Result<Arc<Tree>, crate::once::KeptError<TreeError>>| {
228            kept.as_ref().map(Arc::clone).map_err(|k| k.error().clone())
229        };
230        let held = self.tree.get();
231        if let Some(kept) = held.and_then(|c| c.of(nodes)) {
232            return Some(answer(kept));
233        }
234        let cell: ResultCell<Arc<Tree>, TreeError> = ResultCell::new();
235        let got = get_or_publish_result(&cell, nodes.meter(), || compile(nodes.clone())).cloned();
236        let Some(kept) = cell.into_inner() else {
237            return Some(got);
238        };
239        if held.is_some() {
240            return Some(answer(&kept));
241        }
242        let compiled = Compiled {
243            nodes: nodes.clone(),
244            tree: kept,
245        };
246        // The first answer published wins.
247        let won = crate::once::get_or_publish(&self.tree, move || compiled);
248        Some(answer(&won.tree))
249    }
250}
251
252/// One row of the object table.
253#[derive(Clone, Debug, PartialEq, Eq)]
254#[non_exhaustive]
255pub struct ObjectInfo {
256    /// `path_id`.
257    pub path_id: i64,
258    /// Absolute within the `SerializedFile`: the stored `u32` (or format 22's
259    /// `i64`) plus `data_offset`, added as Python adds them, so it can pass
260    /// `i64::MAX` (`2^63 - 1 + 144` loads in UnityPy) or go negative; a read
261    /// from it is by the file's reader's rules ([`SerializedFile::reader_kind`]):
262    /// a Python slice on the memory reader ([`crate::stream::py_read`]).
263    pub byte_start: i128,
264    /// `byte_size`.
265    pub byte_size: u32,
266    /// `type_id` as stored.
267    pub type_id: i32,
268    /// Below format 16 the stored `u16`; from 16 the type's `class_id`.
269    pub class_id: i32,
270    /// The index into `types` this object resolves to, if any.
271    pub type_index: Option<usize>,
272    /// Below format 11.
273    pub is_destroyed: Option<u16>,
274    /// Formats 15 and 16.
275    pub is_stripped: Option<i8>,
276    /// Formats 11-16.
277    pub script_type_index: Option<i16>,
278}
279
280/// One external file reference.
281#[derive(Clone, Debug, PartialEq, Eq)]
282#[non_exhaustive]
283pub struct External {
284    /// `temp_empty` (format 6 and up).
285    pub temp_empty: Option<RawStr>,
286    /// `guid` (format 5 and up): the bytes `read_bytes(16)` returned, short
287    /// at a negative position or the end.
288    pub guid: Option<ShortArray<16>>,
289    /// `type` (format 5 and up).
290    pub kind: Option<i32>,
291    /// `path`.
292    pub path: RawStr,
293}
294
295impl External {
296    /// A writable reference to `path`, with empty GUID and type zero.
297    #[must_use]
298    pub fn new(path: RawStr) -> Self {
299        Self {
300            temp_empty: Some(RawStr::from_static(b"")),
301            guid: Some([0; 16].into()),
302            kind: Some(0),
303            path,
304        }
305    }
306}
307
308/// One script type reference (`LocalSerializedObjectIdentifier`).
309#[derive(Clone, Copy, Debug, PartialEq, Eq)]
310#[non_exhaustive]
311pub struct ScriptRef {
312    /// `local_serialized_file_index`.
313    pub file_index: i32,
314    /// `local_identifier_in_file`.
315    pub identifier: i64,
316}
317
318/// A parsed `SerializedFile`: metadata and object table. Values are read on
319/// demand through [`ObjectRef`].
320pub struct SerializedFile {
321    changed: std::sync::atomic::AtomicBool,
322    edits: std::sync::Mutex<crate::limits::MeteredVec<(u32, Bytes)>>,
323    head_handlers: crate::limits::MeteredVec<head::Handler>,
324    head_roots: usize,
325    pub(super) pending_externals: std::sync::Mutex<crate::limits::MeteredVec<External>>,
326    name: RawStr,
327    data: Bytes,
328    header: SerializedHeader,
329    unity_version: Option<RawStr>,
330    version: Option<ResolvedVersion>,
331    target_platform: Option<i32>,
332    enable_type_tree: bool,
333    big_id_enabled: i32,
334    types: Box<[SerializedType]>,
335    ref_types: Option<Box<[SerializedType]>>,
336    script_types: Box<[ScriptRef]>,
337    externals: Box<[External]>,
338    user_information: Option<RawStr>,
339    object_infos: Box<[ObjectInfo]>,
340    object_order: Box<[u32]>,
341    /// The dict's entries (indexes into `object_infos`) sorted by path id,
342    /// for [`Self::object`].
343    by_path: Box<[u32]>,
344    /// Published by [`get_or_publish_result`]: a refused charge is not kept.
345    container: ResultCell<Container, Error>,
346    parent: Option<Parent>,
347    pub(super) dependency_path: super::DependencyPath,
348    /// The reader UnityPy reads it with, for its metadata and its objects.
349    reader: ReaderKind,
350    constructor_position: i128,
351    /// What its reads and its parse copied out of the buffer its bytes are
352    /// a slice of ([`Self::copies`]).
353    copies: CopyCounts,
354    /// The handle and every table above, charged to the input, with the
355    /// resolved version's heap ([`crate::version::UnityVersion::heap_bytes`], charged
356    /// by the chain before it was allocated;
357    /// its string is the file's own slice, or the parent's, never a copy).
358    charge: Charge,
359    ctx: Arc<FileContext>,
360}
361
362impl std::fmt::Debug for SerializedFile {
363    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
364        f.debug_struct("SerializedFile")
365            .field("name", &self.name)
366            .field("header", &self.header)
367            .field("unity_version", &self.unity_version)
368            .field("types", &self.types.len())
369            .field("objects", &self.object_order.len())
370            .finish_non_exhaustive()
371    }
372}
373
374impl SerializedFile {
375    /// The identity of this file occurrence while it is held. A dependency
376    /// keeps the same input address and directory path across cache reopens.
377    #[must_use]
378    pub fn occurrence_key(&self) -> (usize, &[usize]) {
379        self.dependency_path.0.get().map_or_else(
380            || (std::ptr::from_ref(self).addr(), &[][..]),
381            |path| (self.meter().input_address(), path.as_slice()),
382        )
383    }
384
385    /// The meter of the input it belongs to: what reading its objects
386    /// charges ([`crate::walk::ReadCtx::meter`]).
387    pub fn meter(&self) -> &Arc<Meter> {
388        self.charge.meter()
389    }
390
391    /// The name it was loaded under.
392    pub fn name(&self) -> &RawStr {
393        &self.name
394    }
395
396    /// The whole file's bytes.
397    pub fn data(&self) -> &Bytes {
398        &self.data
399    }
400
401    /// The length of the buffer its bytes are a slice of, which a slice of
402    /// them keeps alive: its container's decoded run, or the container's
403    /// own bytes' buffer ([`Parent::pinned`]); its own length for a
404    /// top-level file. A value read from it, and each typetree it parsed,
405    /// copy their slices out when they would keep much more than
406    /// themselves alive ([`crate::pin`]).
407    #[must_use]
408    pub fn pinned(&self) -> u64 {
409        pinned(self.parent.as_ref(), &self.data)
410    }
411
412    /// What its object reads and its parse copied out of the buffer its
413    /// bytes are a slice of so far ([`crate::pin`]; plan section 8, R3).
414    #[must_use]
415    pub fn copies(&self) -> Copies {
416        self.copies.get()
417    }
418
419    /// Copies `value`'s slices of this file out of the buffer they keep
420    /// alive, when they would keep much more than themselves alive
421    /// ([`crate::pin`]), and counts the copy: the bytes copied.
422    pub(crate) fn unpin(
423        &self,
424        value: &mut Parsed,
425        caller: Option<&Arc<Meter>>,
426    ) -> Result<(), ChargeError> {
427        let target = value.value_mut();
428        let n = if let Some(meter) = caller {
429            crate::pin::try_copy_out(target, &self.data, self.pinned(), meter, true)?
430        } else {
431            crate::pin::copy_out(target, &self.data, self.pinned(), self.meter())
432        };
433        self.copies.value(n);
434        Ok(())
435    }
436
437    /// Final metadata cursor of the constructor's input reader.
438    #[must_use]
439    pub fn constructor_position(&self) -> i128 {
440        self.constructor_position
441    }
442
443    /// The reader used for metadata and object reads: stream for paths,
444    /// otherwise memory ([`ObjectRef::read_typetree`], [`ObjectRef::raw_data`]).
445    pub fn reader_kind(&self) -> ReaderKind {
446        self.reader
447    }
448
449    /// The shared reader's position after loading metadata and the eager container.
450    pub fn reader_position(&self) -> i128 {
451        self.constructor_position
452    }
453
454    /// The header.
455    pub fn header(&self) -> &SerializedHeader {
456        &self.header
457    }
458
459    /// The version string as read (format 7 and up).
460    pub fn unity_version(&self) -> Option<&RawStr> {
461        self.unity_version.as_ref()
462    }
463
464    /// Chain 2's result (format 7 and up).
465    pub fn version(&self) -> Option<&ResolvedVersion> {
466        self.version.as_ref()
467    }
468
469    /// The raw target platform (format 8 and up).
470    pub fn target_platform(&self) -> Option<i32> {
471        self.target_platform
472    }
473
474    /// Whether type records carry trees.
475    pub fn enable_type_tree(&self) -> bool {
476        self.enable_type_tree
477    }
478
479    /// `big_id_enabled` (formats 7-13, else 0).
480    pub fn big_id_enabled(&self) -> i32 {
481        self.big_id_enabled
482    }
483
484    /// Type records, in file order, script indexes written back.
485    pub fn types(&self) -> &[SerializedType] {
486        &self.types
487    }
488
489    /// Ref types (format 20 and up).
490    pub fn ref_types(&self) -> Option<&[SerializedType]> {
491        self.ref_types.as_deref()
492    }
493
494    /// The reader's view of the ref types.
495    pub fn ref_types_view(&self) -> RefTypes<'_> {
496        match &self.ref_types {
497            Some(t) => RefTypes::List(t),
498            None => RefTypes::Absent,
499        }
500    }
501
502    /// Script type references.
503    pub fn script_types(&self) -> &[ScriptRef] {
504        &self.script_types
505    }
506
507    /// External file references.
508    pub fn externals(&self) -> &[External] {
509        &self.externals
510    }
511
512    /// `userInformation` (format 5 and up).
513    pub fn user_information(&self) -> Option<&RawStr> {
514        self.user_information.as_ref()
515    }
516
517    /// The object table in file order, repeated path ids kept.
518    pub fn object_infos(&self) -> &[ObjectInfo] {
519        &self.object_infos
520    }
521
522    /// UnityPy's `objects` dict order: indexes into [`Self::object_infos`] of
523    /// each path id's last entry, at its first position.
524    pub fn object_order(&self) -> &[u32] {
525        &self.object_order
526    }
527
528    /// The objects, in dict order.
529    pub fn objects(self: &Arc<Self>) -> impl Iterator<Item = ObjectRef> + '_ {
530        self.object_order
531            .iter()
532            .filter_map(|i| ObjectRef::new(self.clone(), *i))
533    }
534
535    /// The objects in ascending signed path id (UnityPy's
536    /// `sorted(objects.values(), key=lambda o: o.path_id)`): the table
537    /// [`Self::object`] searches, kept and charged with the file, so a
538    /// caller orders them without a copy or a sort.
539    pub fn objects_by_path(self: &Arc<Self>) -> impl Iterator<Item = ObjectRef> + '_ {
540        self.by_path
541            .iter()
542            .filter_map(|i| ObjectRef::new(self.clone(), *i))
543    }
544
545    /// The object `objects[path_id]` holds.
546    pub fn object(self: &Arc<Self>, path_id: i64) -> Option<ObjectRef> {
547        let at = self
548            .by_path
549            .binary_search_by_key(&path_id, |i| {
550                usize::try_from(*i)
551                    .ok()
552                    .and_then(|i| self.object_infos.get(i))
553                    .map_or(i64::MIN, |o| o.path_id)
554            })
555            .ok()?;
556        ObjectRef::new(self.clone(), *self.by_path.get(at)?)
557    }
558
559    /// The container rows of the first AssetBundle in dict order, read once
560    /// ([`crate::container::read_container`]) and published
561    /// ([`get_or_publish_result`]: the read runs outside the cell, and a
562    /// refused charge is returned, not kept). What the read was granted and
563    /// its container does not keep is the open's work (module docs, "Work").
564    pub fn container(self: &Arc<Self>) -> Result<&Container, Error> {
565        self.container_counted(true)
566    }
567
568    /// [`Self::container`] as the load reads it (`SerializedFile.py:316-324`):
569    /// a failure fails the parse, whose caller counts its grants.
570    fn container_at_load(self: &Arc<Self>) -> Result<&Container, Error> {
571        self.container_counted(false)
572    }
573
574    /// The container, its read's grants counted as work: on success what its
575    /// container does not keep, on a failure its cell keeps all of it when
576    /// `failure_counts`. A refusal the cell does not keep is
577    /// [`get_or_publish_result`]'s to count.
578    fn container_counted(self: &Arc<Self>, failure_counts: bool) -> Result<&Container, Error> {
579        let meter = self.meter();
580        get_or_publish_result(&self.container, meter, || {
581            let scope = GrantScope::enter(meter);
582            let got = read_container(self);
583            let granted = scope.finish(meter);
584            match &got {
585                Ok(c) => meter.add_work(granted.saturating_sub(c.charge().bytes())),
586                Err(e) if failure_counts && !e.is_transient() => meter.add_work(granted),
587                Err(_) => {}
588            }
589            got
590        })
591    }
592
593    /// The container this file is an entry of.
594    pub fn parent(&self) -> Option<&Parent> {
595        self.parent.as_ref()
596    }
597
598    /// The context it was loaded with.
599    pub fn context(&self) -> &Arc<FileContext> {
600        &self.ctx
601    }
602
603    /// A file of `rows` and nothing else, for the crate's tests before
604    /// package C's `parse` lands: dict order is file order.
605    #[cfg(test)]
606    pub(crate) fn for_tests(rows: Vec<ObjectInfo>) -> Arc<Self> {
607        let meter = Meter::unlimited();
608        let order = (0..u32::try_from(rows.len()).unwrap()).collect();
609        Arc::new(Self {
610            changed: std::sync::atomic::AtomicBool::new(false),
611            edits: std::sync::Mutex::new(crate::limits::MeteredVec::new(&meter)),
612            head_handlers: crate::limits::MeteredVec::new(&meter),
613            head_roots: 0,
614            pending_externals: std::sync::Mutex::new(crate::limits::MeteredVec::new(&meter)),
615            name: RawStr::from_static(b"CAB-test"),
616            data: Bytes::new(),
617            header: SerializedHeader {
618                metadata_size: 0,
619                file_size: 0,
620                version: 22,
621                data_offset: 0,
622                endian: Endian::Little,
623                reserved: None,
624                unknown: 0,
625            },
626            unity_version: None,
627            version: None,
628            target_platform: None,
629            enable_type_tree: true,
630            big_id_enabled: 0,
631            types: Box::new([]),
632            ref_types: None,
633            script_types: Box::new([]),
634            externals: Box::new([]),
635            user_information: None,
636            by_path: Box::new([]),
637            object_infos: rows.into_boxed_slice(),
638            object_order: order,
639            container: ResultCell::new(),
640            parent: None,
641            dependency_path: super::DependencyPath::default(),
642            reader: ReaderKind::Memory,
643            constructor_position: 0,
644            copies: CopyCounts::default(),
645            charge: Charge::zero(&meter),
646            ctx: Arc::new(FileContext::unitypy()),
647        })
648    }
649}
650
651/// [`SerializedFile::pinned`] for a file of `data` under `parent`: what its
652/// container says the buffer is, never less than its own bytes.
653pub(crate) fn pinned(parent: Option<&Parent>, data: &Bytes) -> u64 {
654    let own = u64::try_from(data.len()).unwrap_or(u64::MAX);
655    parent.map_or(own, |p| p.pinned.max(own))
656}
657
658#[cfg(test)]
659mod tests;