feagi_data_serialization/implementations/
feagi_json.rs

1//! Serialization implementation for JSON data structures.
2//!
3//! Provides UTF-8 text serialization for `FeagiJSON` values, allowing
4//! arbitrary JSON data to be stored in FEAGI byte containers.
5
6use feagi_data_structures::FeagiJSON;
7use feagi_data_structures::FeagiDataError;
8use crate::{FeagiByteContainer, FeagiByteStructureType, FeagiSerializable};
9
10/// Current version of the JSON serialization format.
11const BYTE_STRUCT_VERSION: u8 = 1;
12
13impl FeagiSerializable for FeagiJSON {
14    fn get_type(&self) -> FeagiByteStructureType {
15        FeagiByteStructureType::JSON
16    }
17
18    fn get_version(&self) -> u8 {
19        BYTE_STRUCT_VERSION
20    }
21
22    fn get_number_of_bytes_needed(&self) -> usize {
23        self.borrow_json_value().to_string().as_bytes().len() + FeagiByteContainer::STRUCT_HEADER_BYTE_COUNT
24    }
25
26    fn try_serialize_struct_to_byte_slice(&self, byte_destination: &mut [u8]) -> Result<(), FeagiDataError> {
27        byte_destination[0] = self.get_type() as u8;
28        byte_destination[1] = self.get_version();
29
30        let json_string = self.borrow_json_value().to_string();
31        let json_bytes = json_string.as_bytes();
32
33        // Write the JSON data as UTF-8 bytes
34        byte_destination[FeagiByteContainer::STRUCT_HEADER_BYTE_COUNT..].copy_from_slice(json_bytes);
35        Ok(())
36    }
37
38    fn try_deserialize_and_update_self_from_byte_slice(&mut self, byte_structure_slice: &[u8]) -> Result<(), FeagiDataError> {
39        // Assuming type is correct
40        self.verify_byte_slice_is_of_correct_version(byte_structure_slice)?;
41        
42        let json_bytes = &byte_structure_slice[FeagiByteContainer::STRUCT_HEADER_BYTE_COUNT..];
43
44        // Parse JSON string
45        let json_value = match serde_json::from_slice(json_bytes) {
46            Ok(value) => value,
47            Err(e) => return Err(FeagiDataError::DeserializationError(format!("Invalid JSON data: {}", e))),
48        };
49        self.update_json_value(json_value);
50
51        Ok(())
52    }
53
54
55}