use unityrs_core::UnityVersion;
use unityrs_core::version::VersionError;
use crate::error::MeshError;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Version {
parts: Result<[u16; 5], u8>,
}
const _: () = crate::send_sync::<Version>();
impl Version {
#[must_use]
pub fn of(version: &UnityVersion) -> Self {
let parts = match version.as_tuple() {
Ok((major, minor, build, ty, number)) => {
Ok([major, minor, build, u16::from(ty), u16::from(number)])
}
Err(VersionError::TypeByte(b)) => Err(b),
Err(_) => Err(6),
};
Self { parts }
}
#[must_use]
pub const fn new(major: u16, minor: u16, build: u16, ty: u8, number: u8) -> Self {
let parts = if ty <= 5 || ty == 255 {
Ok([major, minor, build, ty as u16, number as u16])
} else {
Err(ty)
};
Self { parts }
}
pub fn as_tuple(self) -> Result<[u16; 5], MeshError> {
self.parts.map_err(MeshError::VersionType)
}
pub fn major(self) -> Result<u16, MeshError> {
self.as_tuple().map(|[major, ..]| major)
}
pub fn at_least(self, other: &[u16]) -> Result<bool, MeshError> {
self.as_tuple().map(|t| t.as_slice() >= other)
}
pub fn minor_is(self, major: u16, minor: u16) -> Result<bool, MeshError> {
self.as_tuple().map(|[a, b, ..]| a == major && b == minor)
}
}
#[cfg(test)]
mod tests {
use unityrs_core::{RawStr, UnityVersion};
use super::Version;
use crate::error::MeshError;
fn parsed(s: &str) -> Version {
Version::of(&UnityVersion::parse(&RawStr::from(s)).unwrap())
}
#[test]
fn a_file_s_version_reads_as_unitypy_s_tuple_or_its_type_byte_s_error() {
assert_eq!(parsed("2019.4.0f1"), Version::new(2019, 4, 0, 3, 1));
assert_eq!(parsed("2019.4.0a256"), Version::new(2019, 4, 0, 1, 0));
let v = parsed("2019.4.0f1024");
assert!(matches!(v.major(), Err(MeshError::VersionType(7))));
assert_eq!(
v.as_tuple().unwrap_err().python(),
Some(("ValueError", "7 is not a valid UnityVersionType".to_owned()))
);
let packed = |ty: u64| {
Version::of(&UnityVersion::from_packed(
(2019 << 48) | (4 << 32) | (ty << 8) | 1,
))
};
assert!(matches!(
packed(6).at_least(&[2017, 4]),
Err(MeshError::VersionType(6))
));
assert_eq!(packed(6), Version::new(2019, 4, 0, 6, 1));
assert_eq!(packed(255).as_tuple().unwrap(), [2019, 4, 0, 255, 1]);
}
}