r4d/storage.rs
1/// Result alias for storage operation
2///
3/// Error is a boxed container for generic error trait. Therefore any kind of errors can be
4/// captured by storageresult.
5pub type StorageResult<T> = Result<T, Box<dyn std::error::Error>>;
6
7/// Triat for storage interaction
8///
9/// Rad can utilizes storage to save given input as modified form and extract data from
10///
11/// # Example
12///
13/// ```rust
14/// use r4d::{RadStorage, RadError, StorageOutput, StorageResult};
15///
16/// pub struct StorageDemo {
17/// content: Vec<String>,
18/// }
19///
20/// impl RadStorage for StorageDemo {
21/// fn update(&mut self, args: &[String]) -> StorageResult<()> {
22/// if args.is_empty() {
23/// return Err(Box::new(RadError::InvalidArgument("Not enough arguments".to_string())));
24/// }
25/// self.content.push(args[0].clone());
26///
27/// Ok(())
28/// }
29/// fn extract(&mut self, serialize: bool) -> StorageResult<Option<StorageOutput>> {
30/// let result = if serialize {
31/// StorageOutput::Binary(self.content.join(",").as_bytes().to_vec())
32/// } else {
33/// StorageOutput::Text(self.content.join(","))
34/// };
35/// Ok(Some(result))
36/// }
37/// }
38/// ```
39pub trait RadStorage {
40 /// Update storage with given arguments
41 fn update(&mut self, args: &[String]) -> StorageResult<()>;
42 /// Extract data from storage.
43 ///
44 /// # Args
45 ///
46 /// - serialize : whether to serialize storage output or not
47 fn extract(&mut self, serialize: bool) -> StorageResult<Option<StorageOutput>>;
48}
49
50#[derive(Debug)]
51/// Output that storage creates
52pub enum StorageOutput {
53 /// Binary form of output
54 Binary(Vec<u8>),
55 /// Text form of output
56 Text(String),
57}
58
59impl StorageOutput {
60 /// Convert storage output into a printable string
61 pub(crate) fn into_printable(self) -> String {
62 match self {
63 Self::Binary(bytes) => format!("{:?}", bytes),
64 Self::Text(text) => text,
65 }
66 }
67}