Made serialization working

This commit is contained in:
Weird Constructor 2022-08-04 03:46:56 +02:00
parent 9683213c28
commit 0c75da0912
4 changed files with 80 additions and 13 deletions

View file

@ -1116,7 +1116,7 @@ pub struct BlockFunSnapshot {
} }
impl BlockFunSnapshot { impl BlockFunSnapshot {
pub fn serialize(&self) -> String { pub fn serialize(&self) -> Value {
let mut v = json!({ let mut v = json!({
"VERSION": 1, "VERSION": 1,
}); });
@ -1132,12 +1132,10 @@ impl BlockFunSnapshot {
v["areas"] = areas; v["areas"] = areas;
v.to_string() v
} }
pub fn deserialize(s: &str) -> Result<BlockFunSnapshot, serde_json::Error> { pub fn deserialize(v: &Value) -> Result<BlockFunSnapshot, serde_json::Error> {
let v: Value = serde_json::from_str(s)?;
let mut a = vec![]; let mut a = vec![];
let areas = &v["areas"]; let areas = &v["areas"];
@ -1184,6 +1182,10 @@ impl BlockFun {
} }
} }
pub fn is_unset(&self) -> bool {
self.generation == 0
}
pub fn block_language(&self) -> Rc<RefCell<BlockLanguage>> { pub fn block_language(&self) -> Rc<RefCell<BlockLanguage>> {
self.language.clone() self.language.clone()
} }
@ -1817,12 +1819,34 @@ mod test {
let mut bf = BlockFun::new(lang.clone()); let mut bf = BlockFun::new(lang.clone());
let sn = bf.save_snapshot(); let sn = bf.save_snapshot();
let serialized = sn.serialize(); let serialized = sn.serialize().to_string();
assert_eq!(serialized, "{\"VERSION\":1,\"areas\":[{\"auto_shrink\":false,\"blocks\":[],\"header\":\"\",\"size\":[16,16]}],\"current_block_id_counter\":0}"); assert_eq!(serialized, "{\"VERSION\":1,\"areas\":[{\"auto_shrink\":false,\"blocks\":[],\"header\":\"\",\"size\":[16,16]}],\"current_block_id_counter\":0}");
let sn = BlockFunSnapshot::deserialize(&serialized).expect("No deserialization error"); let v: Value = serde_json::from_str(&serialized).unwrap();
let sn = BlockFunSnapshot::deserialize(&v).expect("No deserialization error");
let mut bf2 = BlockFun::new(lang); let mut bf2 = BlockFun::new(lang);
let bf2 = bf2.load_snapshot(&sn); let bf2 = bf2.load_snapshot(&sn);
} }
}
#[test]
fn check_blockfun_serialize_1() {
let dsp_lib = synfx_dsp_jit::get_standard_library();
let lang = crate::blocklang_def::setup_hxdsp_block_language(dsp_lib);
let mut bf = BlockFun::new(lang.clone());
bf.instanciate_at(0, 0, 0, "+", None);
let sn = bf.save_snapshot();
let serialized = sn.serialize().to_string();
assert_eq!(serialized,
"{\"VERSION\":1,\"areas\":[{\"auto_shrink\":false,\"blocks\":[{\"block\":{\"color\":4,\"contains\":[null,null],\"expanded\":true,\"id\":1,\"inputs\":[\"\",\"\"],\"lbl\":\"+\",\"outputs\":[\"\"],\"rows\":2,\"typ\":\"+\"},\"x\":0,\"y\":0}],\"header\":\"\",\"size\":[16,16]}],\"current_block_id_counter\":1}");
let v: Value = serde_json::from_str(&serialized).unwrap();
let sn = BlockFunSnapshot::deserialize(&v).expect("No deserialization error");
let mut bf2 = BlockFun::new(lang);
bf2.load_snapshot(&sn);
let bv = bf2.block_at(0, 0, 0).unwrap();
assert!(bv.has_input(0));
}
}

View file

