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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
//! # Serialization interface
//!
//! Interface to serialize and to deserialize `dos-actors` objects.

use std::{
    env::{self, VarError},
    fmt::Debug,
    fs::File,
    io::{Read, Write},
    path::Path,
};

use serde::{Deserialize, Serialize};

#[derive(Debug, thiserror::Error)]
pub enum FilingError {
    #[error("filing error")]
    IO(#[from] std::io::Error),
    #[error("decoder error")]
    Decoder(#[from] bincode::error::DecodeError),
    #[error("encoder error")]
    Encoder(#[from] bincode::error::EncodeError),
    #[error("builder error: {0}")]
    Builder(String),
    #[error("DATA_REPO not set")]
    DataRepo(#[from] VarError),
}

pub type Result<T> = std::result::Result<T, FilingError>;

/// Encoding and decoding
pub trait Codec
where
    Self: Sized + serde::ser::Serialize + for<'de> serde::de::Deserialize<'de>,
{
    /// Decodes object from [std::io::Read]
    #[inline]
    fn decode<R>(reader: &mut R) -> Result<Self>
    where
        R: Read,
    {
        Ok(bincode::serde::decode_from_std_read(
            reader,
            bincode::config::standard(),
        )?)
    }

    /// Encodes object to [std::io::Write]
    #[inline]
    fn encode<W>(&self, writer: &mut W) -> Result<()>
    where
        W: Write,
    {
        bincode::serde::encode_into_std_write(self, writer, bincode::config::standard())?;
        Ok(())
    }
}

impl<T> Filing for T where
    T: Sized + Codec + serde::ser::Serialize + for<'de> serde::de::Deserialize<'de>
{
}

/// Encoding and decoding to/from [File]
pub trait Filing: Codec
where
    Self: Sized + serde::ser::Serialize + for<'de> serde::de::Deserialize<'de>,
{
    /// Decodes object from given path
    fn from_path<P>(path: P) -> Result<Self>
    where
        P: AsRef<Path> + Debug,
    {
        log::info!("decoding from {path:?}");
        let file = File::open(path)?;
        let mut buffer = std::io::BufReader::new(file);
        Self::decode(&mut buffer)
    }

    /// Decodes object from given file
    /// The file is read from the directory specified by the `DATA_REPO` environment variable.
    fn from_data_repo(file_name: impl AsRef<Path>) -> Result<Self> {
        let data_repo = env::var("DATA_REPO")?;
        let path = Path::new(&data_repo).join(file_name);
        Self::from_path(path)
    }

    /// Encodes object from given path
    fn to_path<P>(&self, path: P) -> Result<()>
    where
        P: AsRef<Path> + Debug,
    {
        log::info!("encoding to {path:?}");
        let file = File::create(path)?;
        let mut buffer = std::io::BufWriter::new(file);
        self.encode(&mut buffer)?;
        Ok(())
    }

    /// Encodes object from given file.
    /// The file is written to the directory specified by the `DATA_REPO` environment variable.
    fn to_data_repo(&self, file_name: impl AsRef<Path>) -> Result<()> {
        let data_repo = env::var("DATA_REPO")?;
        let path = Path::new(&data_repo).join(file_name);
        Self::to_path(self, path)
    }

    /// Decodes object from given path or creates a new object from the builder and encodes the object to the given path
    fn from_path_or_else<P, F, B>(path: P, builder: F) -> Result<Self>
    where
        P: AsRef<Path> + Debug,
        F: FnOnce() -> B,
        Self: TryFrom<B>,
        <Self as TryFrom<B>>::Error: std::fmt::Debug,
    {
        Self::from_path(&path).or_else(|_| {
            let this =
                Self::try_from(builder()).map_err(|e| FilingError::Builder(format!("{e:?}")))?;
            this.to_path(path)?;
            Ok(this)
        })
    }

    /// Decodes object from given file or creates a new object from the builder and encodes the object to the given file.
    /// The file is read from the directory specified by the `DATA_REPO` environment variable.
    fn from_data_repo_or_else<P, F, B>(file_name: P, builder: F) -> Result<Self>
    where
        P: AsRef<Path>,
        F: FnOnce() -> B,
        Self: TryFrom<B>,
        <Self as TryFrom<B>>::Error: std::fmt::Debug,
    {
        let data_repo = env::var("DATA_REPO")?;
        let path = Path::new(&data_repo).join(file_name);
        Self::from_path_or_else(path, builder)
    }

    /// Decodes object from given path or creates a new object from [Default] and encodes the object to the given path
    fn from_path_or_default<P, F, B>(path: P) -> Result<Self>
    where
        P: AsRef<Path> + Debug,
        B: Default,
        F: FnOnce() -> B,
        Self: TryFrom<B>,
        <Self as TryFrom<B>>::Error: std::fmt::Debug,
    {
        Self::from_path_or_else(path, Default::default)
    }

    /// Decodes object from given file or creates a new object from [Default] and encodes the object to the given file.
    /// The file is read from the directory specified by the `DATA_REPO` environment variable.
    fn from_data_repo_or_default<P, F, B>(file_name: P) -> Result<Self>
    where
        P: AsRef<Path>,
        B: Default,
        F: FnOnce() -> B,
        Self: TryFrom<B>,
        <Self as TryFrom<B>>::Error: std::fmt::Debug,
    {
        Self::from_data_repo_or_else(file_name, Default::default)
    }
    /// Loads an object and builder pair from a given path and returns the object
    /// only if the builder match the current one, or creates a new object from the
    /// current builder then encodes the new object and builder pair to the given path
    /// and finally returns the new object.
    fn from_path_or<P, B>(path: P, current_builder: B) -> Result<Self>
    where
        P: AsRef<Path> + Debug,
        Self: TryFrom<B> + serde::ser::Serialize + for<'de> serde::de::Deserialize<'de>,
        B: Clone + PartialEq + serde::ser::Serialize + for<'de> serde::de::Deserialize<'de>,
        <Self as TryFrom<B>>::Error: std::fmt::Debug,
    {
        match <ObjectAndBuilder<Self, B> as Filing>::from_path(&path) {
            Ok(ObjectAndBuilder { object, builder }) if builder == current_builder => Ok(object),
            _ => {
                let object = Self::try_from(current_builder.clone())
                    .map_err(|e| FilingError::Builder(format!("{e:?}")))?;
                let this = ObjectAndBuilder {
                    object,
                    builder: current_builder,
                };
                this.to_path(path)?;
                let ObjectAndBuilder { object, .. } = this;
                Ok(object)
            }
        }
    }
    /// Loads an object and builder pair from a given file and returns the object
    /// only if the builder match the current one, or creates a new object from the
    /// current builder then encodes the new object and builder pair to the given file
    /// and finally returns the new object.
    /// The file is read from the directory specified by the `DATA_REPO` environment variable.
    fn from_data_repo_or<P, B>(file_name: P, current_builder: B) -> Result<Self>
    where
        P: AsRef<Path>,
        Self: TryFrom<B> + serde::ser::Serialize + for<'de> serde::de::Deserialize<'de>,
        B: Clone + PartialEq + serde::ser::Serialize + for<'de> serde::de::Deserialize<'de>,
        <Self as TryFrom<B>>::Error: std::fmt::Debug,
    {
        let data_repo = env::var("DATA_REPO")?;
        let path = Path::new(&data_repo).join(file_name);
        Self::from_path_or(path, current_builder)
    }
}

/// Object and builder pair
#[derive(Serialize, Deserialize)]
struct ObjectAndBuilder<T, B>
where
    T: TryFrom<B>,
{
    object: T,
    builder: B,
}

impl<T, B> Codec for ObjectAndBuilder<T, B>
where
    T: TryFrom<B> + serde::ser::Serialize + for<'de> serde::de::Deserialize<'de>,
    B: serde::ser::Serialize + for<'de> serde::de::Deserialize<'de>,
{
}