1use std::collections::HashSet;
22use std::fmt;
23
24use crate::bytes::{In, Out, fits_u32};
25use crate::container::ChunkTag;
26use crate::scene::Scene;
27
28pub const METADATA_TAG: ChunkTag = ChunkTag(*b"META");
30
31pub const METADATA_VERSION: u16 = 1;
33
34pub const TEXT_KEYS: [&str; 8] = [
36 "title",
37 "description",
38 "designer",
39 "copyright",
40 "license",
41 "source",
42 "created",
43 "generator",
44];
45
46pub const UUID_KEY: &str = "uuid";
48
49const FILE: u32 = u32::MAX;
51
52const MAX_KEY: usize = 64;
54
55#[derive(Clone, Debug, PartialEq, Eq)]
57pub struct MetadataEntry {
58 pub node: Option<usize>,
61 pub key: String,
64 pub value: Vec<u8>,
67}
68
69impl MetadataEntry {
70 pub fn text(node: Option<usize>, key: &str, text: &str) -> Self {
72 Self {
73 node,
74 key: key.into(),
75 value: text.as_bytes().to_vec(),
76 }
77 }
78
79 pub fn uuid(node: Option<usize>, uuid: [u8; 16]) -> Self {
81 Self {
82 node,
83 key: UUID_KEY.into(),
84 value: uuid.to_vec(),
85 }
86 }
87
88 pub fn as_text(&self) -> Option<&str> {
90 match key_kind(self.key.as_bytes()) {
91 KeyKind::Text => std::str::from_utf8(&self.value).ok(),
92 _ => None,
93 }
94 }
95
96 pub fn as_uuid(&self) -> Option<[u8; 16]> {
98 match key_kind(self.key.as_bytes()) {
99 KeyKind::Uuid => self.value.as_slice().try_into().ok(),
100 _ => None,
101 }
102 }
103}
104
105#[derive(Clone, Debug, PartialEq, Eq)]
107pub enum EncodeMetadataError {
108 NoSuchNode { node: usize },
110 BadKey { key: String },
113 ReservedKey { key: String },
115 BadValue { key: String },
118 SameEntry { key: String },
120 TooLarge,
122}
123
124impl fmt::Display for EncodeMetadataError {
125 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
126 match self {
127 Self::NoSuchNode { node } => write!(
128 f,
129 "metadata names node {node}, which the scene does not have"
130 ),
131 Self::BadKey { key } => write!(f, "{key:?} is not a metadata key"),
132 Self::ReservedKey { key } => write!(f, "the metadata key {key:?} is reserved"),
133 Self::BadValue { key } => write!(
134 f,
135 "the value of the metadata key {key:?} is not what it takes"
136 ),
137 Self::SameEntry { key } => write!(
138 f,
139 "two metadata entries have the same subject and the key {key:?}"
140 ),
141 Self::TooLarge => f.write_str("the metadata is too large for its chunk"),
142 }
143 }
144}
145
146impl std::error::Error for EncodeMetadataError {}
147
148#[derive(Clone, Copy, PartialEq, Eq)]
150enum KeyKind {
151 Text,
153 Uuid,
155 Program,
157 Reserved,
159 Invalid,
161}
162
163fn key_kind(key: &[u8]) -> KeyKind {
164 let well_formed = (1..=MAX_KEY).contains(&key.len())
165 && key[0].is_ascii_lowercase()
166 && key
167 .iter()
168 .all(|&b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"._-".contains(&b));
169 if !well_formed {
170 return KeyKind::Invalid;
171 }
172 if key.contains(&b'.') {
173 return KeyKind::Program;
174 }
175 if key == UUID_KEY.as_bytes() {
176 return KeyKind::Uuid;
177 }
178 if TEXT_KEYS.iter().any(|text| text.as_bytes() == key) {
179 return KeyKind::Text;
180 }
181 KeyKind::Reserved
182}
183
184fn fits(kind: KeyKind, value: &[u8]) -> bool {
186 match kind {
187 KeyKind::Text => std::str::from_utf8(value).is_ok(),
188 KeyKind::Uuid => value.len() == 16,
189 KeyKind::Program => true,
190 KeyKind::Reserved | KeyKind::Invalid => false,
191 }
192}
193
194pub fn encode_metadata(
197 entries: &[MetadataEntry],
198 scene: &Scene,
199) -> Result<Vec<u8>, EncodeMetadataError> {
200 let mut seen = HashSet::new();
201 for entry in entries {
202 if let Some(node) = entry.node
203 && node >= scene.nodes.len()
204 {
205 return Err(EncodeMetadataError::NoSuchNode { node });
206 }
207 let key = entry.key.clone();
208 match key_kind(entry.key.as_bytes()) {
209 KeyKind::Invalid => return Err(EncodeMetadataError::BadKey { key }),
210 KeyKind::Reserved => return Err(EncodeMetadataError::ReservedKey { key }),
211 kind if !fits(kind, &entry.value) => {
212 return Err(EncodeMetadataError::BadValue { key });
213 }
214 _ => {}
215 }
216 if !seen.insert((entry.node, entry.key.as_str())) {
217 return Err(EncodeMetadataError::SameEntry { key });
218 }
219 }
220 if !fits_u32(entries.len()) || entries.iter().any(|entry| !fits_u32(entry.value.len())) {
221 return Err(EncodeMetadataError::TooLarge);
222 }
223 let mut out = Out::default();
224 out.len(entries.len());
225 for entry in entries {
226 out.u32(entry.node.map_or(FILE, |node| node as u32));
228 out.bytes(entry.key.as_bytes());
229 out.bytes(&entry.value);
230 }
231 Ok(out.0)
232}
233
234pub fn decode_metadata(payload: &[u8], scene: &Scene) -> Vec<MetadataEntry> {
238 let Some(raw) = split(payload) else {
239 return Vec::new();
240 };
241 let mut seen = HashSet::new();
242 let mut entries = Vec::new();
243 for (subject, key, value) in raw {
244 if !seen.insert((subject, key)) {
247 continue;
248 }
249 let node = match subject {
250 FILE => None,
251 node if (node as usize) < scene.nodes.len() => Some(node as usize),
252 _ => continue,
253 };
254 let kind = key_kind(key);
255 if !fits(kind, value) {
256 continue;
257 }
258 entries.push(MetadataEntry {
259 node,
260 key: String::from_utf8_lossy(key).into_owned(),
262 value: value.to_vec(),
263 });
264 }
265 entries
266}
267
268type RawEntry<'a> = (u32, &'a [u8], &'a [u8]);
270
271fn split(payload: &[u8]) -> Option<Vec<RawEntry<'_>>> {
273 let mut input = In(payload);
274 let count = input.count(12)?;
275 let mut raw = Vec::with_capacity(count);
276 for _ in 0..count {
277 let subject = input.u32()?;
278 let key = input.bytes()?;
279 let value = input.bytes()?;
280 raw.push((subject, key, value));
281 }
282 input.is_empty().then_some(raw)
283}