#![deny(missing_docs, clippy::disallowed_methods, clippy::disallowed_types)]
#![cfg_attr(
not(test),
deny(
clippy::indexing_slicing,
clippy::arithmetic_side_effects,
clippy::cast_possible_truncation
)
)]
use primase_foundations::bytes::Endian;
pub mod binding;
pub mod bundle;
pub mod bytecode;
pub mod cas;
pub mod db;
pub mod depot;
pub mod ebx;
pub mod fbmod;
pub mod folder;
pub mod inputlayout;
pub mod layout;
pub mod listing;
pub mod lookup;
pub mod meshset;
pub mod names;
pub mod paramdb;
pub mod permutation;
pub mod physics;
pub mod rigid;
pub mod scope;
pub mod selector;
pub mod skeleton;
pub mod tangent;
pub mod texture;
pub mod toc;
pub const MESHSET: u32 = 0x49B1_56D4;
pub const TEXTURE: u32 = 0x6BDE_20BA;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("{what} at {offset:#x}: {detail}")]
Format {
what: &'static str,
offset: usize,
detail: String,
},
#[error("{}: {source}", path.display())]
Io {
path: std::path::PathBuf,
source: std::io::Error,
},
#[error("cas: {0}")]
Cas(#[from] primase_foundations::compress::Error),
#[error("{0}")]
Missing(String),
#[error("{0}")]
Unsupported(String),
}
pub type Result<T, E = Error> = std::result::Result<T, E>;
pub fn djb2(name: &str) -> u32 {
name.bytes()
.fold(5381u32, |h, b| h.wrapping_mul(33) ^ u32::from(b))
}
pub fn guid_text(g: &[u8; 16]) -> String {
let [a0, a1, a2, a3, b0, b1, c0, c1, d0, d1, e0, e1, e2, e3, e4, e5] = *g;
format!(
"{a3:02x}{a2:02x}{a1:02x}{a0:02x}-{b1:02x}{b0:02x}-{c1:02x}{c0:02x}-{d0:02x}{d1:02x}-{e0:02x}{e1:02x}{e2:02x}{e3:02x}{e4:02x}{e5:02x}"
)
}
pub fn hex(bytes: &[u8]) -> String {
use std::fmt::Write;
bytes.iter().fold(
String::with_capacity(bytes.len().saturating_mul(2)),
|mut s, b| {
let _ = write!(s, "{b:02x}");
s
},
)
}
pub fn bad(what: &'static str, offset: usize, detail: impl Into<String>) -> Error {
Error::Format {
what,
offset,
detail: detail.into(),
}
}
pub(crate) fn past_end(
what: &'static str,
e: primase_foundations::bytes::BoundsError,
total: usize,
) -> Error {
let at = usize::try_from(e.absolute()).unwrap_or(usize::MAX);
let length = match e {
primase_foundations::bytes::BoundsError::OutOfBounds { length, .. } => length,
primase_foundations::bytes::BoundsError::LengthOverflow { count, stride, .. } => {
count.saturating_mul(stride)
}
};
bad(what, at, format!("{length} bytes past the end ({total} bytes)"))
}
impl From<primase_foundations::bytes::BoundsError> for Error {
fn from(e: primase_foundations::bytes::BoundsError) -> Self {
match e {
primase_foundations::bytes::BoundsError::OutOfBounds { total, .. } => past_end("read", e, total),
primase_foundations::bytes::BoundsError::LengthOverflow { count, stride, .. } => bad(
"read",
usize::try_from(e.absolute()).unwrap_or(usize::MAX),
format!("{count} entries of {stride} bytes overflow"),
),
}
}
}
#[derive(Debug)]
pub struct Rd<'a> {
pub data: &'a [u8],
pub what: &'static str,
}
impl<'a> Rd<'a> {
pub fn new(data: &'a [u8], what: &'static str) -> Self {
Self { data, what }
}
pub fn bytes(&self, at: usize, n: usize) -> Result<&'a [u8]> {
primase_foundations::bytes::View::new(self.data)
.slice(at, n)
.map_err(|e| past_end(self.what, e, self.data.len()))
}
pub fn arr<const N: usize>(&self, at: usize) -> Result<[u8; N]> {
primase_foundations::bytes::View::new(self.data)
.array(at)
.map_err(|e| past_end(self.what, e, self.data.len()))
}
pub fn u8(&self, at: usize) -> Result<u8> {
primase_foundations::bytes::View::new(self.data)
.u8(at)
.map_err(|e| past_end(self.what, e, self.data.len()))
}
pub fn u16le(&self, at: usize) -> Result<u16> {
self.number(at, Endian::Little, primase_foundations::bytes::View::u16)
}
pub fn u32le(&self, at: usize) -> Result<u32> {
self.number(at, Endian::Little, primase_foundations::bytes::View::u32)
}
pub fn u64le(&self, at: usize) -> Result<u64> {
self.number(at, Endian::Little, primase_foundations::bytes::View::u64)
}
pub fn size32le(&self, at: usize) -> Result<usize> {
let v = self.u32le(at)?;
usize::try_from(v).map_err(|_| bad(self.what, at, format!("{v:#x} does not fit the address space")))
}
pub fn offset64le(&self, at: usize) -> Result<usize> {
let v = self.u64le(at)?;
usize::try_from(v).map_err(|_| bad(self.what, at, format!("{v:#x} does not fit the address space")))
}
pub fn u32be(&self, at: usize) -> Result<u32> {
self.number(at, Endian::Big, primase_foundations::bytes::View::u32)
}
pub fn i32be(&self, at: usize) -> Result<i32> {
self.number(at, Endian::Big, primase_foundations::bytes::View::i32)
}
pub fn u64be(&self, at: usize) -> Result<u64> {
self.number(at, Endian::Big, primase_foundations::bytes::View::u64)
}
fn number<T>(
&self,
at: usize,
e: Endian,
read: fn(
&primase_foundations::bytes::View<'a>,
usize,
Endian,
) -> std::result::Result<T, primase_foundations::bytes::BoundsError>,
) -> Result<T> {
read(&primase_foundations::bytes::View::new(self.data), at, e)
.map_err(|err| past_end(self.what, err, self.data.len()))
}
pub fn cstr(&self, at: usize) -> Result<String> {
let rest = self
.data
.get(at..)
.ok_or_else(|| bad(self.what, at, "string past the end"))?;
let mut parts = rest.splitn(2, |&b| b == 0);
match (parts.next(), parts.next()) {
(Some(text), Some(_)) => Ok(text.iter().map(|&b| char::from(b)).collect()),
_ => Err(bad(self.what, at, "unterminated string, expected a zero byte")),
}
}
}
pub fn latin1(s: &str, what: &'static str) -> Result<Vec<u8>> {
s.chars()
.map(|c| u8::try_from(u32::from(c)).map_err(|_| bad(what, 0, format!("name {s:?} is not Latin-1"))))
.collect()
}
pub fn capacity(what: &'static str, count: usize, min_bytes: usize, remaining: usize) -> Result<usize> {
match primase_foundations::bytes::checked_span(0, count, min_bytes, remaining) {
Ok(_) => Ok(count),
_ => Err(bad(
what,
0,
format!("{count} entries of at least {min_bytes} bytes in {remaining} bytes"),
)),
}
}
pub fn u32_len(what: &'static str, n: usize) -> Result<u32> {
u32::try_from(n).map_err(|_| {
bad(
what,
0,
format!("{n} does not fit the 32-bit field it is stored in"),
)
})
}
pub fn at(base: usize, index: usize, stride: usize) -> usize {
base.saturating_add(index.saturating_mul(stride))
}
pub fn align(v: usize, a: usize) -> usize {
v.div_ceil(a).saturating_mul(a)
}
#[cfg(test)]
mod bounds_tests {
use super::*;
fn format_error(error: Error) -> (&'static str, usize, String) {
match error {
Error::Format { what, offset, detail } => (what, offset, detail),
other => panic!("expected a format error, got {other}"),
}
}
#[test]
fn wrapper_retains_bounds_and_error_context() {
let rd = Rd::new(&[1, 2, 3, 4], "bounds fixture");
assert!(rd.bytes(4, 0).unwrap().is_empty());
assert_eq!(rd.u32be(0).unwrap(), 0x01020304);
for (offset, length) in [(4, 1), (5, 0), (usize::MAX, 1)] {
let (what, at, detail) = format_error(rd.bytes(offset, length).unwrap_err());
assert_eq!((what, at), ("bounds fixture", offset));
assert_eq!(detail, format!("{length} bytes past the end (4 bytes)"));
}
assert_eq!(capacity("table", 2, 2, 4).unwrap(), 2);
assert_eq!(capacity("table", usize::MAX, 0, 0).unwrap(), usize::MAX);
for (count, stride) in [(3, 2), (usize::MAX, 2)] {
let (what, at, detail) = format_error(capacity("table", count, stride, 4).unwrap_err());
assert_eq!((what, at), ("table", 0));
assert_eq!(
detail,
format!("{count} entries of at least {stride} bytes in 4 bytes")
);
}
}
}