Skip to main content

unityrs_core/
options.rs

1// Ported from UnityPy 1.25.2 (MIT): UnityPy/files/SerializedFile.py. See THIRD_PARTY_LICENSES.
2//! The options every file loaded through one environment shares.
3//!
4//! A [`FileContext`] is built once (usually by [`crate::env::EnvOptions`]) and
5//! `Arc`'d into every file, so a `SerializedFile` deep inside a bundle reads
6//! with the same version policy, providers, codecs, budget and limits as its
7//! parent.
8//!
9//! Owner: the scaffold (frozen fields; implemented constructors).
10
11use std::fmt;
12use std::sync::Arc;
13
14use crate::budget::{MemoryBudget, Unbounded};
15use crate::codec::{BlockDecryptor, Codecs};
16use crate::limits::Limits;
17use crate::provider::ProviderChain;
18use crate::version::VersionPolicy;
19use crate::walk::{FloatMode, ReadOptions, WriteRules};
20
21/// Options shared by every file of one load.
22#[derive(Clone)]
23#[non_exhaustive]
24pub struct FileContext {
25    /// Optional mutable binding settings, snapshotted while each file loads.
26    pub runtime_config: Option<Arc<crate::config::RuntimeConfig>>,
27    /// UnityPy's `config.FALLBACK_UNITY_VERSION`, plus opt-in, reported overrides.
28    pub version: VersionPolicy,
29    /// How a float32 signalling NaN reaches the value (plan section 3.10).
30    pub floats: FloatMode,
31    /// The writer's alignment rules (plan section 3.11).
32    pub write: WriteRules,
33    /// Typetree sources for stripped files, keyed by (class, version).
34    pub providers: Arc<ProviderChain>,
35    /// Block codecs by compression type.
36    pub codecs: Arc<Codecs>,
37    /// Custom block decryption, overriding the built-in UnityCN decryptor.
38    pub decryptor: Option<Arc<dyn BlockDecryptor>>,
39    /// Load-local UnityCN key. Configure with `set_assetbundle_decrypt_key`.
40    pub(crate) assetbundle_decrypt_key: Option<[u8; 16]>,
41    /// Where decoded buffers are paid for.
42    pub budget: Arc<dyn MemoryBudget>,
43    /// Hard bounds.
44    pub limits: Limits,
45    /// Read the first AssetBundle object while a `SerializedFile` loads, and
46    /// fail the file when it fails, as UnityPy does (`SerializedFile.py:316-324`).
47    pub eager_asset_bundle: bool,
48    /// UnityPy config: parse trees at load, but omit them on save from v13.
49    /// Below v13 save retains the mandatory trees (Tier C writing).
50    pub serialized_file_parse_typetree: bool,
51}
52
53impl FileContext {
54    /// Whether the Python setting preserves the file's stored tree flag.
55    pub(crate) fn parse_typetree_enabled(&self) -> bool {
56        self.runtime_config
57            .as_ref()
58            .is_none_or(|config| config.snapshot().1)
59    }
60    /// UnityPy 1.25.2's behaviour: no fallback version, no providers, the
61    /// UnityPy codecs, no decryptor, no budget, `FloatMode::UnityPy`,
62    /// `WriteRules::UnityPy`, the AssetBundle read at load.
63    #[must_use]
64    pub fn unitypy() -> Self {
65        Self {
66            runtime_config: None,
67            version: VersionPolicy::default(),
68            floats: FloatMode::UnityPy,
69            write: WriteRules::UnityPy,
70            providers: Arc::new(ProviderChain::empty()),
71            codecs: Arc::new(Codecs::unitypy()),
72            decryptor: None,
73            assetbundle_decrypt_key: None,
74            budget: Arc::new(Unbounded),
75            limits: Limits::default(),
76            eager_asset_bundle: true,
77            serialized_file_parse_typetree: true,
78        }
79    }
80
81    /// Sets this load's UnityCN key (16 bytes, including for UTF-8 strings).
82    /// An invalid length leaves the previous key intact. No global state.
83    pub fn set_assetbundle_decrypt_key(
84        &mut self,
85        key: impl AsRef<[u8]>,
86    ) -> Result<(), crate::Error> {
87        let key = key.as_ref();
88        let key = <[u8; 16]>::try_from(key)
89            .map_err(|_| crate::Error::UnityCnKeyLength { length: key.len() })?;
90        self.assetbundle_decrypt_key = Some(key);
91        Ok(())
92    }
93
94    /// The walker's options for this context.
95    #[must_use]
96    pub fn read_options(&self) -> ReadOptions {
97        ReadOptions {
98            floats: self.floats,
99            limits: self.limits,
100        }
101    }
102
103    /// Version policy with the binding's current fallback snapshot.
104    #[must_use]
105    pub fn version_policy(&self) -> VersionPolicy {
106        let mut policy = self.version.clone();
107        if let Some(config) = &self.runtime_config {
108            policy.fallback = config.snapshot().0;
109        }
110        policy
111    }
112}
113
114impl Default for FileContext {
115    fn default() -> Self {
116        Self::unitypy()
117    }
118}
119
120impl fmt::Debug for FileContext {
121    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122        f.debug_struct("FileContext")
123            .field("version", &self.version)
124            .field("floats", &self.floats)
125            .field("write", &self.write)
126            .field("providers", &self.providers)
127            .field("decryptor", &self.decryptor.is_some())
128            .field("budget", &self.budget)
129            .field("limits", &self.limits)
130            .field("eager_asset_bundle", &self.eager_asset_bundle)
131            .finish_non_exhaustive()
132    }
133}