use std::collections::BTreeMap;
use std::hash::Hasher;
use std::path::Path;
use serde::{Deserialize, Serialize};
use crate::DaeError;
pub const MAGIC: &[u8; 4] = b"GSCK";
pub const FORMAT_VERSION: u32 = 1;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum SignalSnapshot {
Scalar(f64),
Vector(Vec<f64>),
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum BlockSnapshot {
Stateless,
Dynamic {
x: Vec<f64>,
},
DiscreteDynamic {
x: Vec<f64>,
time_since_sample: f64,
last_output: Vec<f64>,
},
DiscretePid {
int_state: f64,
int_prev_e: f64,
filt_state: f64,
filt_prev_v: f64,
time_since_sample: f64,
last_output: f64,
},
Phase(f64),
Pmsm {
x: Vec<f64>,
},
Bit(bool),
FlipFlop {
q: bool,
prev_clk: f64,
},
Counter {
count: i64,
prev_clk: f64,
},
SampledFunction {
time_since_sample: f64,
last_output: Vec<f64>,
},
PyBlock {
time_since_sample: f64,
next_hit_dt: f64,
last_output: Vec<f64>,
xc: Vec<f64>,
state: Vec<u8>,
},
CScript {
time_since_sample: f64,
next_hit_dt: f64,
last_output: Vec<f64>,
xc: Vec<f64>,
state: Vec<u8>,
},
OctBlock {
time_since_sample: f64,
next_hit_dt: f64,
last_output: Vec<f64>,
xc: Vec<f64>,
state: Vec<u8>,
},
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PointSnapshot {
pub x: Vec<f64>,
pub diode_names: Vec<String>,
pub diode_z: Vec<(f64, f64)>,
pub diode_raw_ioff: Vec<f64>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Checkpoint {
pub deck_hash: u64,
pub unknowns: Vec<String>,
pub t: f64,
pub accepted_steps: usize,
pub step_index: usize,
pub dt_next: Option<f64>,
pub ringing_cooldown: u32,
pub x_prev: Vec<f64>,
pub x_prev_prev: Option<Vec<f64>>,
pub point_prev: PointSnapshot,
pub prev_diode_raw_ioff: BTreeMap<String, f64>,
pub prev_segments: Option<Vec<u8>>,
pub prev_gate_states: Option<BTreeMap<String, bool>>,
pub prev_outputs: BTreeMap<String, SignalSnapshot>,
pub blocks: Vec<(String, BlockSnapshot)>,
}
impl Checkpoint {
pub fn to_bytes(&self) -> Result<Vec<u8>, DaeError> {
let mut out = MAGIC.to_vec();
out.extend_from_slice(&FORMAT_VERSION.to_le_bytes());
let payload = postcard::to_stdvec(self)
.map_err(|e| DaeError::CheckpointFormat(format!("encoding failed: {e}")))?;
out.extend_from_slice(&payload);
Ok(out)
}
pub fn from_bytes(bytes: &[u8]) -> Result<Self, DaeError> {
if bytes.len() < 8 || &bytes[..4] != MAGIC {
return Err(DaeError::CheckpointFormat(
"not a general-simulator checkpoint (missing GSCK header)".to_string(),
));
}
let version = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);
if version != FORMAT_VERSION {
return Err(DaeError::CheckpointFormat(format!(
"checkpoint format version {version} is not the {FORMAT_VERSION} this build \
reads"
)));
}
postcard::from_bytes(&bytes[8..])
.map_err(|e| DaeError::CheckpointFormat(format!("decoding failed: {e}")))
}
pub fn write_to(&self, path: &Path) -> Result<(), DaeError> {
let bytes = self.to_bytes()?;
let tmp = path.with_extension("tmp");
std::fs::write(&tmp, bytes).map_err(|e| DaeError::CheckpointIo {
path: path.to_path_buf(),
message: e.to_string(),
})?;
std::fs::rename(&tmp, path).map_err(|e| DaeError::CheckpointIo {
path: path.to_path_buf(),
message: e.to_string(),
})
}
pub fn read_from(path: &Path) -> Result<Self, DaeError> {
let bytes = std::fs::read(path).map_err(|e| DaeError::CheckpointIo {
path: path.to_path_buf(),
message: e.to_string(),
})?;
Self::from_bytes(&bytes)
}
}
pub fn deck_hash(parts: &[&dyn std::fmt::Debug]) -> u64 {
struct Fnv(u64);
impl Hasher for Fnv {
fn finish(&self) -> u64 {
self.0
}
fn write(&mut self, bytes: &[u8]) {
for b in bytes {
self.0 ^= u64::from(*b);
self.0 = self.0.wrapping_mul(0x0000_0100_0000_01b3);
}
}
}
let mut h = Fnv(0xcbf2_9ce4_8422_2325);
for part in parts {
h.write(format!("{part:?}").as_bytes());
h.write(&[0xff]);
}
h.finish()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bytes_round_trip_bit_exactly() {
let ckpt = Checkpoint {
deck_hash: 42,
unknowns: vec!["V(a)".into()],
t: 0.1 + 0.2,
accepted_steps: 3,
step_index: 3,
dt_next: Some(f64::MIN_POSITIVE),
ringing_cooldown: 1,
x_prev: vec![1.0 / 3.0, -0.0, f64::MAX],
x_prev_prev: None,
point_prev: PointSnapshot {
x: vec![1e-300],
diode_names: vec![],
diode_z: vec![],
diode_raw_ioff: vec![],
},
prev_diode_raw_ioff: BTreeMap::new(),
prev_segments: Some(vec![0, 1, 2]),
prev_gate_states: Some([("S1".to_string(), true)].into_iter().collect()),
prev_outputs: [("G".to_string(), SignalSnapshot::Scalar(0.7))]
.into_iter()
.collect(),
blocks: vec![("G".into(), BlockSnapshot::Dynamic { x: vec![2.5] })],
};
let bytes = ckpt.to_bytes().unwrap();
assert_eq!(&bytes[..4], MAGIC);
let back = Checkpoint::from_bytes(&bytes).unwrap();
assert_eq!(back, ckpt);
assert!(back.x_prev[1].is_sign_negative());
}
#[test]
fn a_foreign_or_future_file_is_refused_up_front() {
assert!(matches!(
Checkpoint::from_bytes(b"hello world"),
Err(DaeError::CheckpointFormat(_))
));
let mut bytes = MAGIC.to_vec();
bytes.extend_from_slice(&(FORMAT_VERSION + 1).to_le_bytes());
assert!(matches!(
Checkpoint::from_bytes(&bytes),
Err(DaeError::CheckpointFormat(m)) if m.contains("version")
));
}
#[test]
fn deck_hash_is_order_sensitive_and_stable() {
let a = deck_hash(&[&"R1 a b 1", &"C1 b 0 1u"]);
let b = deck_hash(&[&"C1 b 0 1u", &"R1 a b 1"]);
assert_ne!(a, b);
assert_eq!(a, deck_hash(&[&"R1 a b 1", &"C1 b 0 1u"]));
assert_eq!(deck_hash(&[]), 0xcbf2_9ce4_8422_2325);
}
}