1use crate::topology::BrepSolid;
56use crate::{decode_solid, encode_solid, SolidNames};
57use std::collections::BTreeMap;
58
59pub const SNAPSHOT_FORMAT_VERSION: u32 = 1;
65
66const MAGIC: &[u8; 8] = b"BREPSNAP";
67
68#[derive(Debug, Clone)]
70pub struct RestoredSolid {
71 pub name: String,
72 pub solid: BrepSolid,
73}
74
75#[derive(Debug, Clone)]
79pub struct RestoredSnapshot {
80 pub solids: Vec<RestoredSolid>,
81 pub metadata: Vec<(String, serde_json::Map<String, serde_json::Value>)>,
82}
83
84pub fn snapshot_solids(solids: &[(&str, &BrepSolid)]) -> Result<String, String> {
94 let mut out = Vec::with_capacity(1024);
95 out.extend_from_slice(MAGIC);
96 push_u32(&mut out, SNAPSHOT_FORMAT_VERSION);
97 push_count(&mut out, solids.len())?;
98 let mut metadata = BTreeMap::<String, String>::new();
99 let mut capture = |name: &str| -> Result<(), String> {
100 if let Some(record) = crate::feature_pipeline::scene_metadata::own_record(name) {
101 let json = serde_json::to_string(&record)
102 .map_err(|error| format!("snapshot: metadata record for '{name}': {error}"))?;
103 metadata.insert(name.to_string(), json);
104 }
105 Ok(())
106 };
107 for (name, solid) in solids {
108 let (data, names) = encode_solid(solid)?;
109 let names_json = serde_json::to_string(&names)
110 .map_err(|error| format!("snapshot: names for '{name}': {error}"))?;
111 push_str(&mut out, name)?;
112 push_str(&mut out, &names_json)?;
113 push_count(&mut out, data.len())?;
114 for value in &data {
115 out.extend_from_slice(&value.to_le_bytes());
116 }
117 capture(name)?;
118 for face_name in names.faces.values() {
119 capture(face_name)?;
120 }
121 for edge_name in names.edges.values() {
122 capture(edge_name)?;
123 }
124 }
125 push_count(&mut out, metadata.len())?;
126 for (name, record_json) in &metadata {
127 push_str(&mut out, name)?;
128 push_str(&mut out, record_json)?;
129 }
130 Ok(seal(out))
131}
132
133fn seal(mut container: Vec<u8>) -> String {
135 let digest = fnv1a(&container);
136 container.extend_from_slice(&digest.to_le_bytes());
137 base64_encode(&container)
138}
139
140fn fnv1a(bytes: &[u8]) -> u64 {
144 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
145 for &byte in bytes {
146 hash ^= byte as u64;
147 hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
148 }
149 hash
150}
151
152pub fn snapshot_resident_solids(named_handles: &[(String, u32)]) -> Result<String, String> {
155 let mut owned = Vec::with_capacity(named_handles.len());
156 for (name, handle) in named_handles {
157 let solid = crate::with_registered_solid_str(*handle, |solid| Ok(solid.clone()))?;
158 owned.push((name.as_str(), solid));
159 }
160 let borrowed: Vec<(&str, &BrepSolid)> = owned
161 .iter()
162 .map(|(name, solid)| (*name, solid))
163 .collect();
164 snapshot_solids(&borrowed)
165}
166
167pub fn restore_solids(payload: &str) -> Result<RestoredSnapshot, String> {
174 let bytes = base64_decode(payload)?;
175 if bytes.len() < MAGIC.len() + 8 {
177 return Err("snapshot: payload too short".into());
178 }
179 let (body, trailer) = bytes.split_at(bytes.len() - 8);
180 let stored = u64::from_le_bytes(trailer.try_into().expect("8-byte trailer"));
181 if fnv1a(body) != stored {
182 return Err("snapshot: payload checksum mismatch (corrupted)".into());
183 }
184 let mut reader = ByteReader {
185 data: body,
186 cursor: 0,
187 };
188 if reader.take(MAGIC.len())? != MAGIC {
189 return Err("snapshot: not a BREP snapshot payload (bad magic)".into());
190 }
191 let version = reader.u32()?;
192 if version != SNAPSHOT_FORMAT_VERSION {
193 return Err(format!(
194 "snapshot: unsupported format version {version} (expected {SNAPSHOT_FORMAT_VERSION})"
195 ));
196 }
197 let solid_count = reader.u32()? as usize;
198 let mut solids = Vec::with_capacity(solid_count.min(1024));
199 for _ in 0..solid_count {
200 let name = reader.string()?;
201 let names_json = reader.string()?;
202 let names: SolidNames = serde_json::from_str(&names_json)
203 .map_err(|error| format!("snapshot: names for '{name}': {error}"))?;
204 let data = reader.f64_vec()?;
205 let solid = decode_solid(&data, &names)
206 .map_err(|error| format!("snapshot: solid '{name}': {error}"))?;
207 solids.push(RestoredSolid { name, solid });
208 }
209 let record_count = reader.u32()? as usize;
210 let mut metadata = Vec::with_capacity(record_count.min(4096));
211 for _ in 0..record_count {
212 let name = reader.string()?;
213 let record_json = reader.string()?;
214 let record: serde_json::Map<String, serde_json::Value> =
215 serde_json::from_str(&record_json)
216 .map_err(|error| format!("snapshot: metadata record for '{name}': {error}"))?;
217 metadata.push((name, record));
218 }
219 if reader.cursor != body.len() {
220 return Err("snapshot: trailing bytes after payload".into());
221 }
222 Ok(RestoredSnapshot { solids, metadata })
223}
224
225fn push_u32(out: &mut Vec<u8>, value: u32) {
230 out.extend_from_slice(&value.to_le_bytes());
231}
232
233fn push_count(out: &mut Vec<u8>, count: usize) -> Result<(), String> {
234 let value: u32 = count
235 .try_into()
236 .map_err(|_| format!("snapshot: count {count} exceeds u32"))?;
237 push_u32(out, value);
238 Ok(())
239}
240
241fn push_str(out: &mut Vec<u8>, text: &str) -> Result<(), String> {
242 push_count(out, text.len())?;
243 out.extend_from_slice(text.as_bytes());
244 Ok(())
245}
246
247struct ByteReader<'a> {
248 data: &'a [u8],
249 cursor: usize,
250}
251
252impl<'a> ByteReader<'a> {
253 fn take(&mut self, count: usize) -> Result<&'a [u8], String> {
254 let end = self
255 .cursor
256 .checked_add(count)
257 .ok_or("snapshot: truncated payload")?;
258 let slice = self
259 .data
260 .get(self.cursor..end)
261 .ok_or("snapshot: truncated payload")?;
262 self.cursor = end;
263 Ok(slice)
264 }
265
266 fn u32(&mut self) -> Result<u32, String> {
267 let raw = self.take(4)?;
268 Ok(u32::from_le_bytes([raw[0], raw[1], raw[2], raw[3]]))
269 }
270
271 fn string(&mut self) -> Result<String, String> {
272 let length = self.u32()? as usize;
273 let raw = self.take(length)?;
274 String::from_utf8(raw.to_vec()).map_err(|_| "snapshot: invalid UTF-8 string".into())
275 }
276
277 fn f64_vec(&mut self) -> Result<Vec<f64>, String> {
278 let count = self.u32()? as usize;
279 let raw = self.take(
280 count
281 .checked_mul(8)
282 .ok_or("snapshot: truncated payload")?,
283 )?;
284 Ok(raw
285 .chunks_exact(8)
286 .map(|chunk| {
287 f64::from_le_bytes([
288 chunk[0], chunk[1], chunk[2], chunk[3], chunk[4], chunk[5], chunk[6], chunk[7],
289 ])
290 })
291 .collect())
292 }
293}
294
295const B64_ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
302
303fn base64_encode(bytes: &[u8]) -> String {
304 let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
305 for chunk in bytes.chunks(3) {
306 let b0 = chunk[0] as u32;
307 let b1 = chunk.get(1).copied().unwrap_or(0) as u32;
308 let b2 = chunk.get(2).copied().unwrap_or(0) as u32;
309 let triple = (b0 << 16) | (b1 << 8) | b2;
310 out.push(B64_ALPHABET[(triple >> 18) as usize & 63] as char);
311 out.push(B64_ALPHABET[(triple >> 12) as usize & 63] as char);
312 out.push(if chunk.len() > 1 {
313 B64_ALPHABET[(triple >> 6) as usize & 63] as char
314 } else {
315 '='
316 });
317 out.push(if chunk.len() > 2 {
318 B64_ALPHABET[triple as usize & 63] as char
319 } else {
320 '='
321 });
322 }
323 out
324}
325
326fn base64_value(byte: u8) -> Result<u32, String> {
327 match byte {
328 b'A'..=b'Z' => Ok((byte - b'A') as u32),
329 b'a'..=b'z' => Ok((byte - b'a') as u32 + 26),
330 b'0'..=b'9' => Ok((byte - b'0') as u32 + 52),
331 b'+' => Ok(62),
332 b'/' => Ok(63),
333 _ => Err(format!(
334 "snapshot: invalid base64 character 0x{byte:02x}"
335 )),
336 }
337}
338
339fn base64_decode(text: &str) -> Result<Vec<u8>, String> {
340 let bytes = text.as_bytes();
341 if bytes.len() % 4 != 0 {
342 return Err("snapshot: base64 length must be a multiple of 4".into());
343 }
344 let mut out = Vec::with_capacity(bytes.len() / 4 * 3);
345 for (index, quad) in bytes.chunks_exact(4).enumerate() {
346 let is_last = (index + 1) * 4 == bytes.len();
347 let padding = match (quad[2], quad[3]) {
349 (b'=', b'=') if is_last => 2,
350 (_, b'=') if is_last && quad[2] != b'=' => 1,
351 (b'=', _) => return Err("snapshot: misplaced base64 padding".into()),
352 _ => 0,
353 };
354 if quad[0] == b'=' || quad[1] == b'=' {
355 return Err("snapshot: misplaced base64 padding".into());
356 }
357 let mut triple = base64_value(quad[0])? << 18 | base64_value(quad[1])? << 12;
358 if padding < 2 {
359 triple |= base64_value(quad[2])? << 6;
360 }
361 if padding < 1 {
362 triple |= base64_value(quad[3])?;
363 }
364 out.push((triple >> 16) as u8);
365 if padding < 2 {
366 out.push((triple >> 8) as u8);
367 }
368 if padding < 1 {
369 out.push(triple as u8);
370 }
371 }
372 Ok(out)
373}
374