digital_ink_library/serialization/
json_serializer.rs

1use std::fs;
2
3use crate::sketch::Sketch;
4use crate::stroke::Stroke;
5
6pub fn dump_stroke(stroke: &Stroke, file_path: &String) {
7    let json_string = dumps_stroke(stroke);
8    fs::write(file_path, json_string).expect("unable to write stroke to file");
9}
10
11pub fn dump_sketch(sketch: &Sketch, file_path: &String) {
12    let json_string = dumps_sketch(sketch);
13    fs::write(file_path, json_string).expect("unable to write sketch to file");
14}
15
16pub fn dumps_stroke(stroke: &Stroke) -> String {
17    serde_json::to_string_pretty(stroke).unwrap()
18}
19
20pub fn dumps_sketch(sketch: &Sketch) -> String {
21    serde_json::to_string_pretty(sketch).unwrap()
22}
23
24pub fn load_stroke(file_path: &String) -> Result<Stroke, String> {
25    let contents = fs::read_to_string(file_path).expect("unable to read stroke from file");
26    loads_stroke(contents)
27}
28
29pub fn load_sketch(file_path: &String) -> Result<Sketch, String> {
30    let contents = fs::read_to_string(file_path).expect("unable to read stroke from file");
31    match loads_sketch(contents) {
32        Err(e) => return Err(e.to_string()),
33        Ok(s) => return Ok(s),
34    };
35}
36
37pub fn load_sketches(file_path: &String) -> Result<Vec<Sketch>, String> {
38    let contents = fs::read_to_string(file_path).expect("unable to read stroke from file");
39    match loads_sketches(contents) {
40        Err(e) => return Err(e.to_string()),
41        Ok(s) => return Ok(s),
42    };
43}
44
45pub fn loads_stroke(serialized_string: String) -> Result<Stroke, String> {
46    match serde_json::from_str(serialized_string.as_str()) {
47        Err(e) => return Err(e.to_string()),
48        Ok(s) => return Ok(s),
49    };
50}
51
52pub fn loads_strokes(serialized_string: String) -> Result<Vec<Stroke>, String> {
53    match serde_json::from_str(serialized_string.as_str()) {
54        Err(e) => return Err(e.to_string()),
55        Ok(s) => return Ok(s),
56    };
57}
58
59pub fn loads_sketch(serialized_string: String) -> Result<Sketch, String> {
60    match serde_json::from_str(serialized_string.as_str()) {
61        Err(e) => return Err(e.to_string()),
62        Ok(s) => return Ok(s),
63    };
64}
65
66pub fn loads_sketches(serialized_string: String) -> Result<Vec<Sketch>, String> {
67    match serde_json::from_str(serialized_string.as_str()) {
68        Err(e) => return Err(e.to_string()),
69        Ok(s) => return Ok(s),
70    };
71}