feagi_data_serialization/implementations/
feagi_json.rs1use std::any::Any;
7use feagi_data_structures::FeagiJSON;
8use feagi_data_structures::FeagiDataError;
9use crate::{FeagiByteContainer, FeagiByteStructureType, FeagiSerializable};
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().as_bytes().len() + FeagiByteContainer::STRUCT_HEADER_BYTE_COUNT
25 }
26
27 fn try_serialize_struct_to_byte_slice(&self, byte_destination: &mut [u8]) -> Result<(), FeagiDataError> {
28 byte_destination[0] = self.get_type() as u8;
29 byte_destination[1] = self.get_version();
30
31 let json_string = self.borrow_json_value().to_string();
32 let json_bytes = json_string.as_bytes();
33
34 byte_destination[FeagiByteContainer::STRUCT_HEADER_BYTE_COUNT..].copy_from_slice(json_bytes);
36 Ok(())
37 }
38
39 fn try_deserialize_and_update_self_from_byte_slice(&mut self, byte_structure_slice: &[u8]) -> Result<(), FeagiDataError> {
40 self.verify_byte_slice_is_of_correct_version(byte_structure_slice)?;
42
43 let json_bytes = &byte_structure_slice[FeagiByteContainer::STRUCT_HEADER_BYTE_COUNT..];
44
45 let json_value = match serde_json::from_slice(json_bytes) {
47 Ok(value) => value,
48 Err(e) => return Err(FeagiDataError::DeserializationError(format!("Invalid JSON data: {}", e))),
49 };
50 self.update_json_value(json_value);
51
52 Ok(())
53 }
54
55 fn as_any(&self) -> &dyn Any {
56 self
57 }
58
59}