rof_rs/rof_compat/
mod.rs

1// A trait that allows a rust struct to serialized and deserialized
2
3use crate::object_format::{rof::Rof, DataValue};
4
5/// ## Rof Compatible
6/// A trait that enables a high level abstraction from the low level system that allows serializing and deserializing any ```RofCompat``` implementing type to string.
7/// Using the ```RofCompat``` derive macro, you can automatically implement the ```RofCompat``` trait on any struct or enum in most situations (refer to docs for more information).
8///
9/// In order to manually implement ```RofCompat``` for any type, the `serialize` and `deserialize` methods only have to be implemented, as the other functions are only utility functions based on those two simple methods.
10pub trait RofCompat: Default {
11    /// ## Serialize
12    ///
13    /// Serialize ```RofCompat``` implementing object to a ```DataValue``` implementing object.
14    ///
15    /// ## Example
16    ///
17    /// ```
18    /// fn serialize(&self) -> Box<dyn DataValue> {
19    ///     Box::new(DataValueInteger::U32(
20    ///         65536 * (self.r as u32) + 256 * (self.g as u32) + (self.b as u32),
21    ///     ))
22    /// }
23    /// ```
24    fn serialize(&self) -> Box<dyn DataValue>;
25
26    fn serialize_to_string(&self, pretty_print: bool) -> String {
27        Rof::new(self.serialize()).serialize(pretty_print)
28    }
29
30    /// ## Deserialize
31    ///
32    /// Deserialize a ```DataValue``` implementing (not string) to itself.
33    ///
34    /// ## Example
35    ///
36    /// ```
37    /// fn deserialize(rof_object: Box<dyn DataValue>) -> Self {
38    ///     let color_int: u32 = rof_object.as_u32();
39    ///
40    ///     Self {
41    ///         r: (color_int % 16_777_216 / 65_536) as u8,
42    ///         g: (color_int % 65_536 / 256) as u8,
43    ///         b: (color_int % 256) as u8,
44    ///     }
45    /// }
46    /// ```
47    fn deserialize(rof_object: Box<dyn DataValue>) -> Self;
48
49    fn deserialize_from_string(serialized_rof: &str) -> Self {
50        Self::deserialize(Rof::deserialize(serialized_rof).get_object())
51    }
52
53    /// ## As Rof
54    ///
55    /// Returns a new Rof created from itself's serialized value
56    fn as_rof(&self) -> Rof {
57        Rof::new(self.serialize())
58    }
59
60    fn load_from_file(file_path: &str) -> Self {
61        Self::deserialize(Rof::load_from_file(file_path).get_object())
62    }
63
64    fn save_to_file(&self, file_path: &str, pretty_print: bool) -> Result<(), ()> {
65        Rof::new(self.serialize()).save_to_file(file_path, pretty_print)
66    }
67}
68
69pub mod inbuilt_type_extensions;