Skip to main content

feagi_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 crate::{FeagiByteContainer, FeagiByteStructureType, FeagiSerializable};
7use feagi_structures::FeagiDataError;
8use feagi_structures::FeagiJSON;
9use std::any::Any;
10
11/// Current version of the JSON serialization format.
12const 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        let header = FeagiByteContainer::STRUCT_HEADER_BYTE_COUNT;
37        let end = header + json_bytes.len();
38        if end > byte_destination.len() {
39            return Err(FeagiDataError::SerializationError(format!(
40                "JSON serialization overflow: need {} bytes, have {}",
41                end,
42                byte_destination.len()
43            )));
44        }
45        // Write the JSON data as UTF-8 bytes (length may differ from get_number_of_bytes_needed due to serde_json formatting)
46        byte_destination[header..end].copy_from_slice(json_bytes);
47        Ok(())
48    }
49
50    fn try_deserialize_and_update_self_from_byte_slice(
51        &mut self,
52        byte_structure_slice: &[u8],
53    ) -> Result<(), FeagiDataError> {
54        // Assuming type is correct
55        self.verify_byte_slice_is_of_correct_version(byte_structure_slice)?;
56
57        let json_bytes = &byte_structure_slice[FeagiByteContainer::STRUCT_HEADER_BYTE_COUNT..];
58
59        // Parse JSON string
60        let json_value = match serde_json::from_slice(json_bytes) {
61            Ok(value) => value,
62            Err(e) => {
63                return Err(FeagiDataError::DeserializationError(format!(
64                    "Invalid JSON data: {}",
65                    e
66                )))
67            }
68        };
69        self.update_json_value(json_value);
70
71        Ok(())
72    }
73
74    fn as_any(&self) -> &dyn Any {
75        self
76    }
77}