unityrs_meshdecode/version.rs
1// Ported from UnityPy 1.25.2 (MIT): UnityPy/helpers/UnityVersion.py's indexing and tuple comparisons, as MeshHandler uses them. See THIRD_PARTY_LICENSES.
2//! The version `MeshHandler` compares with.
3//!
4//! UnityPy hands the handler the object's `UnityVersion`, an `int`, and
5//! the handler reads it three ways: `version[0]`, `version[:2]` and
6//! `version >= (2017, 4)`. Each builds the tuple `(major, minor, build,
7//! type, number)` (`__getitem__`, `helpers/UnityVersion.py:99-107`;
8//! `as_tuple`, `:109-110`; `__gt__` and `__ge__`, `:132-140`), whose
9//! `type` is `UnityVersionType(byte)` (`:41-42`), so every read raises
10//! `ValueError` for a type byte that is no member (of a version string's
11//! type number, `:57-60`, the number's bits 8 to 15 are OR-ed into the type
12//! byte: `a` first reads as `b` at 256, `p` first raises at 512, `f` at
13//! 1024). [`Version`]
14//! keeps the tuple or that byte, and each read returns the tuple's answer
15//! or [`MeshError::VersionType`].
16//!
17//! A 5-tuple compared with a shorter one is Python's tuple order: equal
18//! on the shorter one's length, the longer is the greater, so
19//! `version >= (2017, 4)` holds exactly when `(major, minor)` is at least
20//! `(2017, 4)`, and `==` with a shorter tuple never holds.
21
22use unityrs_core::UnityVersion;
23use unityrs_core::version::VersionError;
24
25use crate::error::MeshError;
26
27/// The version a handler reads (module docs).
28#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
29pub struct Version {
30 /// `(major, minor, build, type, number)`, or the type byte that is no
31 /// `UnityVersionType`.
32 parts: Result<[u16; 5], u8>,
33}
34
35const _: () = crate::send_sync::<Version>();
36
37impl Version {
38 /// The version of an object's file, as UnityPy's `object_reader.version`
39 /// is (the caller's to pick: the handler is given one, as `SpriteHelper`
40 /// gives it, `export/SpriteHelper.py:117`).
41 #[must_use]
42 pub fn of(version: &UnityVersion) -> Self {
43 let parts = match version.as_tuple() {
44 Ok((major, minor, build, ty, number)) => {
45 Ok([major, minor, build, u16::from(ty), u16::from(number)])
46 }
47 Err(VersionError::TypeByte(b)) => Err(b),
48 // `as_tuple` raises nothing else; were it to, the type byte
49 // 6 is no member either.
50 Err(_) => Err(6),
51 };
52 Self { parts }
53 }
54
55 /// A version from its parts, `type` UnityPy's `UnityVersionType` value
56 /// (0 to 5, or 255; another is kept as the byte every read raises
57 /// for).
58 #[must_use]
59 pub const fn new(major: u16, minor: u16, build: u16, ty: u8, number: u8) -> Self {
60 let parts = if ty <= 5 || ty == 255 {
61 Ok([major, minor, build, ty as u16, number as u16])
62 } else {
63 Err(ty)
64 };
65 Self { parts }
66 }
67
68 /// The tuple, or `ValueError` for its type byte.
69 pub fn as_tuple(self) -> Result<[u16; 5], MeshError> {
70 self.parts.map_err(MeshError::VersionType)
71 }
72
73 /// `version[0]`.
74 pub fn major(self) -> Result<u16, MeshError> {
75 self.as_tuple().map(|[major, ..]| major)
76 }
77
78 /// `version >= other`, `other` a tuple of at most five parts.
79 pub fn at_least(self, other: &[u16]) -> Result<bool, MeshError> {
80 // UnityPy helpers/UnityVersion.py:132-140: `>` or `==`, each on
81 // `as_tuple()`, so Python's tuple order.
82 self.as_tuple().map(|t| t.as_slice() >= other)
83 }
84
85 /// `version[:2] == (major, minor)`.
86 pub fn minor_is(self, major: u16, minor: u16) -> Result<bool, MeshError> {
87 self.as_tuple().map(|[a, b, ..]| a == major && b == minor)
88 }
89}
90
91#[cfg(test)]
92mod tests {
93 use unityrs_core::{RawStr, UnityVersion};
94
95 use super::Version;
96 use crate::error::MeshError;
97
98 fn parsed(s: &str) -> Version {
99 Version::of(&UnityVersion::parse(&RawStr::from(s)).unwrap())
100 }
101
102 #[test]
103 fn a_file_s_version_reads_as_unitypy_s_tuple_or_its_type_byte_s_error() {
104 assert_eq!(parsed("2019.4.0f1"), Version::new(2019, 4, 0, 3, 1));
105 // A type number of 256 or more is OR-ed into the type byte (module
106 // docs): `a` (0) reads as `b` (1), and `f` (3) as 7 from 1024, no
107 // member, which every read raises for.
108 assert_eq!(parsed("2019.4.0a256"), Version::new(2019, 4, 0, 1, 0));
109 let v = parsed("2019.4.0f1024");
110 assert!(matches!(v.major(), Err(MeshError::VersionType(7))));
111 assert_eq!(
112 v.as_tuple().unwrap_err().python(),
113 Some(("ValueError", "7 is not a valid UnityVersionType".to_owned()))
114 );
115 // A packed version of type 6, and of `u` (255), which is a member.
116 let packed = |ty: u64| {
117 Version::of(&UnityVersion::from_packed(
118 (2019 << 48) | (4 << 32) | (ty << 8) | 1,
119 ))
120 };
121 assert!(matches!(
122 packed(6).at_least(&[2017, 4]),
123 Err(MeshError::VersionType(6))
124 ));
125 assert_eq!(packed(6), Version::new(2019, 4, 0, 6, 1));
126 assert_eq!(packed(255).as_tuple().unwrap(), [2019, 4, 0, 255, 1]);
127 }
128}