@ -10,7 +10,7 @@ pub use crate::nodes::MinMaxMonitorSamples;
use crate::nodes::{NodeConfigurator, NodeGraphOrdering, NodeProg, MAX_ALLOCATED_NODES}; use crate::nodes::{NodeConfigurator, NodeGraphOrdering, NodeProg, MAX_ALLOCATED_NODES};
pub use crate::CellDir; pub use crate::CellDir;
use crate::ScopeHandle; use crate::ScopeHandle;
use crate::blocklang::BlockFun; use crate::blocklang::{BlockFun, BlockFunSnapshot};
use crate::block_compiler::BlkJITCompileError; use crate::block_compiler::BlkJITCompileError;
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
@ -607,7 +607,7 @@ impl Matrix {
/// Retrieve a handle to the block function `id`. In case you modify the block function, /// Retrieve a handle to the block function `id`. In case you modify the block function,
/// make sure to call [check_block_function]. /// make sure to call [check_block_function].
pub fn get_block_function(&mut self, id: usize) -> Option<Arc<Mutex<BlockFun>>> { pub fn get_block_function(&self, id: usize) -> Option<Arc<Mutex<BlockFun>>> {
self.config.get_block_function(id) self.config.get_block_function(id)
} }
@ -845,9 +845,21 @@ impl Matrix {
tracker_id += 1; tracker_id += 1;
} }
let mut block_funs: Vec<Option<BlockFunSnapshot>> = vec![];
let mut bf_id = 0;
while let Some(bf) = self.get_block_function(bf_id) {
block_funs.push(if bf.lock().unwrap().is_unset() {
None
} else {
Some(bf.lock().unwrap().save_snapshot())
});
bf_id += 1;
}
let properties = self.properties.iter().map(|(k, v)| (k.to_string(), v.clone())).collect(); let properties = self.properties.iter().map(|(k, v)| (k.to_string(), v.clone())).collect();
MatrixRepr { cells, params, atoms, patterns, properties, version: 2 } MatrixRepr { cells, params, atoms, patterns, block_funs, properties, version: 2 }
} }
/// Loads the matrix from a previously my [Matrix::to_repr] /// Loads the matrix from a previously my [Matrix::to_repr]
@ -879,6 +891,14 @@ impl Matrix {
} }
} }
for (bf_id, block_fun) in repr.block_funs.iter().enumerate() {
if let Some(block_fun) = block_fun {
if let Some(bf) = self.get_block_function(bf_id) {
bf.lock().unwrap().load_snapshot(block_fun);
}
}
}
let ret = self.sync(); let ret = self.sync();
if let Some(obs) = &self.observer { if let Some(obs) = &self.observer {

View file

@ -4,6 +4,7 @@
use crate::dsp::{NodeId, ParamId, SAtom}; use crate::dsp::{NodeId, ParamId, SAtom};
use serde_json::{json, Value}; use serde_json::{json, Value};
use crate::blocklang::BlockFunSnapshot;
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
pub struct CellRepr { pub struct CellRepr {
@ -187,6 +188,7 @@ pub struct MatrixRepr {
pub atoms: Vec<(ParamId, SAtom)>, pub atoms: Vec<(ParamId, SAtom)>,
pub patterns: Vec<Option<PatternRepr>>, pub patterns: Vec<Option<PatternRepr>>,
pub properties: Vec<(String, SAtom)>, pub properties: Vec<(String, SAtom)>,
pub block_funs: Vec<Option<BlockFunSnapshot>>,
pub version: i64, pub version: i64,
} }
@ -289,8 +291,9 @@ impl MatrixRepr {
let atoms = vec![]; let atoms = vec![];
let patterns = vec![]; let patterns = vec![];
let properties = vec![]; let properties = vec![];
let block_funs = vec![];
Self { cells, params, atoms, patterns, properties, version: 2 } Self { cells, params, atoms, patterns, block_funs, properties, version: 2 }
} }
pub fn write_to_file(&mut self, filepath: &str) -> std::io::Result<()> { pub fn write_to_file(&mut self, filepath: &str) -> std::io::Result<()> {
@ -398,6 +401,17 @@ impl MatrixRepr {
} }
} }
let block_funs = &v["block_funs"];
if let Value::Array(block_funs) = block_funs {
for p in block_funs.iter() {
m.block_funs.push(if p.is_object() {
Some(BlockFunSnapshot::deserialize(&p)?)
} else {
None
});
}
}
Ok(m) Ok(m)
} }
@ -468,6 +482,15 @@ impl MatrixRepr {
v["patterns"] = patterns; v["patterns"] = patterns;
let mut block_funs = json!([]);
if let Value::Array(block_funs) = &mut block_funs {
for p in self.block_funs.iter() {
block_funs.push(if let Some(p) = p { p.serialize() } else { Value::Null });
}
}
v["block_funs"] = block_funs;
v.to_string() v.to_string()
} }
} }

View file

@ -719,7 +719,7 @@ impl NodeConfigurator {
/// Retrieve a handle to the block function `id`. In case you modify the block function, /// Retrieve a handle to the block function `id`. In case you modify the block function,
/// make sure to call [check_block_function]. /// make sure to call [check_block_function].
pub fn get_block_function(&mut self, id: usize) -> Option<Arc<Mutex<BlockFun>>> { pub fn get_block_function(&self, id: usize) -> Option<Arc<Mutex<BlockFun>>> {
self.block_functions.get(id).map(|pair| pair.1.clone()) self.block_functions.get(id).map(|pair| pair.1.clone())
} }