// SPDX-License-Identifier: MIT //! Save states (the `serde` feature; not in ay8910-python, whose state is plain attributes a //! board copies): a chip serialised part way through a stream and restored carries on exactly //! as the one that was never stopped, for every part and for a part that is none of them. //! Rung 4 does the same against ay8910-python's own traces, at every checkpoint of rungs 2 //! and 3. #![cfg(feature = "serde")] use std::borrow::Cow; use ay8910_rust::{PSGVariant, PSG, VARIANTS, YM2149}; /// Python's `random.Random` is not needed here: a small fixed generator (xorshift64*). struct Rng(u64); impl Rng { fn below(&mut self, n: u64) -> u64 { self.0 ^= self.0 >> 12; self.0 ^= self.0 << 25; self.0 ^= self.0 >> 27; (self.0.wrapping_mul(0x2545_F491_4F6C_DD1D) >> 33) % n } } /// Writes to every register with sound: short periods, envelope volumes, the shape rewritten. fn stream(seed: u64) -> Vec<(u64, u8, u8)> { let mut rng = Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15).wrapping_add(1)); (0..3000) .map(|_| { let register = rng.below(16) as u8; let value = match register { 1 | 3 | 5 | 12 => rng.below(2) as u8, 0 | 2 | 4 | 6 | 11 => rng.below(12) as u8, 7 => (rng.below(256) & rng.below(256)) as u8, _ => rng.below(256) as u8, }; (rng.below(300), register, value) }) .collect() } #[test] fn a_restored_chip_continues_identically() { let mut odd: PSGVariant = YM2149; odd.name = Cow::Owned("neither".into()); odd.ports = Cow::Owned("B".into()); odd.dac = Cow::Owned((0..32).map(|c| c as f64 / 31.0).collect()); odd.clock_divider = 2; let mut parts: Vec = VARIANTS.to_vec(); parts.push(odd); for part in parts { for seed in 0..4 { let writes = stream(seed); let (first, second) = writes.split_at(writes.len() / 2 + seed as usize); let mut chip = PSG::new(part.clone()); chip.port_a_out = true; chip.port_b_in = Some(0x5A); for &(clocks, register, value) in first { chip.run(clocks); chip.write_register(register, value); } chip.run(3 + seed); // inside the divider's eight let saved = bincode::serialize(&chip).unwrap(); let mut restored: PSG = bincode::deserialize(&saved).unwrap(); assert_eq!(restored, chip); let json = serde_json::to_string(&chip).unwrap(); assert_eq!(serde_json::from_str::(&json).unwrap(), chip); for each in [&mut chip, &mut restored] { for &(clocks, register, value) in second { each.run(clocks); each.write_register(register, value); } each.run(5000); } assert!(chip.outputs.iter().any(|l| *l != [0, 0, 0])); assert_eq!(restored, chip); assert_eq!(restored.take_samples(), chip.take_samples()); } } }