Skip to main content

datex_core/values/value/
serde_dif.rs

1use crate::{
2    dif::{
3        deserialize_serde_context::DeserializeSerdeContext,
4        deserialize_with_serde_context::DeserializeWithSerdeContext,
5        serde_context::SerdeContext,
6        serialize_with_serde_context::SerializeWithSerdeContext,
7        value_with_serde_context::ValueWithSerdeContext,
8    },
9    libs::core::{core_lib_id::CoreLibIdIndex, type_id::CoreLibTypeId},
10    prelude::*,
11    types::entities::entity_type_definition::dyn_deserialize::DynSeed,
12    values::{
13        core_value::CoreValue,
14        core_value_with_classification::{
15            CoreValueWithClassification, serde_dif::TagMarker,
16        },
17        value::{
18            Value,
19            value_classification::{ValueClassification, ValueTag},
20        },
21    },
22};
23use core::{fmt, str::FromStr};
24use num::ToPrimitive;
25use serde::{
26    Deserializer, Serialize, Serializer,
27    de::{self, Error as DeError, MapAccess, Visitor},
28    ser::{SerializeMap, SerializeTuple},
29};
30use strum::VariantNames;
31
32impl<'ctx> SerdeContext<'ctx> {
33    /// This method is used to serialize a value that can be represented directly depending on the flag set (e.g. a boolean or a text)
34    /// or with a custom type definition (e.g. a nominal type).
35    /// ## For no custom type:
36    ///   true -> "true"
37    ///   "Hello" -> "Hello"
38    ///   42f64 -> 42
39    ///   42f32 -> "42"
40    /// ## For custom type:
41    /// {custom_type: LiteralTypeDefinition::Integer(42), value: 42} -> [<core_lib_id>, <type_definition>, 42]
42    pub(crate) fn serialize_core_value<Se, T>(
43        &self,
44        inner: &T,
45        core_lib_type_id: CoreLibTypeId,
46        serializer: Se,
47        direct: bool,
48    ) -> Result<Se::Ok, Se::Error>
49    where
50        T: Serialize + ?Sized,
51        Se: Serializer,
52    {
53        if direct {
54            return inner.serialize(serializer);
55        }
56
57        let index = CoreLibIdIndex::from(core_lib_type_id);
58        let mut tuple = serializer.serialize_tuple(2)?;
59        tuple.serialize_element(&index.to_u16())?;
60        tuple.serialize_element(inner)?;
61        tuple.end()
62    }
63
64    /// This method is used to serialize a value that requires a context to be serialized (i.e. a value that implements [SerializeWithSerdeContext]).
65    /// It will serialize the value as a tuple of [<core_lib_id>, <value>, <classification>], where the classification is optional.
66    #[allow(unused)]
67    pub(crate) fn serialize_value_with_context<Se, T>(
68        &self,
69        inner: &T,
70        core_lib_type_id: CoreLibTypeId,
71        serializer: Se,
72        direct: bool,
73    ) -> Result<Se::Ok, Se::Error>
74    where
75        T: Sized,
76        Se: Serializer,
77        for<'a> T: SerializeWithSerdeContext,
78    {
79        if direct {
80            return inner.serialize_with_ctx(self, serializer);
81        }
82        let index = CoreLibIdIndex::from(core_lib_type_id);
83        let mut tuple = serializer.serialize_tuple(2)?;
84        tuple.serialize_element(&index.to_u16())?;
85        tuple.serialize_element(&ValueWithSerdeContext::new(inner, self))?;
86        tuple.end()
87    }
88
89    /// Deserializes into a [CoreValue] using the provided [CoreLibTypeId] to determine the type of the value.
90    pub(crate) fn deserialize_core_value<'de, D>(
91        &self,
92        deserializer: D,
93    ) -> Result<CoreValue, D::Error>
94    where
95        D: Deserializer<'de>,
96    {
97        let deserialize_ctx = DeserializeSerdeContext::<CoreValue>::new(self);
98        deserializer.deserialize_any(deserialize_ctx)
99    }
100}
101
102/// Serialization for [Value].
103impl SerializeWithSerdeContext for Value {
104    fn serialize_with_ctx<S>(
105        &self,
106        ctx: &SerdeContext<'_>,
107        serializer: S,
108    ) -> Result<S::Ok, S::Error>
109    where
110        S: Serializer,
111    {
112        match self {
113            Value::Native(native) => native.serialize_with_ctx(ctx, serializer),
114            Value::Core(core) => core.serialize_with_ctx(ctx, serializer),
115        }
116    }
117}
118
119impl SerializeWithSerdeContext for (&CoreValue, &Option<ValueTag>) {
120    fn serialize_with_ctx<S>(
121        &self,
122        ctx: &SerdeContext<'_>,
123        serializer: S,
124    ) -> Result<S::Ok, S::Error>
125    where
126        S: Serializer,
127    {
128        // if no tag, just serialize the core value
129        if self.1.is_none() {
130            self.0.serialize_with_ctx(ctx, serializer)
131        }
132        // else serialize as a map with "t" and "v" keys
133        else {
134            let mut map = serializer.serialize_map(Some(3))?;
135            map.serialize_entry(
136                TagMarker::Hint.as_ref(),
137                TagMarker::Tag.as_ref(),
138            )?;
139            map.serialize_entry(TagMarker::Tag.as_ref(), &self.1)?;
140            map.serialize_entry(
141                TagMarker::Value.as_ref(),
142                &ValueWithSerdeContext::new(&self.0, ctx),
143            )?;
144            map.end()
145        }
146    }
147}
148
149impl<'de> DeserializeWithSerdeContext<'de> for Value {
150    fn deserialize_with_ctx<D>(
151        ctx: &SerdeContext<'_>,
152        deserializer: D,
153    ) -> Result<Self, D::Error>
154    where
155        D: Deserializer<'de>,
156    {
157        deserializer.deserialize_any(DeserializeSerdeContext::<Value>::new(ctx))
158    }
159}
160
161impl<'de, 'a, 'ctx> Visitor<'de> for DeserializeSerdeContext<'a, 'ctx, Value> {
162    type Value = Value;
163
164    fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
165        f.write_str("a value, which can be a direct core value (e.g. boolean, text) or a complex value with a custom type definition")
166    }
167
168    /// default mapping for unit: null
169    fn visit_unit<E>(self) -> Result<Self::Value, E>
170    where
171        E: DeError,
172    {
173        Ok(Value::new(self.cast::<CoreValue>().visit_unit()?))
174    }
175
176    /// default mapping for none: null
177    fn visit_none<E>(self) -> Result<Self::Value, E>
178    where
179        E: DeError,
180    {
181        self.visit_unit()
182    }
183
184    /// default mapping for bool: boolean
185    fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
186    where
187        E: DeError,
188    {
189        Ok(Value::new(self.cast::<CoreValue>().visit_bool(v)?))
190    }
191
192    /// default mapping for string: text
193    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
194    where
195        E: DeError,
196    {
197        Ok(Value::new(self.cast::<CoreValue>().visit_str(v)?))
198    }
199    fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
200    where
201        E: DeError,
202    {
203        self.visit_str(&v)
204    }
205
206    /// default mapping for f64: decimal/f64
207    fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>
208    where
209        E: DeError,
210    {
211        Ok(Value::new(self.cast::<CoreValue>().visit_f64(v)?))
212    }
213
214    // default mapping for integers: decimal/f64 (with a check for overflow)
215    fn visit_i8<E>(self, v: i8) -> Result<Self::Value, E>
216    where
217        E: DeError,
218    {
219        self.visit_f64(v as f64)
220    }
221    fn visit_i16<E>(self, v: i16) -> Result<Self::Value, E>
222    where
223        E: DeError,
224    {
225        self.visit_f64(v as f64)
226    }
227    fn visit_i32<E>(self, v: i32) -> Result<Self::Value, E>
228    where
229        E: DeError,
230    {
231        self.visit_f64(v as f64)
232    }
233    fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
234    where
235        E: DeError,
236    {
237        self.visit_f64(v.to_f64().ok_or_else(|| {
238            DeError::custom(format!(
239                "i64 value {v} is too large to fit into f64"
240            ))
241        })?)
242    }
243    fn visit_u8<E>(self, v: u8) -> Result<Self::Value, E>
244    where
245        E: DeError,
246    {
247        self.visit_f64(v as f64)
248    }
249    fn visit_u16<E>(self, v: u16) -> Result<Self::Value, E>
250    where
251        E: DeError,
252    {
253        self.visit_f64(v as f64)
254    }
255    fn visit_u32<E>(self, v: u32) -> Result<Self::Value, E>
256    where
257        E: DeError,
258    {
259        self.visit_f64(v as f64)
260    }
261    fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
262    where
263        E: DeError,
264    {
265        self.visit_f64(v.to_f64().ok_or_else(|| {
266            DeError::custom(format!(
267                "u64 value {v} is too large to fit into f64"
268            ))
269        })?)
270    }
271    fn visit_f32<E>(self, v: f32) -> Result<Self::Value, E>
272    where
273        E: DeError,
274    {
275        self.visit_f64(v as f64)
276    }
277    fn visit_i128<E>(self, v: i128) -> Result<Self::Value, E>
278    where
279        E: DeError,
280    {
281        self.visit_f64(v.to_f64().ok_or_else(|| {
282            DeError::custom(format!(
283                "i128 value {v} is too large to fit into f64"
284            ))
285        })?)
286    }
287    fn visit_u128<E>(self, v: u128) -> Result<Self::Value, E>
288    where
289        E: DeError,
290    {
291        self.visit_f64(v.to_f64().ok_or_else(|| {
292            DeError::custom(format!(
293                "u128 value {v} is too large to fit into f64"
294            ))
295        })?)
296    }
297
298    /// mapping for [tag?, [core_lib_type_id, core_value]]
299    fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
300    where
301        A: serde::de::SeqAccess<'de>,
302    {
303        Ok(Value::Core(
304            self.cast::<CoreValueWithClassification>().visit_seq(seq)?,
305        ))
306    }
307
308    fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
309    where
310        A: MapAccess<'de>,
311    {
312        let mut classification = ValueClassification::new_unclassified();
313
314        while let Some(key) = map.next_key::<String>()? {
315            match TagMarker::from_str(&key).map_err(|_| {
316                de::Error::unknown_variant(&key, TagMarker::VARIANTS)
317            })? {
318                // Not relevant at this level.
319                TagMarker::Hint => {
320                    let _: serde_json::Value = map.next_value()?;
321                }
322
323                // Get the classification first if it exists.
324                TagMarker::Classification => {
325                    classification = map
326                        .next_value_seed(self.cast::<ValueClassification>())?;
327
328                    // Resolve native value based on entity classification.
329                    if let Some(entity_type) = &classification.entity_type
330                        && let Some(deserialize_fn) =
331                            entity_type.entity_definition().deserialize_from_dif
332                    {
333                        // The next key must be "v".
334                        let key =
335                            map.next_key::<String>()?.ok_or_else(|| {
336                                DeError::custom(
337                                    "Expected key 'v' not found in map",
338                                )
339                            })?;
340
341                        if key != TagMarker::Value.as_ref() {
342                            return Err(DeError::custom(format!(
343                                "Expected key 'v' not found in map, found key '{key}' instead"
344                            )));
345                        }
346
347                        // Deserialize via the entity type deserialize function.
348                        let value = map.next_value_seed(DynSeed {
349                            f: deserialize_fn,
350                            ctx: self.ctx,
351                        })?;
352
353                        return Ok(value);
354                    }
355                }
356
357                // Normal, non-native core value.
358                TagMarker::Value => {
359                    let mut value = map.next_value_seed(
360                        self.cast::<CoreValueWithClassification>(),
361                    )?;
362
363                    value.classification =
364                        value.classification.merge(classification);
365
366                    return Ok(Value::Core(value));
367                }
368                TagMarker::Tag => {
369                    return Err(DeError::custom("Unexpected Tag here"));
370                }
371            }
372        }
373
374        Err(DeError::custom(
375            "Expected either classification or value key in map",
376        ))
377    }
378}
379
380#[cfg(test)]
381mod tests {
382    use super::*;
383    use crate::{
384        libs::core::{
385            core_lib_id::CoreLibIdIndex,
386            type_id::{CoreLibBaseTypeId, CoreLibVariantTypeId},
387        },
388        runtime::cache::{
389            shared_references_cache::SharedReferencesCache,
390            shared_values_cache::SharedValuesCache,
391        },
392        values::{
393            core_value::CoreValue,
394            core_values::{
395                decimal::typed_decimal::{DecimalTypeVariant, TypedDecimal},
396                endpoint::Endpoint,
397                instant::Instant,
398                integer::{Integer, typed_integer::IntegerTypeVariant},
399                map::Map,
400            },
401            value_container::ValueContainer,
402        },
403    };
404    use core::{cell::RefCell, str::FromStr};
405    use test_case::test_case;
406
407    #[test]
408    fn endpoint_serialization() {
409        let endpoint = Endpoint::from_str("@jonas").unwrap();
410        let value = Value::new(CoreValue::Endpoint(endpoint.clone()));
411        let shared_values_cache = RefCell::new(SharedValuesCache::default());
412        let shared_references_cache =
413            RefCell::new(SharedReferencesCache::default());
414        let mut context =
415            SerdeContext::new(&shared_values_cache, &shared_references_cache);
416        let serialized = context.serialize_to_json(&value);
417        assert_eq!(
418            serialized,
419            format!(
420                r#"[{},"{}"]"#,
421                CoreLibIdIndex::from(CoreLibTypeId::Base(
422                    CoreLibBaseTypeId::Endpoint
423                )),
424                endpoint
425            )
426        );
427    }
428
429    #[test]
430    fn serialize_map() {
431        let shared_values_cache = RefCell::new(SharedValuesCache::default());
432        let shared_references_cache =
433            RefCell::new(SharedReferencesCache::default());
434        let mut context =
435            SerdeContext::new(&shared_values_cache, &shared_references_cache);
436
437        // { endpoint: "@jonas" } -> [<map-idx>, ["endpoint", [<endpoint-idx>, "@jonas"] ]]
438        let value = Value::from(CoreValue::Map(Map::new_structural(vec![(
439            "endpoint".into(),
440            ValueContainer::Local(Value::from(
441                Endpoint::from_str("@jonas").unwrap(),
442            )),
443        )])));
444        let serialized = context.serialize_to_json(&value);
445        assert_eq!(
446            serialized,
447            format!(
448                r#"[{},[["endpoint",[{},"@jonas"]]]]"#,
449                CoreLibIdIndex::from(CoreLibTypeId::Base(
450                    CoreLibBaseTypeId::Map
451                )),
452                CoreLibIdIndex::from(CoreLibTypeId::Base(
453                    CoreLibBaseTypeId::Endpoint
454                ))
455            )
456        );
457    }
458
459    #[test]
460    fn default_representation() {
461        let shared_values_cache = RefCell::new(SharedValuesCache::default());
462        let shared_references_cache =
463            RefCell::new(SharedReferencesCache::default());
464        let mut context =
465            SerdeContext::new(&shared_values_cache, &shared_references_cache);
466
467        // text
468        let value = Value::from(CoreValue::Text("Hello, world!".into()));
469        let serialized = context.serialize_to_json(&value);
470        assert_eq!(serialized, r#""Hello, world!""#);
471
472        // decimal f64
473        let value = Value::from(CoreValue::TypedDecimal(TypedDecimal::F64(
474            5.14f64.into(),
475        )));
476        let serialized = context.serialize_to_json(&value);
477        assert_eq!(serialized, r#"5.14"#);
478
479        // boolean
480        let value = Value::from(CoreValue::Boolean(true.into()));
481        let serialized = context.serialize_to_json(&value);
482        assert_eq!(serialized, r#"true"#);
483    }
484
485    #[test]
486    fn non_default_representation() {
487        let shared_values_cache = RefCell::new(SharedValuesCache::default());
488        let shared_references_cache =
489            RefCell::new(SharedReferencesCache::default());
490        let mut context =
491            SerdeContext::new(&shared_values_cache, &shared_references_cache);
492
493        // f32
494        let value = Value::from(CoreValue::TypedDecimal(TypedDecimal::F32(
495            5.14f32.into(),
496        )));
497        let serialized = context.serialize_to_json(&value);
498
499        assert_eq!(
500            serialized,
501            format!(
502                r#"[{},5.14]"#,
503                CoreLibIdIndex::from(CoreLibTypeId::Variant(
504                    CoreLibVariantTypeId::Decimal(DecimalTypeVariant::F32)
505                ))
506            )
507        );
508
509        // integer
510        let value = Value::from(CoreValue::Integer(Integer::new(42)));
511        let serialized = context.serialize_to_json(&value);
512        assert_eq!(
513            serialized,
514            format!(
515                r#"[{},"42"]"#,
516                CoreLibIdIndex::from(CoreLibTypeId::Base(
517                    CoreLibBaseTypeId::Integer
518                ))
519            )
520        );
521
522        // typed integer
523        let value = Value::from(CoreValue::TypedInteger(42u8.into()));
524        let serialized = context.serialize_to_json(&value);
525        assert_eq!(
526            serialized,
527            format!(
528                r#"[{},42]"#,
529                CoreLibIdIndex::from(CoreLibTypeId::Variant(
530                    CoreLibVariantTypeId::Integer(IntegerTypeVariant::U8)
531                ))
532            )
533        );
534    }
535
536    #[test_case(
537        CoreValue::Text("Hello, world!".into()) ; "text"
538    )]
539    #[test_case(
540        CoreValue::TypedDecimal(TypedDecimal::F32(5.14f32.into())) ; "decimal f32"
541    )]
542    #[test_case(
543        CoreValue::TypedDecimal(TypedDecimal::F64(f64::NAN.into())) ; "nan f64"
544    )]
545    #[test_case(
546        CoreValue::TypedDecimal(TypedDecimal::F32(f32::NAN.into())) ; "nan f32"
547    )]
548    #[test_case(
549        CoreValue::TypedDecimal(TypedDecimal::F32(f32::INFINITY.into())) ; "inf f32"
550    )]
551    #[test_case(
552        CoreValue::TypedDecimal(TypedDecimal::F64(f64::INFINITY.into())) ; "inf f64"
553    )]
554    #[test_case(
555        CoreValue::TypedDecimal(TypedDecimal::F64(5.14f64.into())) ; "decimal f64"
556    )]
557    #[test_case(
558        CoreValue::Boolean(true.into()) ; "boolean"
559    )]
560    #[test_case(
561        CoreValue::TypedInteger(42u8.into()) ; "typed integer u8"
562    )]
563    #[test_case(
564        CoreValue::Endpoint(Endpoint::from_str("@jonas").unwrap()) ; "endpoint"
565    )]
566    #[test_case(
567        CoreValue::Map(Map::new_structural(vec![(
568            "endpoint".into(),
569            ValueContainer::Local(Value::from(Endpoint::from_str("@jonas").unwrap())),
570        )])) ; "map with string keys"
571    )]
572    #[test_case(
573        CoreValue::Null ; "null"
574    )]
575    #[test_case(
576        CoreValue::Integer(Integer::new(42)) ; "base integer"
577    )]
578    #[test_case(
579        CoreValue::TypedInteger((-42i8).into()) ; "typed integer i8"
580    )]
581    #[test_case(
582        CoreValue::TypedInteger(42u16.into()) ; "typed integer u16"
583    )]
584    #[test_case(
585        CoreValue::TypedInteger(42u32.into()) ; "typed integer u32"
586    )]
587    #[test_case(
588        CoreValue::TypedInteger(42u64.into()) ; "typed integer u64"
589    )]
590    #[test_case(
591        CoreValue::TypedInteger(42u128.into()) ; "typed integer u128"
592    )]
593    #[test_case(
594        CoreValue::TypedDecimal(TypedDecimal::F64(f64::NEG_INFINITY.into())) ; "negative inf f64"
595    )]
596    #[test_case(
597        CoreValue::TypedDecimal(TypedDecimal::F32(f32::NEG_INFINITY.into())) ; "negative inf f32"
598    )]
599    #[test_case(
600        CoreValue::Instant(Instant::now()) ; "instant"
601    )]
602    fn roundtrip_no_custom_type(value: CoreValue) {
603        let shared_values_cache = RefCell::new(SharedValuesCache::default());
604        let shared_references_cache =
605            RefCell::new(SharedReferencesCache::default());
606        let mut context =
607            SerdeContext::new(&shared_values_cache, &shared_references_cache);
608
609        let value = Value::from(value);
610        let serialized = context.serialize_to_json(&value);
611        let deserialized: Value =
612            context.try_deserialize_from_json(&serialized).unwrap();
613        assert_eq!(deserialized, value);
614    }
615}