use super::{Error, In, Result};
use std::fmt;
const NAMES: [&str; 6] = [
"CELLNAME",
"TEXTSTRING",
"PROPNAME",
"PROPSTRING",
"LAYERNAME",
"XNAME",
];
pub(super) type Directory = [(bool, u64); 6];
#[derive(Default, Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct Location {
pub file: u64,
pub local: Option<u64>,
}
impl fmt::Display for Location {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "file offset {}", self.file)?;
if let Some(local) = self.local {
write!(f, ", CBLOCK offset {local}")?;
}
Ok(())
}
}
impl Location {
pub fn annotate(self, e: Error) -> Error {
match e {
Error::Invalid(s) => Error::invalid(format!("{s} ({self})")),
Error::Unsupported(s) => Error::unsupported(format!("{s} ({self})")),
Error::Io(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => {
Error::invalid(format!("unexpected end of OASIS input ({self})"))
}
Error::Io(e) => Error::Io(std::io::Error::new(e.kind(), format!("{e} ({self})"))),
}
}
}
#[derive(Default)]
pub(super) struct Observed {
first: [Option<Location>; 6],
split: [Option<Location>; 6],
inline: [Option<Location>; 6],
active: Option<usize>,
targets: Vec<(u64, usize)>,
}
impl Observed {
pub fn record(&mut self, id: u64, pos: Location) {
if matches!(id, 0 | 28 | 29) {
return;
} let kind = match id {
3 | 4 => 0,
5 | 6 => 1,
7 | 8 => 2,
9 | 10 => 3,
11 | 12 => 4,
30 | 31 => 5,
_ => {
self.active = None;
return;
}
};
if self.first[kind].is_some() && self.active != Some(kind) {
self.split[kind].get_or_insert(pos);
}
self.first[kind].get_or_insert(pos);
self.active = Some(kind);
if pos.local.is_none_or(|offset| offset == 0) {
self.targets.push((pos.file, kind));
}
}
pub fn literal(&mut self, kind: usize, at: Location) {
self.inline[kind].get_or_insert(at);
}
pub fn validate(&self, dir: Directory) -> Result<()> {
for (kind, (strict, offset)) in dir.into_iter().enumerate() {
let name = NAMES[kind];
if offset != 0 && self.targets.binary_search(&(offset, kind)).is_err() {
return Err(Error::invalid(format!(
"OASIS {name} table at file offset {offset} does not point to a matching record boundary"
)));
}
if !strict {
continue;
}
if let Some(first) = self.first[kind]
&& (first.local.is_some_and(|p| p != 0) || first.file != offset)
{
return Err(first.annotate(Error::invalid(format!(
"OASIS strict {name} table offset {offset} does not identify its first record"
))));
}
if let Some(at) = self.split[kind] {
return Err(at.annotate(Error::invalid(format!(
"discontiguous OASIS strict {name} table"
))));
}
if let Some(at) = self.inline[kind] {
return Err(at.annotate(Error::invalid(format!(
"literal value used for strict OASIS {name} table"
))));
}
}
Ok(())
}
}
pub(super) fn read(input: &mut In) -> Result<Directory> {
let mut entries = [(false, 0); 6];
for entry in &mut entries {
let flag = input.uint()?;
if flag > 1 {
return Err(Error::invalid("invalid OASIS offset-table flag"));
}
*entry = (flag == 1, input.uint()?);
}
Ok(entries)
}