use std::collections::HashSet;
use std::fmt;
use crate::bytes::{In, Out, fits_u32};
use crate::container::ChunkTag;
use crate::scene::Scene;
pub const PROGRAM_TAG: ChunkTag = ChunkTag(*b"PROG");
pub const PROGRAM_VERSION: u16 = 1;
const FILE: u32 = u32::MAX;
const MAX_NAME: usize = 64;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ProgramEntry {
pub program: String,
pub node: Option<usize>,
pub version: u32,
pub document: Vec<u8>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum EncodeProgramDataError {
BadName { program: String },
NoSuchNode { node: usize },
SameEntry { program: String },
TooLarge,
}
impl fmt::Display for EncodeProgramDataError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::BadName { program } => write!(f, "{program:?} is not a program name"),
Self::NoSuchNode { node } => write!(
f,
"program data names node {node}, which the scene does not have"
),
Self::SameEntry { program } => write!(
f,
"two program data entries of {program:?} have the same subject"
),
Self::TooLarge => f.write_str("the program data is too large for its chunk"),
}
}
}
impl std::error::Error for EncodeProgramDataError {}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DecodeProgramDataError {
Malformed,
NoSuchNode,
SameEntry,
}
impl fmt::Display for DecodeProgramDataError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Malformed => f.write_str("the program data is malformed"),
Self::NoSuchNode => f.write_str("program data names a node the scene does not have"),
Self::SameEntry => {
f.write_str("two program data entries have the same program and subject")
}
}
}
}
impl std::error::Error for DecodeProgramDataError {}
pub fn is_program_name(name: &str) -> bool {
is_name(name.as_bytes())
}
pub(crate) fn is_name(name: &[u8]) -> bool {
(1..=MAX_NAME).contains(&name.len())
&& name[0].is_ascii_lowercase()
&& name
.iter()
.all(|&b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"._-".contains(&b))
}
pub fn encode_program_data(
entries: &[ProgramEntry],
scene: &Scene,
) -> Result<Vec<u8>, EncodeProgramDataError> {
let mut seen = HashSet::new();
for entry in entries {
if !is_name(entry.program.as_bytes()) {
return Err(EncodeProgramDataError::BadName {
program: entry.program.clone(),
});
}
if let Some(node) = entry.node
&& node >= scene.nodes.len()
{
return Err(EncodeProgramDataError::NoSuchNode { node });
}
if !seen.insert((entry.program.as_str(), entry.node)) {
return Err(EncodeProgramDataError::SameEntry {
program: entry.program.clone(),
});
}
}
if !fits_u32(entries.len()) || entries.iter().any(|entry| !fits_u32(entry.document.len())) {
return Err(EncodeProgramDataError::TooLarge);
}
let mut out = Out::default();
out.len(entries.len());
for entry in entries {
out.bytes(entry.program.as_bytes());
out.u32(entry.node.map_or(FILE, |node| node as u32));
out.u32(entry.version);
out.bytes(&entry.document);
}
Ok(out.0)
}
pub fn decode_program_data(
payload: &[u8],
scene: &Scene,
) -> Result<Vec<ProgramEntry>, DecodeProgramDataError> {
let mut input = In(payload);
let malformed = DecodeProgramDataError::Malformed;
let count = input.count(17).ok_or(malformed.clone())?;
let mut entries = Vec::with_capacity(count);
for _ in 0..count {
let name = input.bytes().ok_or(malformed.clone())?;
if !is_name(name) {
return Err(malformed);
}
let subject = input.u32().ok_or(malformed.clone())?;
let version = input.u32().ok_or(malformed.clone())?;
let document = input.bytes().ok_or(malformed.clone())?;
entries.push((name, subject, version, document));
}
if !input.is_empty() {
return Err(malformed);
}
let mut seen = HashSet::new();
let mut out = Vec::with_capacity(entries.len());
for (name, subject, version, document) in entries {
let node = match subject {
FILE => None,
node if (node as usize) < scene.nodes.len() => Some(node as usize),
_ => return Err(DecodeProgramDataError::NoSuchNode),
};
if !seen.insert((name, node)) {
return Err(DecodeProgramDataError::SameEntry);
}
out.push(ProgramEntry {
program: String::from_utf8_lossy(name).into_owned(),
node,
version,
document: document.to_vec(),
});
}
Ok(out)
}