1use crate::dif::r#type::{DIFTypeContainer, DIFTypeDefinition};
2use crate::dif::value::{DIFReferenceNotFoundError, DIFValueContainer};
3use crate::libs::core::{CoreLibPointerId, get_core_lib_type};
4use crate::runtime::memory::Memory;
5use crate::types::structural_type_definition::StructuralTypeDefinition;
6use crate::values::core_value::CoreValue;
7use crate::values::core_values::decimal::typed_decimal::{
8 DecimalTypeVariant, TypedDecimal,
9};
10use crate::values::value::Value;
11use crate::values::value_container::ValueContainer;
12use indexmap::IndexMap;
13use ordered_float::OrderedFloat;
14use serde::de::{MapAccess, SeqAccess, Visitor};
15use serde::ser::{SerializeMap, SerializeSeq};
16use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
17use std::cell::RefCell;
18use std::fmt;
19
20#[derive(Clone, Debug, PartialEq)]
21pub enum DIFValueRepresentation {
22 Null,
23 Boolean(bool),
25 String(String),
27 Number(f64),
29 Array(Vec<DIFValueContainer>),
31 Map(Vec<(DIFValueContainer, DIFValueContainer)>),
33 Object(Vec<(String, DIFValueContainer)>),
35}
36
37#[derive(Clone, Debug, PartialEq)]
38pub enum DIFTypeRepresentation {
39 Null,
40 Boolean(bool),
42 String(String),
44 Number(f64),
46 Array(Vec<DIFTypeContainer>),
48 Map(Vec<(DIFTypeContainer, DIFTypeContainer)>),
50 Object(Vec<(String, DIFTypeContainer)>),
52}
53
54impl DIFValueRepresentation {
55 pub fn to_default_value(
58 self,
59 memory: &RefCell<Memory>,
60 ) -> Result<Value, DIFReferenceNotFoundError> {
61 Ok(match self {
62 DIFValueRepresentation::Null => Value::null(),
63 DIFValueRepresentation::String(str) => Value {
64 actual_type: Box::new(get_core_lib_type(
65 CoreLibPointerId::Text,
66 )),
67 inner: CoreValue::Text(str.into()),
68 },
69 DIFValueRepresentation::Boolean(b) => Value {
70 actual_type: Box::new(get_core_lib_type(
71 CoreLibPointerId::Boolean,
72 )),
73 inner: CoreValue::Boolean(b.into()),
74 },
75 DIFValueRepresentation::Number(n) => Value {
76 actual_type: Box::new(get_core_lib_type(
77 CoreLibPointerId::Decimal(Some(DecimalTypeVariant::F64)),
78 )),
79 inner: CoreValue::TypedDecimal(TypedDecimal::F64(
80 OrderedFloat::from(n),
81 )),
82 },
83 DIFValueRepresentation::Array(array) => Value {
84 actual_type: Box::new(get_core_lib_type(
85 CoreLibPointerId::List,
86 )),
87 inner: CoreValue::List(
88 array
89 .into_iter()
90 .map(|v| v.to_value_container(memory))
91 .collect::<Result<Vec<ValueContainer>, _>>()?
92 .into(),
93 ),
94 },
95 DIFValueRepresentation::Object(object) => {
96 let mut map = IndexMap::new();
97 for (k, v) in object {
98 map.insert(
99 ValueContainer::Value(Value::from(k)),
100 v.to_value_container(memory)?,
101 );
102 }
103 Value {
104 actual_type: Box::new(get_core_lib_type(
105 CoreLibPointerId::Map,
106 )),
107 inner: CoreValue::Map(map.into()),
108 }
109 }
110 DIFValueRepresentation::Map(map) => {
111 let mut core_map = IndexMap::new();
112 for (k, v) in map {
113 core_map.insert(
114 k.to_value_container(memory)?,
115 v.to_value_container(memory)?,
116 );
117 }
118 Value {
119 actual_type: Box::new(get_core_lib_type(
120 CoreLibPointerId::Map,
121 )),
122 inner: CoreValue::Map(core_map.into()),
123 }
124 }
125 _ => {
126 todo!("#388 Other DIFRepresentationValue variants not supported yet")
127 }
128 })
129 }
130
131 pub fn to_value_with_type(
134 self,
135 type_container: &DIFTypeContainer,
136 memory: &RefCell<Memory>,
137 ) -> Result<Value, DIFReferenceNotFoundError> {
138 Ok(match r#type_container {
139 DIFTypeContainer::Reference(r) => {
140 if let Ok(core_lib_ptr_id) = CoreLibPointerId::try_from(r) {
141 match core_lib_ptr_id {
142 CoreLibPointerId::Map
145 if let DIFValueRepresentation::Object(object) =
146 self =>
147 {
148 let mut core_map: IndexMap<
149 ValueContainer,
150 ValueContainer,
151 > = IndexMap::new();
152 for (k, v) in object {
153 core_map.insert(
154 Value::from(k).into(),
155 v.to_value_container(memory)?,
156 );
157 }
158 Value::from(CoreValue::Map(core_map.into()))
159 }
160 _ => self.to_default_value(memory)?,
162 }
163 } else {
164 todo!("#389 Handle non-core library type references")
165 }
166 }
167 DIFTypeContainer::Type(dif_type) => {
168 match &dif_type.type_definition {
169 DIFTypeDefinition::Structural(s) => {
170 todo!("#390 Structural type conversion not supported yet")
171 }
172 DIFTypeDefinition::Unit => Value {
173 actual_type: Box::new(get_core_lib_type(
174 CoreLibPointerId::Null,
175 )),
176 inner: CoreValue::Null,
177 },
178 _ => todo!("#391 Other type definitions not supported yet"),
179 }
180 }
181 })
182 }
183}
184
185#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
186#[serde(untagged)]
187pub enum DeserializeMapOrArray<T> {
188 MapEntry(T, T),
189 ArrayEntry(T),
190}
191
192impl DIFTypeRepresentation {
193 pub fn from_structural_type_definition(
194 struct_def: &StructuralTypeDefinition,
195 memory: &RefCell<Memory>,
196 ) -> Self {
197 match struct_def {
198 StructuralTypeDefinition::Null => DIFTypeRepresentation::Null,
199 StructuralTypeDefinition::Boolean(b) => {
200 DIFTypeRepresentation::Boolean(b.as_bool())
201 }
202 StructuralTypeDefinition::Integer(i) => {
203 DIFTypeRepresentation::Number(i.as_i128().unwrap() as f64)
205 }
206 StructuralTypeDefinition::TypedInteger(i) => {
207 DIFTypeRepresentation::Number(i.as_i128().unwrap() as f64)
208 }
209 StructuralTypeDefinition::Decimal(d) => {
210 DIFTypeRepresentation::Number(d.into_f64())
211 }
212 StructuralTypeDefinition::TypedDecimal(d) => {
213 DIFTypeRepresentation::Number(d.as_f64())
214 }
215 StructuralTypeDefinition::Text(t) => {
216 DIFTypeRepresentation::String(t.0.clone())
217 }
218 StructuralTypeDefinition::Endpoint(endpoint) => {
219 DIFTypeRepresentation::String(endpoint.to_string())
220 }
221 StructuralTypeDefinition::List(arr) => {
222 DIFTypeRepresentation::Array(
223 arr.iter()
224 .map(|v| {
225 DIFTypeContainer::from_type_container(v, memory)
226 })
227 .collect(),
228 )
229 }
230 StructuralTypeDefinition::Map(fields) => {
231 DIFTypeRepresentation::Map(
232 fields
233 .iter()
234 .map(|(k, v)| {
235 (
236 DIFTypeContainer::from_type_container(
237 k, memory,
238 ),
239 DIFTypeContainer::from_type_container(
240 v, memory,
241 ),
242 )
243 })
244 .collect(),
245 )
246 }
247 }
248 }
249}
250
251impl Serialize for DIFValueRepresentation {
252 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
253 where
254 S: Serializer,
255 {
256 match self {
257 DIFValueRepresentation::Null => serializer.serialize_unit(),
258 DIFValueRepresentation::Boolean(b) => serializer.serialize_bool(*b),
259 DIFValueRepresentation::String(s) => serializer.serialize_str(s),
260 DIFValueRepresentation::Number(f) => serializer.serialize_f64(*f),
261 DIFValueRepresentation::Array(vec) => vec.serialize(serializer),
262 DIFValueRepresentation::Map(entries) => {
263 let mut seq = serializer.serialize_seq(Some(entries.len()))?;
264 for (k, v) in entries {
265 seq.serialize_element(&vec![k, v])?;
266 }
267 seq.end()
268 }
269 DIFValueRepresentation::Object(fields) => {
270 let mut map = serializer.serialize_map(Some(fields.len()))?;
271 for (k, v) in fields {
272 map.serialize_entry(k, v)?;
273 }
274 map.end()
275 }
276 }
277 }
278}
279
280impl<'de> Deserialize<'de> for DIFValueRepresentation {
281 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
282 where
283 D: Deserializer<'de>,
284 {
285 struct DIFCoreValueVisitor;
286
287 impl<'de> Visitor<'de> for DIFCoreValueVisitor {
288 type Value = DIFValueRepresentation;
289
290 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
291 formatter.write_str("a valid DIFCoreValue")
292 }
293
294 fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E> {
295 Ok(DIFValueRepresentation::Boolean(value))
296 }
297
298 fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E> {
299 Ok(DIFValueRepresentation::Number(value as f64))
300 }
301
302 fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E> {
303 Ok(DIFValueRepresentation::Number(value as f64))
305 }
306
307 fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E> {
308 Ok(DIFValueRepresentation::Number(value))
309 }
310
311 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
312 where
313 E: de::Error,
314 {
315 Ok(DIFValueRepresentation::String(value.to_owned()))
316 }
317
318 fn visit_string<E>(self, value: String) -> Result<Self::Value, E> {
319 Ok(DIFValueRepresentation::String(value))
320 }
321
322 fn visit_none<E>(self) -> Result<Self::Value, E> {
323 Ok(DIFValueRepresentation::Null)
324 }
325
326 fn visit_unit<E>(self) -> Result<Self::Value, E> {
327 Ok(DIFValueRepresentation::Null)
328 }
329
330 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
332 where
333 A: SeqAccess<'de>,
334 {
335 let first_entry = seq
336 .next_element::<DeserializeMapOrArray<DIFValueContainer>>(
337 )?;
338 match first_entry {
339 Some(DeserializeMapOrArray::ArrayEntry(first)) => {
340 let mut elements = vec![first];
341 while let Some(elem) =
342 seq.next_element::<DIFValueContainer>()?
343 {
344 elements.push(elem);
345 }
346 Ok(DIFValueRepresentation::Array(elements))
347 }
348 Some(DeserializeMapOrArray::MapEntry(k, v)) => {
349 let mut elements = vec![(k, v)];
350 while let Some((k, v)) = seq.next_element::<(
351 DIFValueContainer,
352 DIFValueContainer,
353 )>(
354 )? {
355 elements.push((k, v));
356 }
357 Ok(DIFValueRepresentation::Map(elements))
358 }
359 None => Ok(DIFValueRepresentation::Array(vec![])), }
361 }
362
363 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
365 where
366 A: MapAccess<'de>,
367 {
368 let mut entries = Vec::new();
369 while let Some((k, v)) = map.next_entry()? {
370 entries.push((k, v));
371 }
372 Ok(DIFValueRepresentation::Object(entries))
373 }
374 }
375
376 deserializer.deserialize_any(DIFCoreValueVisitor)
377 }
378}
379
380impl Serialize for DIFTypeRepresentation {
381 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
382 where
383 S: Serializer,
384 {
385 match self {
386 DIFTypeRepresentation::Null => serializer.serialize_unit(),
387 DIFTypeRepresentation::Boolean(b) => serializer.serialize_bool(*b),
388 DIFTypeRepresentation::String(s) => serializer.serialize_str(s),
389 DIFTypeRepresentation::Number(f) => serializer.serialize_f64(*f),
390 DIFTypeRepresentation::Array(vec) => vec.serialize(serializer),
391 DIFTypeRepresentation::Map(entries) => {
392 let mut seq = serializer.serialize_seq(Some(entries.len()))?;
393 for (k, v) in entries {
394 seq.serialize_element(&vec![k, v])?;
395 }
396 seq.end()
397 }
398 DIFTypeRepresentation::Object(fields) => {
399 let mut map = serializer.serialize_map(Some(fields.len()))?;
400 for (k, v) in fields {
401 map.serialize_entry(k, v)?;
402 }
403 map.end()
404 }
405 }
406 }
407}
408
409impl<'de> Deserialize<'de> for DIFTypeRepresentation {
410 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
411 where
412 D: Deserializer<'de>,
413 {
414 struct DIFCoreValueVisitor;
415
416 impl<'de> Visitor<'de> for DIFCoreValueVisitor {
417 type Value = DIFTypeRepresentation;
418
419 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
420 formatter.write_str("a valid DIFCoreValue")
421 }
422
423 fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E> {
424 Ok(DIFTypeRepresentation::Boolean(value))
425 }
426
427 fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E> {
428 Ok(DIFTypeRepresentation::Number(value as f64))
429 }
430
431 fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E> {
432 Ok(DIFTypeRepresentation::Number(value as f64))
434 }
435
436 fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E> {
437 Ok(DIFTypeRepresentation::Number(value))
438 }
439
440 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
441 where
442 E: de::Error,
443 {
444 Ok(DIFTypeRepresentation::String(value.to_owned()))
445 }
446
447 fn visit_string<E>(self, value: String) -> Result<Self::Value, E> {
448 Ok(DIFTypeRepresentation::String(value))
449 }
450
451 fn visit_none<E>(self) -> Result<Self::Value, E> {
452 Ok(DIFTypeRepresentation::Null)
453 }
454
455 fn visit_unit<E>(self) -> Result<Self::Value, E> {
456 Ok(DIFTypeRepresentation::Null)
457 }
458
459 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
461 where
462 A: SeqAccess<'de>,
463 {
464 let first_entry = seq
465 .next_element::<DeserializeMapOrArray<DIFTypeContainer>>(
466 )?;
467 match first_entry {
468 Some(DeserializeMapOrArray::ArrayEntry(first)) => {
469 let mut elements = vec![first];
470 while let Some(elem) =
471 seq.next_element::<DIFTypeContainer>()?
472 {
473 elements.push(elem);
474 }
475 Ok(DIFTypeRepresentation::Array(elements))
476 }
477 Some(DeserializeMapOrArray::MapEntry(k, v)) => {
478 let mut elements = vec![(k, v)];
479 while let Some((k, v)) = seq.next_element::<(
480 DIFTypeContainer,
481 DIFTypeContainer,
482 )>(
483 )? {
484 elements.push((k, v));
485 }
486 Ok(DIFTypeRepresentation::Map(elements))
487 }
488 None => Ok(DIFTypeRepresentation::Array(vec![])), }
490 }
491
492 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
494 where
495 A: MapAccess<'de>,
496 {
497 let mut entries = Vec::new();
498 while let Some((k, v)) = map.next_entry()? {
499 entries.push((k, v));
500 }
501 Ok(DIFTypeRepresentation::Object(entries))
502 }
503 }
504
505 deserializer.deserialize_any(DIFCoreValueVisitor)
506 }
507}