rs_flow/package/
package.rs

1use std::collections::HashMap;
2
3use serde::{Deserialize, Serialize};
4
5use super::{error::PackageError, 
6    serde::{deserialize, serialize, PackageDeserializerError, PackageSerializerError}
7};
8
9
10#[derive(Debug, Clone, Serialize, Deserialize, Default)]
11#[serde(untagged)]
12pub enum Package {
13    #[default]
14    Empty,
15    Number(f64),
16    String(String),
17    Boolean(bool),
18    Bytes(Vec<u8>),
19    Array(Vec<Package>),
20    Object(HashMap<String, Package>)
21}
22
23impl Package {
24    /// Try create a [Package] from a type that implement Serialize
25    /// 
26    /// ```
27    /// use rs_flow::package::Package;
28    /// use serde::Serialize;
29    /// 
30    /// #[derive(Serialize)]
31    /// struct Person {
32    ///     name: String,
33    ///     age: u16
34    /// }
35    /// 
36    /// let package = Package::try_from(Person { name: "Boby".to_string(), age: 24 }).unwrap();
37    /// let mut person = package.get_object().unwrap(); 
38    /// let name = person.remove("name").unwrap().get_string().unwrap();
39    /// let age = person.remove("age").unwrap().get_number().unwrap();
40    /// 
41    /// assert_eq!(&name, "Boby");
42    /// assert_eq!(age, 24.0);
43    /// ```
44    /// 
45    pub fn try_from<T: Serialize>(content: T) -> Result<Self, PackageSerializerError> {
46        serialize(content)
47    }
48    /// Try deserialize that [Package] to the type provided
49    /// 
50    /// ```
51    /// use rs_flow::package::Package;
52    /// use serde::Deserialize;
53    /// 
54    /// #[derive(Deserialize)]
55    /// struct Person {
56    ///     name: String,
57    ///     age: u16
58    /// }
59    /// 
60    /// let name = Package::string("Boby");
61    /// let age = Package::number(24.0);
62    /// let object = Package::object([
63    ///     ("name", name),
64    ///     ("age", age)
65    /// ]);
66    /// 
67    /// let person: Person = object.try_into().unwrap();
68    /// assert_eq!(&person.name, "Boby");
69    /// assert_eq!(person.age, 24);
70    /// ```
71    /// 
72    pub fn try_into<T: for<'a> Deserialize<'a>>(self) -> 
73        Result<T, PackageDeserializerError> 
74    {
75        deserialize(self)
76    }
77
78    /// Create a empty package
79    pub fn empty() -> Self {
80        Package::Empty
81    }
82    /// Create a package with a number
83    pub fn number(value: f64) -> Self {
84        value.into()
85    }
86    /// Create a package with a boolean
87    pub fn bool(value: bool) -> Self {
88        value.into()
89    }
90    /// Create a package with a string
91    pub fn string(value: &str) -> Self {
92        value.into()
93    }
94    /// Create a package with a byte array
95    pub fn bytes(value: &[u8]) -> Self {
96        value.into()
97    }
98    /// Create a package with a from a vector of packages
99    pub fn array<T: Into<Package>>(value: impl IntoIterator<Item = T>) -> Self {
100        Self::Array(value.into_iter().map(Into::into).collect())
101    }
102    /// Create a package with a object that represent a collection of entries of
103    /// that key is a string and tha value is a other package
104    pub fn object<T: Into<Package>, K: Into<String>>(value: impl IntoIterator<Item = (K, T)>) -> Self {
105        Self::Object(value.into_iter().map(|(k,v)| (k.into(), v.into())).collect())
106    }
107
108
109    /// Return if the package is Empty variant
110    pub fn is_empty(&self) -> bool { 
111        match self {
112            Package::Empty => true,
113            _ => false
114        }
115    }
116    /// Return if the package is Number variant
117    pub fn is_number(&self) -> bool { 
118        match self {
119            Package::Number(_) => true,
120            _ => false
121        }
122    }
123    /// Return if the package is Boolean variant
124    pub fn is_bool(&self) -> bool { 
125        match self {
126            Package::Boolean(_) => true,
127            _ => false
128        }
129    }
130    /// Return if the package is String variant
131    pub fn is_string(&self) -> bool { 
132        match self {
133            Package::String(_) => true,
134            _ => false
135        }
136    }
137    /// Return if the package is Bytes variant
138    pub fn is_bytes(&self) -> bool { 
139        match self {
140            Package::Bytes(_) => true,
141            _ => false
142        }
143    }
144    /// Return if the package is Array variant
145    pub fn is_array(&self) -> bool { 
146        match self {
147            Package::Array(_) => true,
148            _ => false
149        }
150    }
151    /// Return if the package is Object variant
152    pub fn is_object(&self) -> bool { 
153        match self {
154            Package::Object(_) => true,
155            _ => false
156        }
157    }
158
159
160    /// Return a () if the package is a Empty variant otherwise a error 
161    pub fn get_empty(self) -> Result<(), PackageError> { 
162        match self {
163            Package::Empty => Ok(()),
164            _ => Err(PackageError::NotEmpty)
165        }
166    }
167    /// Return a f64 if the package is a Number variant otherwise a error 
168    pub fn get_number(self) -> Result<f64, PackageError> { 
169        match self {
170            Package::Number(number) => Ok(number),
171            _ => Err(PackageError::NotNumber)
172        }
173    }
174    /// Return a String if the package is a String variant otherwise a error 
175    pub fn get_string(self) -> Result<String, PackageError> { 
176        match self {
177            Package::String(string) => Ok(string),
178            _ => Err(PackageError::NotString)
179        }
180    }
181    /// Return a bool if the package is a Boolean variant otherwise a error 
182    pub fn get_bool(self) -> Result<bool, PackageError> { 
183        match self {
184            Package::Boolean(bool) => Ok(bool),
185            _ => Err(PackageError::NotBoolean)
186        }
187    }
188    /// Return a Vec<u8> if the package is a Bytes variant otherwise a error 
189    pub fn get_bytes(self) -> Result<Vec<u8>, PackageError> { 
190        match self {
191            Package::Bytes(bytes) => Ok(bytes),
192            _ => Err(PackageError::NotBytes)
193        }
194    }
195    /// Return a Vec<Package> if the package is a Array variant otherwise a error 
196    pub fn get_array(self) -> Result<Vec<Package>, PackageError> { 
197        match self {
198            Package::Array(array) => Ok(array),
199            _ => Err(PackageError::NotArray)
200        }
201    }
202    /// Return a HashMap<String, Package>, if the package is a Object variant otherwise a error 
203    pub fn get_object(self) -> Result<HashMap<String, Package>, PackageError> { 
204        match self {
205            Package::Object(object) => Ok(object),
206            _ => Err(PackageError::NotObject)
207        }
208    }
209
210}
211
212
213
214/// Packages number implmentations
215macro_rules! impl_from_number {
216    ($($ty: ty),+) => {
217        $(
218            impl From<$ty> for Package {
219                fn from(value: $ty) -> Self {
220                    Package::Number(value as f64)
221                }
222            }
223        )+
224    };
225}
226impl_from_number!(u8, u16, u32, u64, usize);
227impl_from_number!(i8, i16, i32, i64, isize);
228impl_from_number!(f32, f64);
229
230/// Packages boolean implmentations
231impl From<bool> for Package {
232    fn from(value: bool) -> Self {
233        Package::Boolean(value)
234    }
235}
236
237
238/// Packages string implementations 
239impl From<String> for Package {
240    fn from(value: String) -> Self {
241        Package::String(value)
242    }
243}
244impl From<&str> for Package {
245    fn from(value: &str) -> Self {
246        Package::String(value.to_owned())
247    }
248}
249
250/// Packages bytes implementations 
251impl From<Vec<u8>> for Package {
252    fn from(value: Vec<u8>) -> Self {
253        Package::Bytes(value)
254    }
255}
256impl From<&[u8]> for Package {
257    fn from(value: &[u8]) -> Self {
258        Package::Bytes(value.into())
259    }
260}
261impl<const C: usize> From<[u8; C]> for Package {
262    fn from(value: [u8; C]) -> Self {
263        Package::Bytes(value.into())
264    }
265}