datex_core/values/serde/
serializer.rs

1use serde::ser::{
2    Serialize, SerializeStruct, SerializeTuple, SerializeTupleStruct,
3    Serializer,
4};
5use std::fmt::Display;
6use log::info;
7use crate::compiler::compile_value;
8use crate::runtime::execution::{execute_dxb_sync, ExecutionInput, ExecutionOptions};
9use crate::values::core_value::CoreValue;
10use crate::values::core_values::object::Object;
11use crate::values::core_values::tuple::Tuple;
12use crate::values::serde::error::SerializationError;
13use crate::values::value::Value;
14use crate::values::value_container::ValueContainer;
15pub struct DatexSerializer {
16    container: ValueContainer,
17}
18
19impl Default for DatexSerializer {
20    fn default() -> Self {
21        Self::new()
22    }
23}
24
25impl DatexSerializer {
26    pub fn new() -> Self {
27        DatexSerializer {
28            container: CoreValue::Null.into(),
29        }
30    }
31
32    pub fn into_inner(self) -> ValueContainer {
33        self.container
34    }
35}
36
37pub fn to_bytes<T>(value: &T) -> Result<Vec<u8>, SerializationError>
38where
39    T: Serialize,
40{
41    let value_container = to_value_container(value)?;
42    println!("Value container: {value_container:?}");
43    compile_value(&value_container).map_err(|e| {
44        SerializationError(format!("Failed to compile value: {e}"))
45    })
46}
47pub fn to_value_container<T>(
48    value: &T,
49) -> Result<ValueContainer, SerializationError>
50where
51    T: Serialize,
52{
53    let mut serializer = DatexSerializer::new();
54    let container = value.serialize(&mut serializer)?;
55    Ok(container)
56}
57
58impl SerializeStruct for &mut DatexSerializer {
59    type Ok = ValueContainer;
60    type Error = SerializationError;
61
62    fn serialize_field<T: ?Sized>(
63        &mut self,
64        key: &'static str,
65        value: &T,
66    ) -> Result<(), Self::Error>
67    where
68        T: Serialize,
69    {
70        let mut serializer = DatexSerializer::new();
71        let value_container = value.serialize(&mut serializer)?;
72        match self.container {
73            ValueContainer::Value(Value {
74                inner: CoreValue::Object(ref mut obj),
75                ..
76            }) => {
77                obj.set(key, value_container);
78            }
79            _ => {
80                return Err(SerializationError(
81                    "Cannot serialize field into non-object container"
82                        .to_string(),
83                ));
84            }
85        }
86        Ok(())
87    }
88
89    fn end(self) -> Result<Self::Ok, Self::Error> {
90        Ok(self.container.clone())
91    }
92}
93
94impl SerializeTuple for &mut DatexSerializer {
95    type Ok = ValueContainer;
96    type Error = SerializationError;
97
98    fn serialize_element<T: ?Sized>(
99        &mut self,
100        value: &T,
101    ) -> Result<(), Self::Error>
102    where
103        T: Serialize,
104    {
105        let value_container = value.serialize(&mut **self)?;
106        match self.container {
107            ValueContainer::Value(Value {
108                inner: CoreValue::Tuple(ref mut tuple),
109                ..
110            }) => {
111                tuple.insert(value_container);
112            }
113            _ => {
114                return Err(SerializationError(
115                    "Cannot serialize element into non-tuple container"
116                        .to_string(),
117                ));
118            }
119        }
120        Ok(())
121    }
122
123    fn end(self) -> Result<Self::Ok, Self::Error> {
124        Ok(self.container.clone())
125    }
126}
127
128impl SerializeTupleStruct for &mut DatexSerializer {
129    type Ok = ValueContainer;
130    type Error = SerializationError;
131
132    fn serialize_field<T: ?Sized>(
133        &mut self,
134        value: &T,
135    ) -> Result<(), Self::Error>
136    where
137        T: Serialize,
138    {
139        let value_container = value.serialize(&mut **self)?;
140        match self.container {
141            ValueContainer::Value(Value {
142                inner: CoreValue::Tuple(ref mut tuple),
143                ..
144            }) => {
145                tuple.insert(value_container);
146            }
147            _ => {
148                return Err(SerializationError(
149                    "Cannot serialize element into non-tuple container"
150                        .to_string(),
151                ));
152            }
153        }
154        Ok(())
155    }
156
157    fn end(self) -> Result<Self::Ok, Self::Error> {
158        Ok(self.container.clone())
159    }
160}
161
162impl Serializer for &mut DatexSerializer {
163    type Ok = ValueContainer;
164    type Error = SerializationError;
165
166    // Non implemented types
167    type SerializeSeq = serde::ser::Impossible<Self::Ok, Self::Error>;
168    type SerializeTupleVariant = serde::ser::Impossible<Self::Ok, Self::Error>;
169    type SerializeMap = serde::ser::Impossible<Self::Ok, Self::Error>;
170    type SerializeStructVariant = serde::ser::Impossible<Self::Ok, Self::Error>;
171
172    // Implemented types
173    type SerializeStruct = Self;
174    type SerializeTuple = Self;
175    type SerializeTupleStruct = Self;
176
177    fn serialize_struct(
178        self,
179        _name: &'static str,
180        _len: usize,
181    ) -> Result<Self::SerializeStruct, Self::Error> {
182        self.container = Object::new().into();
183        Ok(self)
184    }
185
186    fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error> {
187        Ok(ValueContainer::from(v))
188    }
189
190    fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error> {
191        Ok(ValueContainer::from(v))
192    }
193
194    fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error> {
195        Ok(ValueContainer::from(v))
196    }
197
198    fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error> {
199        Ok(ValueContainer::from(v))
200    }
201
202    fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error> {
203        Ok(ValueContainer::from(v))
204    }
205
206    fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error> {
207        Ok(ValueContainer::from(v))
208    }
209
210    fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error> {
211        Ok(ValueContainer::from(v))
212    }
213
214    fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error> {
215        Ok(ValueContainer::from(v))
216    }
217
218    fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error> {
219        Ok(ValueContainer::from(v))
220    }
221
222    fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error> {
223        Ok(ValueContainer::from(v))
224    }
225
226    fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error> {
227        Ok(ValueContainer::from(v))
228    }
229
230    fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error> {
231        Ok(ValueContainer::from(v.to_string()))
232    }
233
234    fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error> {
235        Ok(ValueContainer::from(v))
236    }
237
238    fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error> {
239        todo!("#134 Undescribed by author.")
240    }
241
242    fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
243        Ok(CoreValue::Null.into())
244    }
245
246    fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
247    where
248        T: ?Sized + serde::Serialize,
249    {
250        value.serialize(&mut *self).map_err(|e| {
251            SerializationError(format!("Failed to serialize some: {e}"))
252        })
253    }
254
255    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
256        todo!("#136 Undescribed by author.")
257    }
258
259    fn serialize_unit_struct(
260        self,
261        name: &'static str,
262    ) -> Result<Self::Ok, Self::Error> {
263        todo!("#137 Undescribed by author.")
264    }
265
266    fn serialize_unit_variant(
267        self,
268        name: &'static str,
269        variant_index: u32,
270        variant: &'static str,
271    ) -> Result<Self::Ok, Self::Error> {
272        // convert enum variant name to text
273        Ok(ValueContainer::from(variant))
274    }
275
276    fn serialize_newtype_struct<T>(
277        self,
278        name: &'static str,
279        value: &T,
280    ) -> Result<Self::Ok, Self::Error>
281    where
282        T: ?Sized + serde::Serialize,
283    {
284        if name == "endpoint" {
285            let endpoint = value
286                .serialize(&mut *self)
287                .map_err(|e| {
288                    SerializationError(format!(
289                        "Failed to serialize endpoint: {e}"
290                    ))
291                })?
292                .to_value()
293                .borrow()
294                .cast_to_endpoint()
295                .unwrap();
296            Ok(ValueContainer::from(endpoint))
297        }
298        else if name == "value" {
299            info!("Serializing value");
300            // unsafe cast value to ValueContainer
301            let bytes = unsafe {
302                &*(value as *const T as *const Vec<u8>)
303            };
304            Ok(execute_dxb_sync(ExecutionInput::new_with_dxb_and_options(bytes, ExecutionOptions::default())).unwrap().unwrap())
305        }
306        else if name == "object" {
307            let object = value
308                .serialize(&mut *self);
309            Ok(object.map_err(|e| {
310                SerializationError(format!("Failed to serialize object: {e}"))
311            })?)
312        }
313        else {
314            unreachable!()
315        }
316    }
317
318    fn serialize_newtype_variant<T>(
319        self,
320        name: &'static str,
321        variant_index: u32,
322        variant: &'static str,
323        value: &T,
324    ) -> Result<Self::Ok, Self::Error>
325    where
326        T: ?Sized + serde::Serialize,
327    {
328        todo!("#140 Undescribed by author.")
329    }
330
331    fn serialize_seq(
332        self,
333        len: Option<usize>,
334    ) -> Result<Self::SerializeSeq, Self::Error> {
335        todo!("#141 Undescribed by author.")
336    }
337
338    fn serialize_tuple(
339        self,
340        len: usize,
341    ) -> Result<Self::SerializeTuple, Self::Error> {
342        self.container = Tuple::default().into();
343        Ok(self)
344    }
345
346    fn serialize_tuple_struct(
347        self,
348        name: &'static str,
349        len: usize,
350    ) -> Result<Self::SerializeTupleStruct, Self::Error> {
351        self.container = Tuple::default().into();
352        Ok(self)
353    }
354
355    fn serialize_tuple_variant(
356        self,
357        name: &'static str,
358        variant_index: u32,
359        variant: &'static str,
360        len: usize,
361    ) -> Result<Self::SerializeTupleVariant, Self::Error> {
362        todo!("#142 Undescribed by author.")
363    }
364
365    fn serialize_map(
366        self,
367        len: Option<usize>,
368    ) -> Result<Self::SerializeMap, Self::Error> {
369        todo!("#143 Undescribed by author.")
370    }
371
372    fn serialize_struct_variant(
373        self,
374        name: &'static str,
375        variant_index: u32,
376        variant: &'static str,
377        len: usize,
378    ) -> Result<Self::SerializeStructVariant, Self::Error> {
379        todo!("#144 Undescribed by author.")
380    }
381
382    fn serialize_i128(self, v: i128) -> Result<Self::Ok, Self::Error> {
383        Ok(ValueContainer::from(v))
384    }
385
386    fn serialize_u128(self, v: u128) -> Result<Self::Ok, Self::Error> {
387        Ok(ValueContainer::from(v))
388    }
389
390    fn collect_seq<I>(self, iter: I) -> Result<Self::Ok, Self::Error>
391    where
392        I: IntoIterator,
393        <I as IntoIterator>::Item: Serialize,
394    {
395        let mut seq = Vec::new();
396        for item in iter {
397            let value_container = item.serialize(&mut *self)?;
398            seq.push(value_container);
399        }
400        Ok(ValueContainer::from(seq))
401    }
402
403    fn collect_map<K, V, I>(self, iter: I) -> Result<Self::Ok, Self::Error>
404    where
405        K: Serialize,
406        V: Serialize,
407        I: IntoIterator<Item = (K, V)>,
408    {
409        todo!("#145 Undescribed by author.")
410    }
411
412    fn collect_str<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
413    where
414        T: ?Sized + Display,
415    {
416        println!("Collecting str: {value}");
417        self.serialize_str(&value.to_string())
418    }
419
420    fn is_human_readable(&self) -> bool {
421        true
422    }
423}
424
425#[cfg(test)]
426mod tests {
427    use crate::values::core_values::endpoint::Endpoint;
428    use crate::values::core_values::object::Object;
429    use crate::values::traits::structural_eq::StructuralEq;
430    use crate::values::{
431        core_value::CoreValue,
432        serde::serializer::{DatexSerializer, to_bytes, to_value_container},
433        value::Value,
434        value_container::ValueContainer,
435    };
436    use crate::{assert_structural_eq, assert_value_eq};
437    use serde::{Deserialize, Serialize};
438    use std::assert_matches::assert_matches;
439    use std::collections::HashMap;
440
441    #[derive(Serialize)]
442    struct TestStruct {
443        field1: String,
444        field2: i32,
445    }
446
447    #[derive(Serialize)]
448    enum TestEnum {
449        Variant1,
450        Variant2,
451    }
452
453    #[derive(Serialize)]
454    struct TestStructWithEndpoint {
455        endpoint: Endpoint,
456    }
457
458    #[derive(Serialize, Deserialize, Debug)]
459    pub struct StructWithUSize {
460        pub usize: Option<usize>,
461    }
462
463    #[test]
464    fn test_to_value_container() {
465        let test_struct = TestStruct {
466            field1: "Hello".to_string(),
467            field2: 42,
468        };
469        let result = to_value_container(&test_struct);
470        assert!(result.is_ok());
471        println!("{:?}", result.unwrap());
472    }
473
474    #[test]
475    fn test_to_bytes() {
476        let test_struct = TestStruct {
477            field1: "Hello".to_string(),
478            field2: 42,
479        };
480        let result = to_bytes(&test_struct);
481        assert!(result.is_ok());
482        assert!(!result.unwrap().is_empty());
483    }
484
485    #[test]
486    fn test_to_bytes_with_struct_with_usize() {
487        let test_struct = StructWithUSize { usize: Some(42) };
488        let result = to_value_container(&test_struct);
489        assert!(result.is_ok());
490        let result = result.unwrap();
491        assert_structural_eq!(
492            result
493                .to_value()
494                .borrow()
495                .cast_to_object()
496                .unwrap()
497                .get("usize")
498                .clone(),
499            ValueContainer::from(42)
500        );
501    }
502
503    #[test]
504    fn test_datex_serializer() {
505        let mut serializer = DatexSerializer::new();
506        let test_struct = TestStruct {
507            field1: "Hello".to_string(),
508            field2: 42,
509        };
510        let _ = test_struct.serialize(&mut serializer);
511        let result = serializer.into_inner();
512        assert_matches!(
513            result,
514            ValueContainer::Value(Value {
515                inner: CoreValue::Object(_),
516                ..
517            })
518        );
519    }
520
521    #[test]
522    fn test_enum() {
523        let test_enum = TestEnum::Variant1;
524        let result = to_value_container(&test_enum);
525        assert!(result.is_ok());
526        let result = result.unwrap();
527
528        assert_eq!(result, ValueContainer::from("Variant1"));
529    }
530
531    #[test]
532    fn test_endpoint() {
533        let test_struct = TestStructWithEndpoint {
534            endpoint: Endpoint::new("@test"),
535        };
536
537        let result = to_value_container(&test_struct);
538        assert!(result.is_ok());
539        let result = result.unwrap();
540        let object = Object::from(HashMap::from([(
541            "endpoint".to_string(),
542            ValueContainer::from(Endpoint::new("@test")),
543        )]));
544        assert_eq!(result, ValueContainer::from(object));
545    }
546}