use std::collections::HashSet;
use std::fmt;
use crate::bytes::{In, Out, fits_u32};
use crate::container::ChunkTag;
use crate::scene::Scene;
pub const METADATA_TAG: ChunkTag = ChunkTag(*b"META");
pub const METADATA_VERSION: u16 = 1;
pub const TEXT_KEYS: [&str; 8] = [
"title",
"description",
"designer",
"copyright",
"license",
"source",
"created",
"generator",
];
pub const UUID_KEY: &str = "uuid";
const FILE: u32 = u32::MAX;
const MAX_KEY: usize = 64;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MetadataEntry {
pub node: Option<usize>,
pub key: String,
pub value: Vec<u8>,
}
impl MetadataEntry {
pub fn text(node: Option<usize>, key: &str, text: &str) -> Self {
Self {
node,
key: key.into(),
value: text.as_bytes().to_vec(),
}
}
pub fn uuid(node: Option<usize>, uuid: [u8; 16]) -> Self {
Self {
node,
key: UUID_KEY.into(),
value: uuid.to_vec(),
}
}
pub fn as_text(&self) -> Option<&str> {
match key_kind(self.key.as_bytes()) {
KeyKind::Text => std::str::from_utf8(&self.value).ok(),
_ => None,
}
}
pub fn as_uuid(&self) -> Option<[u8; 16]> {
match key_kind(self.key.as_bytes()) {
KeyKind::Uuid => self.value.as_slice().try_into().ok(),
_ => None,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum EncodeMetadataError {
NoSuchNode { node: usize },
BadKey { key: String },
ReservedKey { key: String },
BadValue { key: String },
SameEntry { key: String },
TooLarge,
}
impl fmt::Display for EncodeMetadataError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NoSuchNode { node } => write!(
f,
"metadata names node {node}, which the scene does not have"
),
Self::BadKey { key } => write!(f, "{key:?} is not a metadata key"),
Self::ReservedKey { key } => write!(f, "the metadata key {key:?} is reserved"),
Self::BadValue { key } => write!(
f,
"the value of the metadata key {key:?} is not what it takes"
),
Self::SameEntry { key } => write!(
f,
"two metadata entries have the same subject and the key {key:?}"
),
Self::TooLarge => f.write_str("the metadata is too large for its chunk"),
}
}
}
impl std::error::Error for EncodeMetadataError {}
#[derive(Clone, Copy, PartialEq, Eq)]
enum KeyKind {
Text,
Uuid,
Program,
Reserved,
Invalid,
}
fn key_kind(key: &[u8]) -> KeyKind {
let well_formed = (1..=MAX_KEY).contains(&key.len())
&& key[0].is_ascii_lowercase()
&& key
.iter()
.all(|&b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"._-".contains(&b));
if !well_formed {
return KeyKind::Invalid;
}
if key.contains(&b'.') {
return KeyKind::Program;
}
if key == UUID_KEY.as_bytes() {
return KeyKind::Uuid;
}
if TEXT_KEYS.iter().any(|text| text.as_bytes() == key) {
return KeyKind::Text;
}
KeyKind::Reserved
}
fn fits(kind: KeyKind, value: &[u8]) -> bool {
match kind {
KeyKind::Text => std::str::from_utf8(value).is_ok(),
KeyKind::Uuid => value.len() == 16,
KeyKind::Program => true,
KeyKind::Reserved | KeyKind::Invalid => false,
}
}
pub fn encode_metadata(
entries: &[MetadataEntry],
scene: &Scene,
) -> Result<Vec<u8>, EncodeMetadataError> {
let mut seen = HashSet::new();
for entry in entries {
if let Some(node) = entry.node
&& node >= scene.nodes.len()
{
return Err(EncodeMetadataError::NoSuchNode { node });
}
let key = entry.key.clone();
match key_kind(entry.key.as_bytes()) {
KeyKind::Invalid => return Err(EncodeMetadataError::BadKey { key }),
KeyKind::Reserved => return Err(EncodeMetadataError::ReservedKey { key }),
kind if !fits(kind, &entry.value) => {
return Err(EncodeMetadataError::BadValue { key });
}
_ => {}
}
if !seen.insert((entry.node, entry.key.as_str())) {
return Err(EncodeMetadataError::SameEntry { key });
}
}
if !fits_u32(entries.len()) || entries.iter().any(|entry| !fits_u32(entry.value.len())) {
return Err(EncodeMetadataError::TooLarge);
}
let mut out = Out::default();
out.len(entries.len());
for entry in entries {
out.u32(entry.node.map_or(FILE, |node| node as u32));
out.bytes(entry.key.as_bytes());
out.bytes(&entry.value);
}
Ok(out.0)
}
pub fn decode_metadata(payload: &[u8], scene: &Scene) -> Vec<MetadataEntry> {
let Some(raw) = split(payload) else {
return Vec::new();
};
let mut seen = HashSet::new();
let mut entries = Vec::new();
for (subject, key, value) in raw {
if !seen.insert((subject, key)) {
continue;
}
let node = match subject {
FILE => None,
node if (node as usize) < scene.nodes.len() => Some(node as usize),
_ => continue,
};
let kind = key_kind(key);
if !fits(kind, value) {
continue;
}
entries.push(MetadataEntry {
node,
key: String::from_utf8_lossy(key).into_owned(),
value: value.to_vec(),
});
}
entries
}
type RawEntry<'a> = (u32, &'a [u8], &'a [u8]);
fn split(payload: &[u8]) -> Option<Vec<RawEntry<'_>>> {
let mut input = In(payload);
let count = input.count(12)?;
let mut raw = Vec::with_capacity(count);
for _ in 0..count {
let subject = input.u32()?;
let key = input.bytes()?;
let value = input.bytes()?;
raw.push((subject, key, value));
}
input.is_empty().then_some(raw)
}