cellular_raza_core/storage/
serde_json.rs1use super::concepts::StorageError;
2use super::concepts::{FileBasedStorage, StorageInterfaceOpen};
3use serde::{Deserialize, Serialize};
4
5use core::marker::PhantomData;
6
7#[cfg(feature = "tracing")]
8use tracing::instrument;
9
10#[derive(Clone, Debug, Deserialize, Serialize)]
12pub struct JsonStorageInterface<Id, Element> {
13 path: std::path::PathBuf,
14 storage_instance: u64,
15 phantom_id: PhantomData<Id>,
16 phantom_element: PhantomData<Element>,
17}
18
19impl<Id, Element> FileBasedStorage<Id, Element> for JsonStorageInterface<Id, Element> {
20 const EXTENSION: &'static str = "json";
21
22 fn get_path(&self) -> &std::path::Path {
23 &self.path
24 }
25
26 fn get_storage_instance(&self) -> u64 {
27 self.storage_instance
28 }
29
30 fn to_writer_pretty<V, W>(&self, writer: W, value: &V) -> Result<(), StorageError>
31 where
32 V: Serialize,
33 W: std::io::Write,
34 {
35 Ok(serde_json::to_writer_pretty(writer, value)?)
36 }
37
38 fn from_str<V>(&self, input: &str) -> Result<V, StorageError>
39 where
40 V: for<'a> Deserialize<'a>,
41 {
42 Ok(serde_json::from_str(input)?)
43 }
44}
45
46impl<Id, Element> StorageInterfaceOpen for JsonStorageInterface<Id, Element> {
47 #[cfg_attr(feature = "tracing", instrument(skip_all))]
48 fn open_or_create(
49 location: &std::path::Path,
50 storage_instance: u64,
51 ) -> Result<Self, StorageError>
52 where
53 Self: Sized,
54 {
55 if !location.is_dir() {
56 std::fs::create_dir_all(location)?;
57 }
58 Ok(JsonStorageInterface {
59 path: location.into(),
60 storage_instance,
61 phantom_id: PhantomData,
62 phantom_element: PhantomData,
63 })
64 }
65
66 fn clone_to_new_instance(&self, storage_instance: u64) -> Self {
67 Self {
68 path: self.path.clone(),
69 storage_instance,
70 phantom_id: PhantomData,
71 phantom_element: PhantomData,
72 }
73 }
74}