// SPDX-License-Identifier: MIT //! A plain byte form for the snapshot's parts (the save state's body): little-endian //! integers, `f64` by its bits (exact), `bool` as 0 or 1. No dependency, no //! self-description: the wrapper's header names the format's version, and a body of //! the wrong length or with a byte out of range is refused. /// Appends values in order. #[derive(Default)] pub struct Writer { pub out: Vec, } impl Writer { pub fn u8(&mut self, v: u8) { self.out.push(v); } pub fn bool(&mut self, v: bool) { self.out.push(v as u8); } pub fn u16(&mut self, v: u16) { self.out.extend_from_slice(&v.to_le_bytes()); } pub fn u32(&mut self, v: u32) { self.out.extend_from_slice(&v.to_le_bytes()); } pub fn u64(&mut self, v: u64) { self.out.extend_from_slice(&v.to_le_bytes()); } pub fn f64(&mut self, v: f64) { self.u64(v.to_bits()); } pub fn bytes(&mut self, v: &[u8]) { self.out.extend_from_slice(v); } } /// Takes values back in the same order. pub struct Reader<'a> { data: &'a [u8], at: usize, } impl<'a> Reader<'a> { pub fn new(data: &'a [u8]) -> Self { Reader { data, at: 0 } } pub fn take(&mut self, n: usize) -> Result<&'a [u8], String> { let end = self.at.checked_add(n).filter(|&e| e <= self.data.len()); let end = end.ok_or_else(|| "a save state cut short".to_string())?; let out = &self.data[self.at..end]; self.at = end; Ok(out) } pub fn u8(&mut self) -> Result { Ok(self.take(1)?[0]) } pub fn bool(&mut self) -> Result { match self.u8()? { 0 => Ok(false), 1 => Ok(true), other => Err(format!("a save state with {other} for a yes-or-no")), } } pub fn u16(&mut self) -> Result { Ok(u16::from_le_bytes(self.take(2)?.try_into().unwrap())) } pub fn u32(&mut self) -> Result { Ok(u32::from_le_bytes(self.take(4)?.try_into().unwrap())) } pub fn u64(&mut self) -> Result { Ok(u64::from_le_bytes(self.take(8)?.try_into().unwrap())) } pub fn f64(&mut self) -> Result { Ok(f64::from_bits(self.u64()?)) } pub fn array(&mut self) -> Result<[u8; N], String> { Ok(self.take(N)?.try_into().unwrap()) } /// Everything was read. pub fn finish(&self) -> Result<(), String> { if self.at == self.data.len() { Ok(()) } else { Err("a save state with bytes left over".to_string()) } } }