cellular_raza_core/storage/
ron.rs

1use super::concepts::StorageError;
2use super::concepts::{FileBasedStorage, StorageInterfaceOpen};
3use serde::{Deserialize, Serialize};
4
5use core::marker::PhantomData;
6
7/// Save elements as ron files with [ron].
8#[derive(Clone, Debug, Deserialize, Serialize)]
9pub struct RonStorageInterface<Id, Element> {
10    path: std::path::PathBuf,
11    storage_instance: u64,
12    phantom_id: PhantomData<Id>,
13    phantom_element: PhantomData<Element>,
14}
15
16impl<Id, Element> FileBasedStorage<Id, Element> for RonStorageInterface<Id, Element> {
17    const EXTENSION: &'static str = "ron";
18
19    fn get_path(&self) -> &std::path::Path {
20        &self.path
21    }
22
23    fn get_storage_instance(&self) -> u64 {
24        self.storage_instance
25    }
26
27    fn to_writer_pretty<V, W>(&self, writer: W, value: &V) -> Result<(), StorageError>
28    where
29        V: Serialize,
30        W: std::io::Write,
31    {
32        let config = ron::ser::PrettyConfig::new()
33            .depth_limit(usize::MAX)
34            .struct_names(true)
35            .separate_tuple_members(false)
36            .compact_arrays(true)
37            .indentor("  ".to_owned());
38        let options = ron::Options::default();
39        Ok(options.to_io_writer_pretty(writer, value, config)?)
40    }
41
42    fn from_str<V>(&self, input: &str) -> Result<V, StorageError>
43    where
44        V: for<'a> Deserialize<'a>,
45    {
46        Ok(ron::de::from_str(input)?)
47    }
48}
49
50impl<Id, Element> StorageInterfaceOpen for RonStorageInterface<Id, Element> {
51    fn open_or_create(
52        location: &std::path::Path,
53        storage_instance: u64,
54    ) -> Result<Self, StorageError>
55    where
56        Self: Sized,
57    {
58        if !location.is_dir() {
59            std::fs::create_dir_all(location)?;
60        }
61        Ok(RonStorageInterface {
62            path: location.into(),
63            storage_instance,
64            phantom_id: PhantomData,
65            phantom_element: PhantomData,
66        })
67    }
68
69    fn clone_to_new_instance(&self, storage_instance: u64) -> Self {
70        Self {
71            path: self.path.clone(),
72            storage_instance,
73            phantom_id: PhantomData,
74            phantom_element: PhantomData,
75        }
76    }
77}