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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
use super::*;
use include_dir::{include_dir, Dir};
pub trait Init {
/// Specialized code to execute upon initialization. For any struct with fields
/// that implement `Init`, this should propagate down the hierarchy.
fn init(&mut self) -> Result<(), Error> {
Ok(())
}
}
pub trait SerdeAPI: Serialize + for<'a> Deserialize<'a> + Init {
const ACCEPTED_BYTE_FORMATS: &'static [&'static str] = &[
#[cfg(feature = "yaml")]
"yaml",
#[cfg(feature = "json")]
"json",
#[cfg(feature = "msgpack")]
"msgpack",
#[cfg(feature = "toml")]
"toml",
];
const ACCEPTED_STR_FORMATS: &'static [&'static str] = &[
#[cfg(feature = "yaml")]
"yaml",
#[cfg(feature = "json")]
"json",
#[cfg(feature = "toml")]
"toml",
];
#[cfg(feature = "resources")]
const RESOURCES_SUBDIR: &'static str = "";
#[cfg(feature = "resources")]
const RESOURCES_DIR: &'static Dir<'_> = &include_dir!("$CARGO_MANIFEST_DIR/resources");
/// Read (deserialize) an object from a resource file packaged with the `altrios-core` crate
///
/// # Arguments:
///
/// * `filepath` - Filepath, relative to the top of the `resources` folder (excluding any relevant prefix), from which to read the object
#[cfg(feature = "resources")]
fn from_resource<P: AsRef<Path>>(filepath: P, skip_init: bool) -> Result<Self, Error> {
let filepath = Path::new(Self::RESOURCES_SUBDIR).join(filepath);
let extension = filepath
.extension()
.and_then(OsStr::to_str)
.ok_or_else(|| {
Error::SerdeError(format!("File extension could not be parsed: {filepath:?}"))
})?;
let file = Self::RESOURCES_DIR.get_file(&filepath).ok_or_else(|| {
Error::SerdeError(format!("File not found in resources: {filepath:?}"))
})?;
Self::from_reader(&mut file.contents(), extension, skip_init)
}
/// List the available resources in the resources directory
///
/// RETURNS: a vector of strings for resources that can be loaded
fn list_resources() -> Result<Vec<PathBuf>, Error> {
// Recursive function to walk the directory
fn collect_paths(dir: &Dir, paths: &mut Vec<PathBuf>) {
for entry in dir.entries() {
match entry {
include_dir::DirEntry::Dir(subdir) => {
// Recursively process subdirectory
collect_paths(subdir, paths);
}
include_dir::DirEntry::File(file) => {
// Add file path
paths.push(file.path().to_path_buf());
}
}
}
}
let mut paths = Vec::new();
if let Some(resources_subdir) = Self::RESOURCES_DIR.get_dir(Self::RESOURCES_SUBDIR) {
collect_paths(resources_subdir, &mut paths);
for p in paths.iter_mut() {
*p = p
.strip_prefix(Self::RESOURCES_SUBDIR)
.map_err(|err| Error::SerdeError(format!("{err}")))?
.to_path_buf();
}
paths.sort();
}
Ok(paths)
}
/// Write (serialize) an object to a file.
/// Supported file extensions are listed in [`ACCEPTED_BYTE_FORMATS`](`SerdeAPI::ACCEPTED_BYTE_FORMATS`).
/// Creates a new file if it does not already exist, otherwise truncates the existing file.
///
/// # Arguments
///
/// * `filepath` - The filepath at which to write the object
///
fn to_file<P: AsRef<Path>>(&self, filepath: P) -> anyhow::Result<()> {
let filepath = filepath.as_ref();
let extension = filepath
.extension()
.and_then(OsStr::to_str)
.with_context(|| format!("File extension could not be parsed: {filepath:?}"))?;
self.to_writer(File::create(filepath)?, extension)
}
/// Read (deserialize) an object from a file.
/// Supported file extensions are listed in [`ACCEPTED_BYTE_FORMATS`](`SerdeAPI::ACCEPTED_BYTE_FORMATS`).
///
/// # Arguments:
///
/// * `filepath`: The filepath from which to read the object
///
fn from_file<P: AsRef<Path>>(filepath: P, skip_init: bool) -> Result<Self, Error> {
let filepath = filepath.as_ref();
let extension = filepath
.extension()
.and_then(OsStr::to_str)
.ok_or_else(|| {
Error::SerdeError(format!("File extension could not be parsed: {filepath:?}"))
})?;
let mut file = File::open(filepath).map_err(|err| {
Error::SerdeError(format!(
"{err}\n{}",
if !filepath.exists() {
format!("File not found: {filepath:?}")
} else {
format!("Could not open file: {filepath:?}")
}
))
})?;
Self::from_reader(&mut file, extension, skip_init)
}
/// Write (serialize) an object into anything that implements [`std::io::Write`]
///
/// # Arguments:
///
/// * `wtr` - The writer into which to write object data
/// * `format` - The target format, any of those listed in [`ACCEPTED_BYTE_FORMATS`](`SerdeAPI::ACCEPTED_BYTE_FORMATS`)
///
fn to_writer<W: std::io::Write>(&self, mut wtr: W, format: &str) -> anyhow::Result<()> {
match format.trim_start_matches('.').to_lowercase().as_str() {
#[cfg(feature = "yaml")]
"yaml" | "yml" => serde_yaml::to_writer(wtr, self)?,
#[cfg(feature = "json")]
"json" => serde_json::to_writer(wtr, self)?,
#[cfg(feature = "msgpack")]
"msgpack" => rmp_serde::encode::write(&mut wtr, self)
.map_err(|err| Error::SerdeError(format!("{err}")))?,
#[cfg(feature = "toml")]
"toml" => {
let toml_string = self.to_toml()?;
wtr.write_all(toml_string.as_bytes())?;
}
_ => bail!(
"Unsupported format {format:?}, must be one of {:?}",
Self::ACCEPTED_BYTE_FORMATS
),
}
Ok(())
}
/// Write (serialize) an object into a string
///
/// # Arguments:
///
/// * `format` - The target format, any of those listed in [`ACCEPTED_STR_FORMATS`](`SerdeAPI::ACCEPTED_STR_FORMATS`)
///
fn to_str(&self, format: &str) -> anyhow::Result<String> {
match format.trim_start_matches('.').to_lowercase().as_str() {
#[cfg(feature = "yaml")]
"yaml" | "yml" => self.to_yaml(),
#[cfg(feature = "json")]
"json" => self.to_json(),
#[cfg(feature = "toml")]
"toml" => self.to_toml(),
_ => bail!(
"Unsupported format {format:?}, must be one of {:?}",
Self::ACCEPTED_STR_FORMATS
),
}
}
/// Read (deserialize) an object from a string
///
/// # Arguments:
///
/// * `contents` - The string containing the object data
/// * `format` - The source format, any of those listed in [`ACCEPTED_STR_FORMATS`](`SerdeAPI::ACCEPTED_STR_FORMATS`)
///
fn from_str<S: AsRef<str>>(contents: S, format: &str, skip_init: bool) -> anyhow::Result<Self> {
Ok(
match format.trim_start_matches('.').to_lowercase().as_str() {
#[cfg(feature = "yaml")]
"yaml" | "yml" => Self::from_yaml(contents, skip_init)?,
#[cfg(feature = "json")]
"json" => Self::from_json(contents, skip_init)?,
#[cfg(feature = "toml")]
"toml" => Self::from_toml(contents, skip_init)?,
_ => bail!(
"Unsupported format {format:?}, must be one of {:?}",
Self::ACCEPTED_STR_FORMATS
),
},
)
}
/// Deserialize an object from anything that implements [`std::io::Read`]
///
/// # Arguments:
///
/// * `rdr` - The reader from which to read object data
/// * `format` - The source format, any of those listed in [`ACCEPTED_BYTE_FORMATS`](`SerdeAPI::ACCEPTED_BYTE_FORMATS`)
///
fn from_reader<R: std::io::Read>(
rdr: &mut R,
format: &str,
skip_init: bool,
) -> Result<Self, Error> {
let mut deserialized: Self = match format.trim_start_matches('.').to_lowercase().as_str() {
"yaml" | "yml" => serde_yaml::from_reader(rdr)
.map_err(|err| Error::SerdeError(format!("{err} while reading `yaml`")))?,
"json" => serde_json::from_reader(rdr)
.map_err(|err| Error::SerdeError(format!("{err} while reading `json`")))?,
#[cfg(feature = "msgpack")]
"msgpack" => rmp_serde::decode::from_read(rdr)
.map_err(|err| Error::SerdeError(format!("{err} while reading `msgpack`")))?,
_ => {
return Err(Error::SerdeError(format!(
"Unsupported format {format:?}, must be one of {:?}",
Self::ACCEPTED_BYTE_FORMATS
)))
}
};
if !skip_init {
deserialized.init()?;
}
Ok(deserialized)
}
/// Write (serialize) an object to a JSON string
#[cfg(feature = "json")]
fn to_json(&self) -> anyhow::Result<String> {
Ok(serde_json::to_string(&self)?)
}
/// Read (deserialize) an object from a JSON string
///
/// # Arguments
///
/// * `json_str` - JSON-formatted string to deserialize from
///
#[cfg(feature = "json")]
fn from_json<S: AsRef<str>>(json_str: S, skip_init: bool) -> anyhow::Result<Self> {
let mut json_de: Self = serde_json::from_str(json_str.as_ref())?;
if !skip_init {
json_de.init()?;
}
Ok(json_de)
}
/// Write (serialize) an object to a message pack
#[cfg(feature = "msgpack")]
fn to_msg_pack(&self) -> anyhow::Result<Vec<u8>> {
Ok(rmp_serde::encode::to_vec_named(&self)?)
}
/// Read (deserialize) an object from a message pack
///
/// # Arguments
///
/// * `msg_pack` - message pack object
///
#[cfg(feature = "msgpack")]
fn from_msg_pack(msg_pack: &[u8], skip_init: bool) -> anyhow::Result<Self> {
let mut msg_pack_de: Self = rmp_serde::decode::from_slice(msg_pack)?;
if !skip_init {
msg_pack_de.init()?;
}
Ok(msg_pack_de)
}
/// Write (serialize) an object to a TOML string
#[cfg(feature = "toml")]
fn to_toml(&self) -> anyhow::Result<String> {
Ok(toml::to_string(&self)?)
}
/// Read (deserialize) an object from a TOML string
///
/// # Arguments
///
/// * `toml_str` - TOML-formatted string to deserialize from
///
#[cfg(feature = "toml")]
fn from_toml<S: AsRef<str>>(toml_str: S, skip_init: bool) -> anyhow::Result<Self> {
let mut toml_de: Self = toml::from_str(toml_str.as_ref())?;
if !skip_init {
toml_de.init()?;
}
Ok(toml_de)
}
/// Write (serialize) an object to a YAML string
#[cfg(feature = "yaml")]
fn to_yaml(&self) -> anyhow::Result<String> {
Ok(serde_yaml::to_string(&self)?)
}
/// Read (deserialize) an object from a YAML string
///
/// # Arguments
///
/// * `yaml_str` - YAML-formatted string to deserialize from
///
#[cfg(feature = "yaml")]
fn from_yaml<S: AsRef<str>>(yaml_str: S, skip_init: bool) -> anyhow::Result<Self> {
let mut yaml_de: Self = serde_yaml::from_str(yaml_str.as_ref())?;
if !skip_init {
yaml_de.init()?;
}
Ok(yaml_de)
}
}
impl<T: Init> Init for Vec<T> {
fn init(&mut self) -> Result<(), Error> {
for val in self {
val.init()?
}
Ok(())
}
}
impl<T: SerdeAPI> SerdeAPI for Vec<T> {}