use super::AlembicError;
pub struct Ogawa<'a> {
pub data: &'a [u8],
pub root: usize,
pub version: u16,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Child {
Group(usize),
Data(usize),
Empty,
}
impl<'a> Ogawa<'a> {
pub fn open(data: &'a [u8]) -> Result<Self, AlembicError> {
if data.len() < 16 || &data[..5] != b"Ogawa" {
return Err(AlembicError::NotAlembic);
}
if data[5] != 0xff {
return Err(AlembicError::Incomplete);
}
let version = u16::from_be_bytes([data[6], data[7]]);
let root = u64::from_le_bytes(data[8..16].try_into().unwrap()) as usize;
if root >= data.len() {
return Err(AlembicError::Corrupt);
}
Ok(Ogawa {
data,
root,
version,
})
}
fn u64_at(&self, at: usize) -> Result<u64, AlembicError> {
let b = self.data.get(at..at + 8).ok_or(AlembicError::Truncated)?;
Ok(u64::from_le_bytes(b.try_into().unwrap()))
}
pub fn group(&self, at: usize) -> Result<Vec<Child>, AlembicError> {
let count = self.u64_at(at)? as usize;
if count.saturating_mul(8) > self.data.len() {
return Err(AlembicError::Corrupt);
}
let mut out = Vec::with_capacity(count.min(4096));
for i in 0..count {
let reference = self.u64_at(at + 8 + i * 8)?;
let offset = (reference & !(1u64 << 63)) as usize;
out.push(if offset == 0 {
Child::Empty
} else if reference >> 63 != 0 {
Child::Data(offset)
} else {
Child::Group(offset)
});
}
Ok(out)
}
pub fn data_at(&self, at: usize) -> Result<&'a [u8], AlembicError> {
let size = self.u64_at(at)? as usize;
self.data
.get(at + 8..at + 8 + size)
.ok_or(AlembicError::Truncated)
}
pub fn child_data(&self, children: &[Child], index: usize) -> Option<&'a [u8]> {
match children.get(index) {
Some(Child::Data(at)) => self.data_at(*at).ok(),
_ => None,
}
}
}