use std::sync::{Arc, OnceLock};
use bytes::Bytes;
use crate::container::{Container, read_container};
use crate::error::Error;
use crate::files::Parent;
use crate::limits::{Charge, ChargeError, GrantScope, Limits, Meter};
use crate::object::ObjectRef;
use crate::once::{CellError, ResultCell, get_or_publish_result};
use crate::options::FileContext;
use crate::pin::{Copies, CopyCounts};
use crate::raw::RawStr;
use crate::stream::{Endian, ReaderKind, ShortArray};
use crate::typetree::{Tree, TreeError};
use crate::value::Parsed;
use crate::version::ResolvedVersion;
use crate::walk::RefTypes;
mod changed;
mod head;
mod parse;
mod write;
pub use write::SerializedSaveSnapshot;
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct SerializedHeader {
pub metadata_size: u32,
pub file_size: i64,
pub version: u32,
pub data_offset: i64,
pub endian: Endian,
pub reserved: Option<[u8; 3]>,
pub unknown: i64,
}
#[derive(Debug)]
#[non_exhaustive]
pub struct SerializedType {
pub class_id: i32,
pub is_stripped_type: Option<bool>,
pub script_type_index: i16,
pub script_id: Option<ShortArray<16>>,
pub old_type_hash: Option<ShortArray<16>>,
pub nodes: Option<crate::typetree::SharedNodes>,
pub type_dependencies: Option<Box<[i32]>>,
pub class_name: Option<RawStr>,
pub namespace: Option<RawStr>,
pub assembly: Option<RawStr>,
tree: ResultCell<Arc<Tree>, TreeError>,
}
impl SerializedType {
#[must_use]
pub fn new(class_id: i32, nodes: Option<crate::typetree::SharedNodes>) -> Self {
Self {
class_id,
is_stripped_type: None,
script_type_index: -1,
script_id: None,
old_type_hash: None,
nodes,
type_dependencies: None,
class_name: None,
namespace: None,
assembly: None,
tree: OnceLock::new(),
}
}
#[must_use]
pub fn ref_type(
class_id: i32,
class_name: RawStr,
namespace: RawStr,
assembly: RawStr,
nodes: Option<crate::typetree::SharedNodes>,
) -> Self {
Self {
class_name: Some(class_name),
namespace: Some(namespace),
assembly: Some(assembly),
..Self::new(class_id, nodes)
}
}
pub fn tree(&self, limits: &Limits) -> Option<Result<Arc<Tree>, TreeError>> {
self.tree_with(|nodes| Tree::compile(nodes, limits))
}
#[must_use]
pub fn compiled_tree(&self) -> Option<&Arc<Tree>> {
self.tree.get()?.as_ref().ok()
}
fn tree_with(
&self,
compile: impl FnOnce(crate::typetree::SharedNodes) -> Result<Arc<Tree>, TreeError>,
) -> Option<Result<Arc<Tree>, TreeError>> {
let nodes = self.nodes.as_ref()?;
Some(get_or_publish_result(&self.tree, nodes.meter(), || compile(nodes.clone())).cloned())
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ObjectInfo {
pub path_id: i64,
pub byte_start: i128,
pub byte_size: u32,
pub type_id: i32,
pub class_id: i32,
pub type_index: Option<usize>,
pub is_destroyed: Option<u16>,
pub is_stripped: Option<i8>,
pub script_type_index: Option<i16>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct External {
pub temp_empty: Option<RawStr>,
pub guid: Option<ShortArray<16>>,
pub kind: Option<i32>,
pub path: RawStr,
}
impl External {
#[must_use]
pub fn new(path: RawStr) -> Self {
Self {
temp_empty: Some(RawStr::from_static(b"")),
guid: Some([0; 16].into()),
kind: Some(0),
path,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ScriptRef {
pub file_index: i32,
pub identifier: i64,
}
pub struct SerializedFile {
changed: std::sync::atomic::AtomicBool,
edits: std::sync::Mutex<crate::limits::MeteredVec<(u32, Bytes)>>,
head_handlers: crate::limits::MeteredVec<head::Handler>,
head_roots: usize,
pub(super) pending_externals: std::sync::Mutex<crate::limits::MeteredVec<External>>,
name: RawStr,
data: Bytes,
header: SerializedHeader,
unity_version: Option<RawStr>,
version: Option<ResolvedVersion>,
target_platform: Option<i32>,
enable_type_tree: bool,
big_id_enabled: i32,
types: Box<[SerializedType]>,
ref_types: Option<Box<[SerializedType]>>,
script_types: Box<[ScriptRef]>,
externals: Box<[External]>,
user_information: Option<RawStr>,
object_infos: Box<[ObjectInfo]>,
object_order: Box<[u32]>,
by_path: Box<[u32]>,
container: ResultCell<Container, Error>,
parent: Option<Parent>,
pub(super) dependency_path: super::DependencyPath,
reader: ReaderKind,
constructor_position: i128,
copies: CopyCounts,
charge: Charge,
ctx: Arc<FileContext>,
}
impl std::fmt::Debug for SerializedFile {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SerializedFile")
.field("name", &self.name)
.field("header", &self.header)
.field("unity_version", &self.unity_version)
.field("types", &self.types.len())
.field("objects", &self.object_order.len())
.finish_non_exhaustive()
}
}
impl SerializedFile {
#[must_use]
pub fn occurrence_key(&self) -> (usize, &[usize]) {
self.dependency_path.0.get().map_or_else(
|| (std::ptr::from_ref(self).addr(), &[][..]),
|path| (self.meter().input_address(), path.as_slice()),
)
}
pub fn meter(&self) -> &Arc<Meter> {
self.charge.meter()
}
pub fn name(&self) -> &RawStr {
&self.name
}
pub fn data(&self) -> &Bytes {
&self.data
}
#[must_use]
pub fn pinned(&self) -> u64 {
pinned(self.parent.as_ref(), &self.data)
}
#[must_use]
pub fn copies(&self) -> Copies {
self.copies.get()
}
pub(crate) fn unpin(
&self,
value: &mut Parsed,
caller: Option<&Arc<Meter>>,
) -> Result<(), ChargeError> {
let target = value.value_mut();
let n = if let Some(meter) = caller {
crate::pin::try_copy_out(target, &self.data, self.pinned(), meter, true)?
} else {
crate::pin::copy_out(target, &self.data, self.pinned(), self.meter())
};
self.copies.value(n);
Ok(())
}
#[must_use]
pub fn constructor_position(&self) -> i128 {
self.constructor_position
}
pub fn reader_kind(&self) -> ReaderKind {
self.reader
}
pub fn reader_position(&self) -> i128 {
self.constructor_position
}
pub fn header(&self) -> &SerializedHeader {
&self.header
}
pub fn unity_version(&self) -> Option<&RawStr> {
self.unity_version.as_ref()
}
pub fn version(&self) -> Option<&ResolvedVersion> {
self.version.as_ref()
}
pub fn target_platform(&self) -> Option<i32> {
self.target_platform
}
pub fn enable_type_tree(&self) -> bool {
self.enable_type_tree
}
pub fn big_id_enabled(&self) -> i32 {
self.big_id_enabled
}
pub fn types(&self) -> &[SerializedType] {
&self.types
}
pub fn ref_types(&self) -> Option<&[SerializedType]> {
self.ref_types.as_deref()
}
pub fn ref_types_view(&self) -> RefTypes<'_> {
match &self.ref_types {
Some(t) => RefTypes::List(t),
None => RefTypes::Absent,
}
}
pub fn script_types(&self) -> &[ScriptRef] {
&self.script_types
}
pub fn externals(&self) -> &[External] {
&self.externals
}
pub fn user_information(&self) -> Option<&RawStr> {
self.user_information.as_ref()
}
pub fn object_infos(&self) -> &[ObjectInfo] {
&self.object_infos
}
pub fn object_order(&self) -> &[u32] {
&self.object_order
}
pub fn objects(self: &Arc<Self>) -> impl Iterator<Item = ObjectRef> + '_ {
self.object_order
.iter()
.filter_map(|i| ObjectRef::new(self.clone(), *i))
}
pub fn objects_by_path(self: &Arc<Self>) -> impl Iterator<Item = ObjectRef> + '_ {
self.by_path
.iter()
.filter_map(|i| ObjectRef::new(self.clone(), *i))
}
pub fn object(self: &Arc<Self>, path_id: i64) -> Option<ObjectRef> {
let at = self
.by_path
.binary_search_by_key(&path_id, |i| {
usize::try_from(*i)
.ok()
.and_then(|i| self.object_infos.get(i))
.map_or(i64::MIN, |o| o.path_id)
})
.ok()?;
ObjectRef::new(self.clone(), *self.by_path.get(at)?)
}
pub fn container(self: &Arc<Self>) -> Result<&Container, Error> {
self.container_counted(true)
}
fn container_at_load(self: &Arc<Self>) -> Result<&Container, Error> {
self.container_counted(false)
}
fn container_counted(self: &Arc<Self>, failure_counts: bool) -> Result<&Container, Error> {
let meter = self.meter();
get_or_publish_result(&self.container, meter, || {
let scope = GrantScope::enter(meter);
let got = read_container(self);
let granted = scope.finish(meter);
match &got {
Ok(c) => meter.add_work(granted.saturating_sub(c.charge().bytes())),
Err(e) if failure_counts && !e.is_transient() => meter.add_work(granted),
Err(_) => {}
}
got
})
}
pub fn parent(&self) -> Option<&Parent> {
self.parent.as_ref()
}
pub fn context(&self) -> &Arc<FileContext> {
&self.ctx
}
#[cfg(test)]
pub(crate) fn for_tests(rows: Vec<ObjectInfo>) -> Arc<Self> {
let meter = Meter::unlimited();
let order = (0..u32::try_from(rows.len()).unwrap()).collect();
Arc::new(Self {
changed: std::sync::atomic::AtomicBool::new(false),
edits: std::sync::Mutex::new(crate::limits::MeteredVec::new(&meter)),
head_handlers: crate::limits::MeteredVec::new(&meter),
head_roots: 0,
pending_externals: std::sync::Mutex::new(crate::limits::MeteredVec::new(&meter)),
name: RawStr::from_static(b"CAB-test"),
data: Bytes::new(),
header: SerializedHeader {
metadata_size: 0,
file_size: 0,
version: 22,
data_offset: 0,
endian: Endian::Little,
reserved: None,
unknown: 0,
},
unity_version: None,
version: None,
target_platform: None,
enable_type_tree: true,
big_id_enabled: 0,
types: Box::new([]),
ref_types: None,
script_types: Box::new([]),
externals: Box::new([]),
user_information: None,
by_path: Box::new([]),
object_infos: rows.into_boxed_slice(),
object_order: order,
container: ResultCell::new(),
parent: None,
dependency_path: super::DependencyPath::default(),
reader: ReaderKind::Memory,
constructor_position: 0,
copies: CopyCounts::default(),
charge: Charge::zero(&meter),
ctx: Arc::new(FileContext::unitypy()),
})
}
}
pub(crate) fn pinned(parent: Option<&Parent>, data: &Bytes) -> u64 {
let own = u64::try_from(data.len()).unwrap_or(u64::MAX);
parent.map_or(own, |p| p.pinned.max(own))
}
#[cfg(test)]
mod tests;