Skip to main content

unityrs_core/
lib.rs

1//! Unity asset bundles, serialized files and typetrees, read with the semantics
2//! of UnityPy 1.25.2 and UnityPyBoost.
3//!
4//! The plan is `docs/plans/core.md`. These modules are its shared interfaces:
5//! every public type and signature here is the contract the P1 work packages
6//! build against. A module whose first line is a `STUB` allow still has
7//! `todo!()` bodies; the package that owns it (plan section 7) fills it and
8//! deletes the allow.
9//!
10//! Layering, bottom up:
11//! - [`raw`], [`limits`], [`budget`], [`once`], [`error`], [`options`], [`pin`]: shared plumbing;
12//! - [`tables`], [`classid`]: generated tables pinned to the oracle's UnityPy and Python;
13//! - [`stream`], [`version`], [`detect`], [`codec`]: UnityPy's readers and rules;
14//! - [`files`]: `BundleFile`, `WebFile`, `SerializedFile` and raw files;
15//! - [`typetree`]: node rows, UnityPy's tree-building rule, the compiled [`typetree::Tree`];
16//! - [`value`] and [`walk`]: the dict model, UnityPyBoost's reader, the
17//!   pure-Python reader and UnityPy's writer;
18//! - [`provider`], [`object`], [`container`], [`env`](mod@env): typetree sources,
19//!   objects, container paths and the `Environment`.
20//!
21//! Under the `test-counters` feature, for tests alone (`docs/plans/batch.md`
22//! section 6, CR8), `testing` counts the refusals the core meets and the
23//! span reads of its bundles; a build without it has none of that code.
24
25#![forbid(unsafe_code)]
26// No panics on untrusted input (plan section 3.15). Tests may opt out.
27#![cfg_attr(
28    not(test),
29    deny(
30        clippy::unwrap_used,
31        clippy::expect_used,
32        clippy::panic,
33        clippy::todo,
34        clippy::unimplemented,
35        clippy::unreachable,
36        clippy::indexing_slicing
37    )
38)]
39
40pub mod budget;
41pub mod classid;
42pub mod codec;
43pub mod config;
44pub mod container;
45mod counters;
46pub mod detect;
47pub mod env;
48pub mod error;
49pub mod files;
50pub mod limits;
51pub mod object;
52pub mod objmode;
53pub mod once;
54pub mod options;
55pub mod pin;
56pub mod provider;
57pub mod pyfloat;
58pub mod pystr;
59pub mod raw;
60pub mod stream;
61pub mod tables;
62#[cfg(feature = "test-counters")]
63pub mod testing;
64pub mod typetree;
65pub mod value;
66pub mod version;
67pub mod walk;
68pub mod zip;
69
70pub use bytes::Bytes;
71pub use error::{Error, LimitError, LimitKind, NotFound, Unsupported};
72pub use files::{BundleFile, File, RawFile, SerializedFile, WebFile};
73pub use object::ObjectRef;
74pub use options::FileContext;
75pub use raw::RawStr;
76pub use value::{Built, Map, Parsed, PrimArray, PrimRun, ReadBy, Value, ValueBuilder};
77pub use version::UnityVersion;
78
79/// The crate version, as built.
80pub const VERSION: &str = env!("CARGO_PKG_VERSION");
81
82/// Asserts at compile time that `T` is `Send + Sync` (plan section 3.16):
83/// `const _: () = crate::send_sync::<T>();`, here or next to the type.
84pub(crate) const fn send_sync<T: Send + Sync + ?Sized>() {}
85
86/// Every public type of the core is `Send + Sync` (plan section 3.16): a pool
87/// or a binding may share any of them. This fails to compile if one stops
88/// being so, and `tests::every_public_type_is_asserted` fails if a public
89/// type is added to the crate with no assertion naming its full path, here
90/// or in its own file (a package that adds a type adds the line next to it).
91const _: () = {
92    // budget
93    send_sync::<budget::Reservation>();
94    send_sync::<budget::BudgetExceeded>();
95    send_sync::<budget::Counting>();
96    send_sync::<budget::DecodeBuf>();
97    send_sync::<budget::Permit>();
98    send_sync::<budget::Unbounded>();
99    send_sync::<dyn budget::MemoryBudget>();
100    send_sync::<dyn budget::PermitHome>();
101    // codec
102    send_sync::<codec::Codec>();
103    send_sync::<codec::Codecs>();
104    send_sync::<dyn codec::BlockCodec>();
105    send_sync::<codec::Decoded>();
106    send_sync::<dyn codec::BlockDecryptor>();
107    // container, detect
108    send_sync::<container::Container>();
109    send_sync::<container::ContainerRow>();
110    send_sync::<detect::DetectError>();
111    send_sync::<detect::FileType>();
112    send_sync::<detect::ParsedAs>();
113    // env
114    send_sync::<env::LoadMode>();
115    send_sync::<env::Source>();
116    send_sync::<env::EnvOptions>();
117    send_sync::<env::EnvStats>();
118    send_sync::<env::Environment>();
119    send_sync::<dyn env::CabResolver>();
120    send_sync::<dyn env::Fetch>();
121    send_sync::<env::pptr::DerefError>();
122    send_sync::<env::pptr::ExternalIndexError>();
123    send_sync::<env::pptr::PPtr>();
124    send_sync::<env::registry::Cab>();
125    send_sync::<env::registry::Keys<'static>>();
126    send_sync::<env::registry::RawCab>();
127    send_sync::<env::registry::Registry>();
128    // error
129    send_sync::<error::Error>();
130    send_sync::<error::LimitKind>();
131    send_sync::<error::NotFound>();
132    send_sync::<error::Unsupported>();
133    send_sync::<error::LimitError>();
134    // files
135    send_sync::<files::bundle::LayoutKind>();
136    send_sync::<files::bundle::BlockInfo>();
137    send_sync::<files::bundle::BundleFile>();
138    send_sync::<files::bundle::BundleHeader>();
139    send_sync::<files::bundle::DirEntry>();
140    send_sync::<files::bundle::FileSlot>();
141    send_sync::<files::File>();
142    send_sync::<files::ParentKind>();
143    send_sync::<files::Parent>();
144    send_sync::<files::RawFile>();
145    send_sync::<files::serialized::External>();
146    send_sync::<files::serialized::ObjectInfo>();
147    send_sync::<files::serialized::ScriptRef>();
148    send_sync::<files::serialized::SerializedFile>();
149    send_sync::<files::serialized::SerializedHeader>();
150    send_sync::<files::serialized::SerializedType>();
151    send_sync::<files::web::WebPacker>();
152    send_sync::<files::web::WebFile>();
153    send_sync::<files::save::SaveLayout>();
154    send_sync::<files::save::SaveOptions>();
155    send_sync::<files::save::SaveError>();
156    // limits, object, options, provider, raw, stream
157    send_sync::<limits::ChargeError>();
158    send_sync::<limits::Limits>();
159    send_sync::<once::KeptError<Error>>();
160    send_sync::<once::ResultCell<u8, Error>>();
161    send_sync::<dyn once::CellError>();
162    send_sync::<object::ObjectRef>();
163    send_sync::<options::FileContext>();
164    send_sync::<dyn config::DecryptKeySource>();
165    send_sync::<provider::TreeSource>();
166    send_sync::<provider::ProviderChain>();
167    send_sync::<provider::ProviderError>();
168    send_sync::<provider::ScriptIdent>();
169    send_sync::<provider::TreeRef>();
170    send_sync::<provider::TreeRequest<'static>>();
171    send_sync::<dyn provider::TypeTreeProvider>();
172    send_sync::<raw::RawStr>();
173    send_sync::<Bytes>();
174    send_sync::<stream::Endian>();
175    send_sync::<stream::Reader<'static>>();
176    // typetree
177    send_sync::<typetree::rows::TreeError>();
178    send_sync::<typetree::rows::NodeId>();
179    send_sync::<typetree::rows::NodeList>();
180    send_sync::<typetree::rows::NodeRow>();
181    send_sync::<typetree::tree::Kind>();
182    send_sync::<typetree::tree::Shape>();
183    send_sync::<typetree::tree::NodeInfo>();
184    send_sync::<typetree::tree::Tree>();
185    // value, version
186    send_sync::<value::PrimArray>();
187    send_sync::<value::Value>();
188    send_sync::<value::Map>();
189    send_sync::<value::Parsed>();
190    send_sync::<value::ValueBuilder>();
191    send_sync::<value::Built>();
192    send_sync::<value::PrimRun>();
193    send_sync::<value::ListIx>();
194    send_sync::<value::ReadBy>();
195    send_sync::<version::FlagsClass>();
196    send_sync::<version::VersionError>();
197    send_sync::<version::VersionSource>();
198    send_sync::<version::ResolvedVersion>();
199    send_sync::<version::UnityVersion>();
200    send_sync::<version::VersionPolicy>();
201    // walk
202    send_sync::<walk::FloatMode>();
203    send_sync::<walk::L2Kind>();
204    send_sync::<walk::ParseError>();
205    send_sync::<walk::ReadDetail>();
206    send_sync::<walk::ReadErrorKind>();
207    send_sync::<walk::RefTypes<'static>>();
208    send_sync::<walk::WriteError>();
209    send_sync::<walk::WriteRules>();
210    send_sync::<walk::ReadCtx<'static>>();
211    send_sync::<walk::ReadError>();
212    send_sync::<walk::ReadOptions>();
213    send_sync::<walk::WriteCtx<'static>>();
214    send_sync::<walk::emit::Emitted<()>>();
215    send_sync::<walk::emit::Run<'static>>();
216    send_sync::<walk::emit::Scalar>();
217    // A sink builds a caller's values (Python's, on the caller's thread):
218    // the trait asks neither, and a sink that is both is.
219    send_sync::<dyn walk::emit::Sink<Obj = ()> + Send + Sync>();
220    // Where a sink's run elements go: likewise.
221    send_sync::<dyn walk::emit::Elements + Send + Sync>();
222};
223
224#[cfg(test)]
225mod tests {
226    use std::path::Path;
227
228    /// Every `pub struct`, `pub enum`, `pub union`, `pub trait` and `pub type`
229    /// of the crate is named,
230    /// by its full module path, by a `send_sync` assertion
231    /// (`unityrs_testkit::public_types`), so none can lose `Send + Sync`
232    /// unnoticed, and a new type that shares a name with an asserted one
233    /// does not pass on the other's line.
234    #[test]
235    fn every_public_type_is_asserted() {
236        let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
237        let missing = unityrs_testkit::public_types::unasserted(&src);
238        assert!(missing.is_empty(), "not asserted Send + Sync: {missing:?}");
239    }
240
241    /// Plan 4.1: outside its tests the core starts no thread and never
242    /// sleeps, parks, spins, or waits on a condition, a barrier or a channel
243    /// (`unityrs_testkit::waits`), so a batch engine's pool threads cannot
244    /// block inside a core call, and the engine alone decides the threads.
245    #[test]
246    fn the_core_starts_no_thread_and_never_waits() {
247        let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
248        let found = unityrs_testkit::waits::waits(&src);
249        assert!(
250            found.is_empty(),
251            "the core waits or starts a thread: {found:?}"
252        );
253    }
254
255    /// Plan 4.1 and 3.16: no lazy value is computed inside its cell. Every
256    /// cell outside `once.rs` is filled through `once::get_or_publish` or
257    /// `get_or_publish_result` (`unityrs_testkit::waits::cell_fills`), whose
258    /// tests pin that only a move runs inside the cell, so a callback that
259    /// re-enters a cell, or a thread holding the GIL, never waits on one.
260    #[test]
261    fn every_cell_is_filled_through_the_once_helper() {
262        let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
263        let found = unityrs_testkit::waits::cell_fills(&src);
264        assert!(
265            found.is_empty(),
266            "a cell filled outside the once helper: {found:?}"
267        );
268    }
269}