feagi_serialization/implementations/
feagi_json.rs1use crate::{FeagiByteContainer, FeagiByteStructureType, FeagiSerializable};
7use feagi_structures::FeagiDataError;
8use feagi_structures::FeagiJSON;
9use std::any::Any;
10
11const BYTE_STRUCT_VERSION: u8 = 1;
13
14impl FeagiSerializable for FeagiJSON {
15 fn get_type(&self) -> FeagiByteStructureType {
16 FeagiByteStructureType::JSON
17 }
18
19 fn get_version(&self) -> u8 {
20 BYTE_STRUCT_VERSION
21 }
22
23 fn get_number_of_bytes_needed(&self) -> usize {
24 self.borrow_json_value().to_string().len() + FeagiByteContainer::STRUCT_HEADER_BYTE_COUNT
25 }
26
27 fn try_serialize_struct_to_byte_slice(
28 &self,
29 byte_destination: &mut [u8],
30 ) -> Result<(), FeagiDataError> {
31 byte_destination[0] = self.get_type() as u8;
32 byte_destination[1] = self.get_version();
33
34 let json_string = self.borrow_json_value().to_string();
35 let json_bytes = json_string.as_bytes();
36
37 byte_destination[FeagiByteContainer::STRUCT_HEADER_BYTE_COUNT..]
39 .copy_from_slice(json_bytes);
40 Ok(())
41 }
42
43 fn try_deserialize_and_update_self_from_byte_slice(
44 &mut self,
45 byte_structure_slice: &[u8],
46 ) -> Result<(), FeagiDataError> {
47 self.verify_byte_slice_is_of_correct_version(byte_structure_slice)?;
49
50 let json_bytes = &byte_structure_slice[FeagiByteContainer::STRUCT_HEADER_BYTE_COUNT..];
51
52 let json_value = match serde_json::from_slice(json_bytes) {
54 Ok(value) => value,
55 Err(e) => {
56 return Err(FeagiDataError::DeserializationError(format!(
57 "Invalid JSON data: {}",
58 e
59 )))
60 }
61 };
62 self.update_json_value(json_value);
63
64 Ok(())
65 }
66
67 fn as_any(&self) -> &dyn Any {
68 self
69 }
70}