1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
//! Canonical serialziation to use. This is so that `paralegal-flow` and
//! `paralegal-policy` agree on the format to use.
//!
use anyhow::{Context, Ok, Result};
use cfg_if::cfg_if;
use std::{fs::File, path::Path};

use crate::ProgramDescription;

cfg_if! {
    if #[cfg(feature = "binenc")] {
        const CODEC: &str = "bincode";
    } else {
        const CODEC: &str = "json";
    }
}

impl ProgramDescription {
    /// Write `self` using the configured serialization format
    pub fn canonical_write(&self, path: impl AsRef<Path>) -> Result<()> {
        let path = path.as_ref();
        let mut out_file = File::create(path)?;
        cfg_if! {
            if #[cfg(feature = "binenc")] {
                let write = bincode::serialize_into(
                    &mut out_file,
                    self
                );
            } else {
                let write = serde_json::to_writer(
                    &mut out_file,
                    self,
                );
            }
        }
        write.with_context(|| {
            format!(
                "Writing SPDG with codec {CODEC} to {}",
                path.canonicalize()
                    .unwrap_or_else(|_| path.to_owned())
                    .display()
            )
        })?;
        Ok(())
    }

    /// Read `self` using the configured serialization format
    pub fn canonical_read(path: impl AsRef<Path>) -> Result<Self> {
        let path = path.as_ref();
        let in_file = File::open(path)?;
        cfg_if! {
            if #[cfg(feature = "binenc")] {
                let read = bincode::deserialize_from(
                    &in_file,
                );
            } else  {
                let read = serde_json::from_reader(
                    &in_file,
                );
            }
        };
        read.with_context(|| {
            format!(
                "Reading SPDG with codec {CODEC} from {}",
                path.canonicalize()
                    .unwrap_or_else(|_| path.to_owned())
                    .display()
            )
        })
    }
}