1use std::collections::HashSet;
23use std::fmt;
24
25use crate::bytes::{In, Out, fits_u32};
26use crate::container::ChunkTag;
27use crate::scene::Scene;
28
29pub const PROGRAM_TAG: ChunkTag = ChunkTag(*b"PROG");
31
32pub const PROGRAM_VERSION: u16 = 1;
34
35const FILE: u32 = u32::MAX;
37
38const MAX_NAME: usize = 64;
40
41#[derive(Clone, Debug, PartialEq, Eq)]
43pub struct ProgramEntry {
44 pub program: String,
47 pub node: Option<usize>,
50 pub version: u32,
52 pub document: Vec<u8>,
54}
55
56#[derive(Clone, Debug, PartialEq, Eq)]
58pub enum EncodeProgramDataError {
59 BadName { program: String },
62 NoSuchNode { node: usize },
64 SameEntry { program: String },
66 TooLarge,
68}
69
70impl fmt::Display for EncodeProgramDataError {
71 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72 match self {
73 Self::BadName { program } => write!(f, "{program:?} is not a program name"),
74 Self::NoSuchNode { node } => write!(
75 f,
76 "program data names node {node}, which the scene does not have"
77 ),
78 Self::SameEntry { program } => write!(
79 f,
80 "two program data entries of {program:?} have the same subject"
81 ),
82 Self::TooLarge => f.write_str("the program data is too large for its chunk"),
83 }
84 }
85}
86
87impl std::error::Error for EncodeProgramDataError {}
88
89#[derive(Clone, Debug, PartialEq, Eq)]
91pub enum DecodeProgramDataError {
92 Malformed,
95 NoSuchNode,
97 SameEntry,
99}
100
101impl fmt::Display for DecodeProgramDataError {
102 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103 match self {
104 Self::Malformed => f.write_str("the program data is malformed"),
105 Self::NoSuchNode => f.write_str("program data names a node the scene does not have"),
106 Self::SameEntry => {
107 f.write_str("two program data entries have the same program and subject")
108 }
109 }
110 }
111}
112
113impl std::error::Error for DecodeProgramDataError {}
114
115pub fn is_program_name(name: &str) -> bool {
120 is_name(name.as_bytes())
121}
122
123pub(crate) fn is_name(name: &[u8]) -> bool {
125 (1..=MAX_NAME).contains(&name.len())
126 && name[0].is_ascii_lowercase()
127 && name
128 .iter()
129 .all(|&b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"._-".contains(&b))
130}
131
132pub fn encode_program_data(
135 entries: &[ProgramEntry],
136 scene: &Scene,
137) -> Result<Vec<u8>, EncodeProgramDataError> {
138 let mut seen = HashSet::new();
139 for entry in entries {
140 if !is_name(entry.program.as_bytes()) {
141 return Err(EncodeProgramDataError::BadName {
142 program: entry.program.clone(),
143 });
144 }
145 if let Some(node) = entry.node
146 && node >= scene.nodes.len()
147 {
148 return Err(EncodeProgramDataError::NoSuchNode { node });
149 }
150 if !seen.insert((entry.program.as_str(), entry.node)) {
151 return Err(EncodeProgramDataError::SameEntry {
152 program: entry.program.clone(),
153 });
154 }
155 }
156 if !fits_u32(entries.len()) || entries.iter().any(|entry| !fits_u32(entry.document.len())) {
157 return Err(EncodeProgramDataError::TooLarge);
158 }
159 let mut out = Out::default();
160 out.len(entries.len());
161 for entry in entries {
162 out.bytes(entry.program.as_bytes());
163 out.u32(entry.node.map_or(FILE, |node| node as u32));
165 out.u32(entry.version);
166 out.bytes(&entry.document);
167 }
168 Ok(out.0)
169}
170
171pub fn decode_program_data(
174 payload: &[u8],
175 scene: &Scene,
176) -> Result<Vec<ProgramEntry>, DecodeProgramDataError> {
177 let mut input = In(payload);
178 let malformed = DecodeProgramDataError::Malformed;
179 let count = input.count(17).ok_or(malformed.clone())?;
180 let mut entries = Vec::with_capacity(count);
181 for _ in 0..count {
182 let name = input.bytes().ok_or(malformed.clone())?;
183 if !is_name(name) {
184 return Err(malformed);
185 }
186 let subject = input.u32().ok_or(malformed.clone())?;
187 let version = input.u32().ok_or(malformed.clone())?;
188 let document = input.bytes().ok_or(malformed.clone())?;
189 entries.push((name, subject, version, document));
190 }
191 if !input.is_empty() {
192 return Err(malformed);
193 }
194 let mut seen = HashSet::new();
195 let mut out = Vec::with_capacity(entries.len());
196 for (name, subject, version, document) in entries {
197 let node = match subject {
198 FILE => None,
199 node if (node as usize) < scene.nodes.len() => Some(node as usize),
200 _ => return Err(DecodeProgramDataError::NoSuchNode),
201 };
202 if !seen.insert((name, node)) {
203 return Err(DecodeProgramDataError::SameEntry);
204 }
205 out.push(ProgramEntry {
206 program: String::from_utf8_lossy(name).into_owned(),
208 node,
209 version,
210 document: document.to_vec(),
211 });
212 }
213 Ok(out)
214}