s2json_core/
value_impl.rs

1use crate::*;
2use alloc::{
3    string::{String, ToString},
4    vec::Vec,
5};
6use libm::round;
7
8// PrimitiveValue
9impl PrimitiveValue {
10    /// Returns true if the value is null
11    pub fn is_null(&self) -> bool {
12        matches!(self, PrimitiveValue::Null)
13    }
14
15    /// Converts a primitive value to a string
16    pub fn to_string(&self) -> Option<String> {
17        match self {
18            PrimitiveValue::String(v) => Some(v.clone()),
19            _ => None,
20        }
21    }
22
23    /// Converts a primitive value to a u64
24    pub fn to_u64(&self) -> Option<u64> {
25        match self {
26            PrimitiveValue::U64(v) => Some(*v),
27            PrimitiveValue::I64(v) => Some(*v as u64),
28            PrimitiveValue::F64(v) => Some(round(*v) as u64),
29            PrimitiveValue::F32(v) => Some(round((*v).into()) as u64),
30            _ => None,
31        }
32    }
33
34    /// Converts a primitive value to a i64
35    pub fn to_i64(&self) -> Option<i64> {
36        match self {
37            PrimitiveValue::U64(v) => Some(*v as i64),
38            PrimitiveValue::I64(v) => Some(*v),
39            PrimitiveValue::F64(v) => Some(round(*v) as i64),
40            PrimitiveValue::F32(v) => Some(round((*v).into()) as i64),
41            _ => None,
42        }
43    }
44
45    /// Converts a primitive value to a f64
46    pub fn to_f64(&self) -> Option<f64> {
47        match self {
48            PrimitiveValue::U64(v) => Some(*v as f64),
49            PrimitiveValue::I64(v) => Some(*v as f64),
50            PrimitiveValue::F64(v) => Some(*v),
51            PrimitiveValue::F32(v) => Some(*v as f64),
52            _ => None,
53        }
54    }
55
56    /// Converts a primitive value to a f32
57    pub fn to_f32(&self) -> Option<f32> {
58        match self {
59            PrimitiveValue::U64(v) => Some(*v as f32),
60            PrimitiveValue::I64(v) => Some(*v as f32),
61            PrimitiveValue::F64(v) => Some(*v as f32),
62            PrimitiveValue::F32(v) => Some(*v),
63            _ => None,
64        }
65    }
66
67    /// Converts a primitive value to a bool
68    pub fn to_bool(&self) -> Option<bool> {
69        match self {
70            PrimitiveValue::Bool(v) => Some(*v),
71            _ => None,
72        }
73    }
74}
75impl From<&str> for PrimitiveValue {
76    fn from(s: &str) -> Self {
77        PrimitiveValue::String(s.to_string())
78    }
79}
80impl From<String> for PrimitiveValue {
81    fn from(s: String) -> Self {
82        PrimitiveValue::String(s)
83    }
84}
85impl From<u64> for PrimitiveValue {
86    fn from(v: u64) -> Self {
87        PrimitiveValue::U64(v)
88    }
89}
90impl From<i64> for PrimitiveValue {
91    fn from(v: i64) -> Self {
92        PrimitiveValue::I64(v)
93    }
94}
95impl From<f32> for PrimitiveValue {
96    fn from(v: f32) -> Self {
97        PrimitiveValue::F32(v)
98    }
99}
100impl From<f64> for PrimitiveValue {
101    fn from(v: f64) -> Self {
102        PrimitiveValue::F64(v)
103    }
104}
105impl From<bool> for PrimitiveValue {
106    fn from(v: bool) -> Self {
107        PrimitiveValue::Bool(v)
108    }
109}
110impl From<()> for PrimitiveValue {
111    fn from(_: ()) -> Self {
112        PrimitiveValue::Null
113    }
114}
115impl<T> From<Option<T>> for PrimitiveValue
116where
117    T: Into<PrimitiveValue>,
118{
119    fn from(v: Option<T>) -> Self {
120        match v {
121            Some(v) => v.into(),
122            None => PrimitiveValue::Null,
123        }
124    }
125}
126impl From<&PrimitiveValue> for JSONValue {
127    fn from(v: &PrimitiveValue) -> Self {
128        JSONValue::Primitive(v.clone())
129    }
130}
131impl From<&JSONValue> for PrimitiveValue {
132    fn from(v: &JSONValue) -> Self {
133        match v {
134            JSONValue::Primitive(v) => v.clone(),
135            // DROPS VALUES THAT ARE NOT PRIMITIVES
136            _ => PrimitiveValue::Null,
137        }
138    }
139}
140
141// ValuePrimitiveType
142impl ValuePrimitiveType {
143    /// Returns the value as a primitive
144    pub fn to_prim(&self) -> Option<&PrimitiveValue> {
145        match self {
146            ValuePrimitiveType::Primitive(v) => Some(v),
147            _ => None,
148        }
149    }
150
151    /// Returns the value as a nested object
152    pub fn to_nested(&self) -> Option<&ValuePrimitive> {
153        match self {
154            ValuePrimitiveType::NestedPrimitive(v) => Some(v),
155            _ => None,
156        }
157    }
158}
159impl From<&str> for ValuePrimitiveType {
160    fn from(s: &str) -> Self {
161        ValuePrimitiveType::Primitive(PrimitiveValue::String(s.to_string()))
162    }
163}
164impl From<String> for ValuePrimitiveType {
165    fn from(s: String) -> Self {
166        ValuePrimitiveType::Primitive(PrimitiveValue::String(s))
167    }
168}
169impl From<u64> for ValuePrimitiveType {
170    fn from(v: u64) -> Self {
171        ValuePrimitiveType::Primitive(PrimitiveValue::U64(v))
172    }
173}
174impl From<i64> for ValuePrimitiveType {
175    fn from(v: i64) -> Self {
176        ValuePrimitiveType::Primitive(PrimitiveValue::I64(v))
177    }
178}
179impl From<f32> for ValuePrimitiveType {
180    fn from(v: f32) -> Self {
181        ValuePrimitiveType::Primitive(PrimitiveValue::F32(v))
182    }
183}
184impl From<f64> for ValuePrimitiveType {
185    fn from(v: f64) -> Self {
186        ValuePrimitiveType::Primitive(PrimitiveValue::F64(v))
187    }
188}
189impl From<bool> for ValuePrimitiveType {
190    fn from(v: bool) -> Self {
191        ValuePrimitiveType::Primitive(PrimitiveValue::Bool(v))
192    }
193}
194impl From<()> for ValuePrimitiveType {
195    fn from(_: ()) -> Self {
196        ValuePrimitiveType::Primitive(PrimitiveValue::Null)
197    }
198}
199impl From<PrimitiveValue> for ValuePrimitiveType {
200    fn from(v: PrimitiveValue) -> Self {
201        ValuePrimitiveType::Primitive(v)
202    }
203}
204impl From<ValuePrimitive> for ValuePrimitiveType {
205    fn from(v: ValuePrimitive) -> Self {
206        ValuePrimitiveType::NestedPrimitive(v)
207    }
208}
209impl<T> From<Option<T>> for ValuePrimitiveType
210where
211    T: Into<ValuePrimitiveType>,
212{
213    fn from(v: Option<T>) -> Self {
214        match v {
215            Some(v) => v.into(),
216            None => ValuePrimitiveType::Primitive(PrimitiveValue::Null),
217        }
218    }
219}
220impl From<&ValuePrimitiveType> for JSONValue {
221    fn from(v: &ValuePrimitiveType) -> Self {
222        match v {
223            ValuePrimitiveType::Primitive(v) => JSONValue::Primitive(v.clone()),
224            ValuePrimitiveType::NestedPrimitive(v) => {
225                let mut map = Map::<String, JSONValue>::new();
226                for (k, v) in v.iter() {
227                    map.insert(k.clone(), v.into());
228                }
229                JSONValue::Object(map)
230            }
231        }
232    }
233}
234impl From<&JSONValue> for ValuePrimitiveType {
235    fn from(v: &JSONValue) -> Self {
236        match v {
237            JSONValue::Primitive(v) => ValuePrimitiveType::Primitive(v.clone()),
238            JSONValue::Object(v) => {
239                let mut map = ValuePrimitive::new();
240                for (k, v) in v.iter() {
241                    map.insert(k.clone(), v.into());
242                }
243                ValuePrimitiveType::NestedPrimitive(map)
244            }
245            // DROPS ALL ARRAY DATA AS IT IS NOT SUPPORTED INSIDE VALUE PRIMITIVES
246            _ => ValuePrimitiveType::Primitive(PrimitiveValue::Null),
247        }
248    }
249}
250
251// ValueType
252impl Default for ValueType {
253    fn default() -> Self {
254        ValueType::Primitive(PrimitiveValue::Null)
255    }
256}
257impl ValueType {
258    /// Returns the value as a primitive
259    pub fn to_prim(&self) -> Option<&PrimitiveValue> {
260        match self {
261            ValueType::Primitive(v) => Some(v),
262            _ => None,
263        }
264    }
265
266    /// Returns the value as a vector
267    pub fn to_vec(&self) -> Option<&Vec<ValuePrimitiveType>> {
268        match self {
269            ValueType::Array(v) => Some(v),
270            _ => None,
271        }
272    }
273
274    /// Returns the value as a nested object
275    pub fn to_nested(&self) -> Option<&Value> {
276        match self {
277            ValueType::Nested(v) => Some(v),
278            _ => None,
279        }
280    }
281}
282impl From<&str> for ValueType {
283    fn from(s: &str) -> Self {
284        ValueType::Primitive(PrimitiveValue::String(s.to_string()))
285    }
286}
287impl AsRef<str> for ValueType {
288    fn as_ref(&self) -> &str {
289        match self {
290            ValueType::Primitive(PrimitiveValue::String(s)) => s.as_str(),
291            _ => "",
292        }
293    }
294}
295impl From<String> for ValueType {
296    fn from(s: String) -> Self {
297        ValueType::Primitive(PrimitiveValue::String(s))
298    }
299}
300impl From<ValueType> for String {
301    fn from(v: ValueType) -> Self {
302        match v {
303            ValueType::Primitive(PrimitiveValue::String(s)) => s,
304            _ => "".to_string(),
305        }
306    }
307}
308
309// Implement for u8, u16, u32, u64
310macro_rules! impl_from_int {
311    ($($t:ty),*) => {
312        $(
313            impl From<$t> for ValueType {
314                fn from(v: $t) -> Self {
315                    ValueType::Primitive(PrimitiveValue::U64(v as u64))
316                }
317            }
318
319            impl From<ValueType> for $t {
320                fn from(v: ValueType) -> Self {
321                    match v {
322                        ValueType::Primitive(PrimitiveValue::U64(v)) => v as $t,
323                        _ => 0,
324                    }
325                }
326            }
327        )*
328    };
329}
330impl_from_int!(u8, u16, u32, u64, usize);
331// Implement for i8, i16, i32, i64
332macro_rules! impl_from_int {
333    ($($t:ty),*) => {
334        $(
335            impl From<$t> for ValueType {
336                fn from(v: $t) -> Self {
337                    ValueType::Primitive(PrimitiveValue::I64(v as i64))
338                }
339            }
340
341            impl From<ValueType> for $t {
342                fn from(v: ValueType) -> Self {
343                    match v {
344                        ValueType::Primitive(PrimitiveValue::I64(v)) => v as $t,
345                        _ => 0,
346                    }
347                }
348            }
349        )*
350    };
351}
352impl_from_int!(i8, i16, i32, i64, isize);
353impl From<f32> for ValueType {
354    fn from(v: f32) -> Self {
355        ValueType::Primitive(PrimitiveValue::F32(v))
356    }
357}
358impl From<ValueType> for f32 {
359    fn from(v: ValueType) -> Self {
360        match v {
361            ValueType::Primitive(PrimitiveValue::F32(v)) => v,
362            _ => 0.0,
363        }
364    }
365}
366impl From<f64> for ValueType {
367    fn from(v: f64) -> Self {
368        ValueType::Primitive(PrimitiveValue::F64(v))
369    }
370}
371impl From<ValueType> for f64 {
372    fn from(v: ValueType) -> Self {
373        match v {
374            ValueType::Primitive(PrimitiveValue::F64(v)) => v,
375            _ => 0.0,
376        }
377    }
378}
379impl From<bool> for ValueType {
380    fn from(v: bool) -> Self {
381        ValueType::Primitive(PrimitiveValue::Bool(v))
382    }
383}
384impl From<ValueType> for bool {
385    fn from(v: ValueType) -> Self {
386        match v {
387            ValueType::Primitive(PrimitiveValue::Bool(v)) => v,
388            _ => false,
389        }
390    }
391}
392impl From<()> for ValueType {
393    fn from(_: ()) -> Self {
394        ValueType::Primitive(PrimitiveValue::Null)
395    }
396}
397impl From<ValueType> for () {
398    fn from(_: ValueType) -> Self {}
399}
400impl<T> From<Vec<T>> for ValueType
401where
402    T: Into<ValuePrimitiveType>,
403{
404    fn from(v: Vec<T>) -> Self {
405        ValueType::Array(v.into_iter().map(Into::into).collect())
406    }
407}
408impl<T> From<ValueType> for Vec<T>
409where
410    T: From<ValuePrimitiveType>,
411{
412    fn from(v: ValueType) -> Self {
413        match v {
414            ValueType::Array(v) => v.into_iter().map(Into::into).collect(),
415            _ => Vec::new(),
416        }
417    }
418}
419impl From<Value> for ValueType {
420    fn from(v: Value) -> Self {
421        ValueType::Nested(v)
422    }
423}
424impl<T> From<Option<T>> for ValueType
425where
426    T: Into<ValueType>,
427{
428    fn from(v: Option<T>) -> Self {
429        match v {
430            Some(v) => v.into(),
431            None => ValueType::Primitive(PrimitiveValue::Null),
432        }
433    }
434}
435// TODO: Find a simpler methodology for this
436/// This trait is used to ensure that only types that implement From<ValueType> are allowed
437pub trait NotValueType {}
438/// A macro to implement the `NotValueType` trait for multiple types at once.
439macro_rules! impl_not_value_type {
440    ( $( $t:ty ),* ) => {
441        $(
442            impl NotValueType for $t {}
443        )*
444    };
445}
446impl_not_value_type!(
447    u8,
448    u16,
449    u32,
450    u64,
451    usize,
452    i8,
453    i16,
454    i32,
455    i64,
456    isize,
457    f32,
458    f64,
459    String,
460    &str,
461    bool,
462    ()
463);
464impl<T> From<ValueType> for Option<T>
465where
466    T: From<ValueType> + NotValueType, /* This ensures that only types that implement From<ValueType> are allowed */
467{
468    fn from(v: ValueType) -> Self {
469        match v {
470            ValueType::Primitive(PrimitiveValue::Null) => None,
471            _ => Some(v.into()),
472        }
473    }
474}
475// First, implement the `From<ValueType>` trait for `Option<T>` where T is not ValueType.
476// impl<T> From<ValueType> for Option<T>
477// where
478//     T: From<ValueType>,
479// {
480//     fn from(v: ValueType) -> Self {
481//         match v {
482//             ValueType::Primitive(PrimitiveValue::Null) => None,
483//             v => Some(v.into()), // Use the custom Into implementation
484//         }
485//     }
486// }
487impl From<&JSONValue> for ValueType {
488    fn from(v: &JSONValue) -> Self {
489        match v {
490            JSONValue::Primitive(v) => ValueType::Primitive(v.clone()),
491            JSONValue::Array(v) => ValueType::Array(v.iter().map(Into::into).collect()),
492            JSONValue::Object(v) => {
493                let mut res = Value::new();
494                for (k, v) in v.iter() {
495                    res.insert(k.clone(), v.into());
496                }
497                ValueType::Nested(res)
498            }
499        }
500    }
501}
502impl From<&ValueType> for JSONValue {
503    fn from(v: &ValueType) -> Self {
504        match v {
505            ValueType::Primitive(v) => JSONValue::Primitive(v.clone()),
506            ValueType::Array(v) => JSONValue::Array(v.iter().map(Into::into).collect()),
507            ValueType::Nested(v) => {
508                let mut res = Map::<String, JSONValue>::new();
509                for (k, v) in v.iter() {
510                    res.insert(k.clone(), v.into());
511                }
512                JSONValue::Object(res)
513            }
514        }
515    }
516}
517
518impl Default for JSONValue {
519    fn default() -> Self {
520        JSONValue::Primitive(PrimitiveValue::Null)
521    }
522}
523impl JSONValue {
524    /// Returns the value as a primitive
525    pub fn to_prim(&self) -> Option<&PrimitiveValue> {
526        match self {
527            JSONValue::Primitive(v) => Some(v),
528            _ => None,
529        }
530    }
531
532    /// Returns the value as a vector
533    pub fn to_vec(&self) -> Option<&Vec<JSONValue>> {
534        match self {
535            JSONValue::Array(v) => Some(v),
536            _ => None,
537        }
538    }
539
540    /// Returns the value as a nested object
541    pub fn to_nested(&self) -> Option<&Map<String, JSONValue>> {
542        match self {
543            JSONValue::Object(v) => Some(v),
544            _ => None,
545        }
546    }
547}
548
549impl MValueCompatible for JSONProperties {}
550impl From<JSONProperties> for MValue {
551    fn from(json: JSONProperties) -> MValue {
552        let mut res = MValue::new();
553        for (k, v) in json.iter() {
554            res.insert(k.clone(), v.into());
555        }
556        res
557    }
558}
559impl From<MValue> for JSONProperties {
560    fn from(v: MValue) -> JSONProperties {
561        let mut res = JSONProperties::new();
562        for (k, v) in v.iter() {
563            res.insert(k.clone(), v.into());
564        }
565        res
566    }
567}
568
569impl MValueCompatible for MapboxProperties {}
570impl From<MapboxProperties> for MValue {
571    fn from(json: MapboxProperties) -> MValue {
572        let mut res = MValue::new();
573        for (k, v) in json.iter() {
574            res.insert(k.clone(), ValueType::Primitive(v.clone()));
575        }
576        res
577    }
578}
579impl From<MValue> for MapboxProperties {
580    fn from(v: MValue) -> MapboxProperties {
581        let mut res = MapboxProperties::new();
582        // Only copy over primitive values
583        for (k, v) in v.iter() {
584            let value = v.clone();
585            if let Some(p) = value.to_prim() {
586                res.insert(k.clone(), p.clone());
587            }
588        }
589        res
590    }
591}
592
593#[cfg(test)]
594mod tests {
595    use alloc::vec;
596
597    use crate::{MValue, MValueCompatible, VectorPoint};
598
599    use super::*;
600
601    #[test]
602    fn value_default() {
603        let default = ValueType::default();
604        assert_eq!(default, ValueType::Primitive(PrimitiveValue::Null));
605    }
606
607    #[test]
608    fn primitive_value_funcs() {
609        // &str
610        let prim_value: PrimitiveValue = "test".into();
611        assert_eq!(PrimitiveValue::String("test".into()), prim_value);
612        assert_eq!(prim_value.to_u64(), None);
613        assert_eq!(prim_value.to_i64(), None);
614        assert_eq!(prim_value.to_f32(), None);
615        assert_eq!(prim_value.to_f64(), None);
616        assert_eq!(prim_value.to_bool(), None);
617        assert!(!prim_value.is_null());
618        // String
619        let prim_value_str: String = "test".into();
620        let prim_value: PrimitiveValue = prim_value_str.clone().into();
621        assert_eq!(PrimitiveValue::String("test".into()), prim_value);
622        assert_eq!(prim_value.to_string(), Some("test".into()));
623        // u64
624        let prim_value: PrimitiveValue = 1_u64.into();
625        assert_eq!(PrimitiveValue::U64(1), prim_value);
626        assert_eq!(prim_value.to_string(), None);
627        assert_eq!(prim_value.to_u64(), Some(1));
628        assert_eq!(prim_value.to_i64(), Some(1));
629        assert_eq!(prim_value.to_f32(), Some(1.0));
630        assert_eq!(prim_value.to_f64(), Some(1.0));
631        // i64
632        let prim_value: PrimitiveValue = (-1_i64).into();
633        assert_eq!(PrimitiveValue::I64(-1), prim_value);
634        assert_eq!(prim_value.to_u64(), Some(18446744073709551615));
635        assert_eq!(prim_value.to_i64(), Some(-1));
636        assert_eq!(prim_value.to_f32(), Some(-1.0));
637        assert_eq!(prim_value.to_f64(), Some(-1.0));
638        // f32
639        let prim_value: PrimitiveValue = (1.0_f32).into();
640        assert_eq!(PrimitiveValue::F32(1.0), prim_value);
641        assert_eq!(prim_value.to_u64(), Some(1));
642        assert_eq!(prim_value.to_i64(), Some(1));
643        assert_eq!(prim_value.to_f32(), Some(1.0));
644        assert_eq!(prim_value.to_f64(), Some(1.0));
645        // f64
646        let prim_value: PrimitiveValue = (1.0_f64).into();
647        assert_eq!(PrimitiveValue::F64(1.0), prim_value);
648        assert_eq!(prim_value.to_u64(), Some(1));
649        assert_eq!(prim_value.to_i64(), Some(1));
650        assert_eq!(prim_value.to_f32(), Some(1.0));
651        assert_eq!(prim_value.to_f64(), Some(1.0));
652        // bool
653        let prim_value: PrimitiveValue = true.into();
654        assert_eq!(PrimitiveValue::Bool(true), prim_value);
655        assert_eq!(prim_value.to_bool(), Some(true));
656        // ()
657        let prim_value: PrimitiveValue = ().into();
658        assert_eq!(PrimitiveValue::Null, prim_value);
659        assert!(prim_value.is_null());
660        // Option
661        let prim_value: PrimitiveValue = Some(true).into();
662        assert_eq!(PrimitiveValue::Bool(true), prim_value);
663        assert_eq!(prim_value.to_bool(), Some(true));
664        let prim_value: PrimitiveValue = None::<bool>.into();
665        assert_eq!(PrimitiveValue::Null, prim_value);
666        assert!(prim_value.is_null());
667    }
668
669    #[test]
670    fn value_prim_type_funcs() {
671        // &str
672        let prim_value: ValuePrimitiveType = "test".into();
673        assert_eq!(
674            ValuePrimitiveType::Primitive(PrimitiveValue::String("test".into())),
675            prim_value
676        );
677        assert_eq!(prim_value.to_prim(), Some(PrimitiveValue::String("test".into())).as_ref());
678        assert_eq!(prim_value.to_nested(), None);
679        // String
680        let prim_value_str: String = "test".into();
681        let prim_value: ValuePrimitiveType = prim_value_str.clone().into();
682        assert_eq!(
683            ValuePrimitiveType::Primitive(PrimitiveValue::String("test".into())),
684            prim_value
685        );
686        // u64
687        let prim_value: ValuePrimitiveType = 1_u64.into();
688        assert_eq!(ValuePrimitiveType::Primitive(PrimitiveValue::U64(1)), prim_value);
689        // i64
690        let prim_value: ValuePrimitiveType = (-1_i64).into();
691        assert_eq!(ValuePrimitiveType::Primitive(PrimitiveValue::I64(-1)), prim_value);
692        // f32
693        let prim_value: ValuePrimitiveType = (1.0_f32).into();
694        assert_eq!(ValuePrimitiveType::Primitive(PrimitiveValue::F32(1.0)), prim_value);
695        // f64
696        let prim_value: ValuePrimitiveType = (1.0_f64).into();
697        assert_eq!(ValuePrimitiveType::Primitive(PrimitiveValue::F64(1.0)), prim_value);
698        // bool
699        let prim_value: ValuePrimitiveType = true.into();
700        assert_eq!(ValuePrimitiveType::Primitive(PrimitiveValue::Bool(true)), prim_value);
701        // ()
702        let prim_value: ValuePrimitiveType = ().into();
703        assert_eq!(ValuePrimitiveType::Primitive(PrimitiveValue::Null), prim_value);
704
705        // from prim
706        let nested: ValuePrimitiveType = PrimitiveValue::Bool(true).into();
707        assert_eq!(nested.to_prim().unwrap().to_bool(), Some(true));
708
709        // nested
710        let nested: ValuePrimitiveType =
711            ValuePrimitive::from([("a".into(), "b".into()), ("c".into(), 2.0_f32.into())]).into();
712        assert_eq!(nested.to_prim(), None);
713        assert_eq!(
714            nested.to_nested(),
715            Some(ValuePrimitive::from([("a".into(), "b".into()), ("c".into(), 2.0_f32.into()),]))
716                .as_ref()
717        );
718
719        // option
720        let prim_value: ValuePrimitiveType = Some(true).into();
721        assert_eq!(ValuePrimitiveType::Primitive(PrimitiveValue::Bool(true)), prim_value);
722        let prim_value: ValuePrimitiveType = None::<bool>.into();
723        assert_eq!(ValuePrimitiveType::Primitive(PrimitiveValue::Null), prim_value);
724    }
725
726    #[test]
727    fn value_funcs() {
728        // &str
729        let prim_value: ValueType = "test".into();
730        assert_eq!(ValueType::Primitive(PrimitiveValue::String("test".into())), prim_value);
731        let prim = prim_value.to_prim().unwrap();
732        assert_eq!(*prim, PrimitiveValue::String("test".into()));
733        assert_eq!(prim_value.to_nested(), None);
734        assert_eq!(prim_value.to_vec(), None);
735        // String
736        let prim_value_str: String = "test".into();
737        let prim_value: ValueType = prim_value_str.into();
738        assert_eq!(ValueType::Primitive(PrimitiveValue::String("test".into())), prim_value);
739        // u64
740        let prim_value: ValueType = 1_u64.into();
741        assert_eq!(ValueType::Primitive(PrimitiveValue::U64(1)), prim_value);
742        // i64
743        let prim_value: ValueType = (-1_i64).into();
744        assert_eq!(ValueType::Primitive(PrimitiveValue::I64(-1)), prim_value);
745        // f32
746        let prim_value: ValueType = (1.0_f32).into();
747        assert_eq!(ValueType::Primitive(PrimitiveValue::F32(1.0)), prim_value);
748        // f64
749        let prim_value: ValueType = (1.0_f64).into();
750        assert_eq!(ValueType::Primitive(PrimitiveValue::F64(1.0)), prim_value);
751        // bool
752        let prim_value: ValueType = true.into();
753        assert_eq!(ValueType::Primitive(PrimitiveValue::Bool(true)), prim_value);
754        // ()
755        let prim_value: ValueType = ().into();
756        assert_eq!(ValueType::Primitive(PrimitiveValue::Null), prim_value);
757
758        // vec
759        let prim_value: ValueType = vec!["test", "test2"].into();
760        assert_eq!(prim_value.to_prim(), None);
761        assert_eq!(
762            ValueType::Array(vec![
763                ValuePrimitiveType::Primitive(PrimitiveValue::String("test".into())),
764                ValuePrimitiveType::Primitive(PrimitiveValue::String("test2".into())),
765            ]),
766            prim_value
767        );
768        let back_to_vec: Vec<String> =
769            prim_value.to_vec().unwrap().iter().filter_map(|v| v.to_prim()?.to_string()).collect();
770        assert_eq!(back_to_vec, vec!["test", "test2"]);
771
772        // nested
773        let nested: ValueType =
774            Value::from([("a".into(), "b".into()), ("c".into(), 2.0_f32.into())]).into();
775        assert_eq!(nested.to_vec(), None);
776        assert_eq!(
777            nested.to_nested(),
778            Some(Value::from([("a".into(), "b".into()), ("c".into(), 2.0_f32.into()),])).as_ref()
779        );
780
781        // option
782        let prim_value: ValueType = Some(true).into();
783        assert_eq!(ValueType::Primitive(PrimitiveValue::Bool(true)), prim_value);
784        let prim_value: ValueType = None::<bool>.into();
785        assert_eq!(ValueType::Primitive(PrimitiveValue::Null), prim_value);
786    }
787
788    #[test]
789    fn test_rgba_struct() {
790        #[derive(Debug, Clone, Copy, PartialEq, Default)]
791        pub struct Rgba {
792            /// Gamma corrected Red between 0 and 1
793            pub r: f64,
794            /// Gamma corrected Green between 0 and 1
795            pub g: f64,
796            /// Gamma corrected Blue between 0 and 1
797            pub b: f64,
798            /// Opacity between 0 and 1 (not gamma corrected as opacity is linear)
799            pub a: f64,
800        }
801        impl Rgba {
802            /// Create a new RGBA value
803            pub fn new(r: f64, g: f64, b: f64, a: f64) -> Self {
804                Self { r, g, b, a }
805            }
806        }
807        impl MValueCompatible for Rgba {}
808        impl From<Rgba> for MValue {
809            fn from(rgba: Rgba) -> MValue {
810                MValue::from([
811                    ("r".into(), (rgba.r).into()),
812                    ("g".into(), (rgba.g).into()),
813                    ("b".into(), (rgba.b).into()),
814                    ("a".into(), (rgba.a).into()),
815                ])
816            }
817        }
818        impl From<MValue> for Rgba {
819            fn from(mvalue: MValue) -> Self {
820                let r: f64 = mvalue.get("r").unwrap().to_prim().unwrap().to_f64().unwrap();
821                let g = mvalue.get("g").unwrap().to_prim().unwrap().to_f64().unwrap();
822                let b = mvalue.get("b").unwrap().to_prim().unwrap().to_f64().unwrap();
823                let a = mvalue.get("a").unwrap().to_prim().unwrap().to_f64().unwrap();
824                Rgba::new(r, g, b, a)
825            }
826        }
827
828        let rgba = Rgba::new(0.1, 0.2, 0.3, 0.4);
829        let rgba_mvalue: MValue = rgba.into();
830        assert_eq!(
831            rgba_mvalue,
832            MValue::from([
833                ("r".into(), ValueType::Primitive(PrimitiveValue::F64(0.1))),
834                ("g".into(), ValueType::Primitive(PrimitiveValue::F64(0.2))),
835                ("b".into(), ValueType::Primitive(PrimitiveValue::F64(0.3))),
836                ("a".into(), ValueType::Primitive(PrimitiveValue::F64(0.4))),
837            ])
838        );
839        let back_to_rgba: Rgba = rgba_mvalue.clone().into();
840        assert_eq!(rgba, back_to_rgba);
841
842        let vp: VectorPoint<Rgba> = VectorPoint { x: 1.0, y: 2.0, z: None, m: Some(rgba), t: None };
843        let vp_mvalue: MValue = vp.m.unwrap().into();
844        assert_eq!(vp_mvalue, rgba_mvalue);
845
846        // distance
847        let a: VectorPoint<Rgba> = VectorPoint { x: 1.0, y: 2.0, z: None, m: Some(rgba), t: None };
848        let b: VectorPoint = VectorPoint::new(3.0, 4.0, None, None);
849        let dist = a.distance(&b);
850        assert_eq!(dist, 2.8284271247461903);
851    }
852
853    #[test]
854    fn to_mapbox() {
855        let value: MValue = MValue::from([
856            ("a".into(), "b".into()),
857            ("c".into(), 2.0_f32.into()),
858            (
859                "d".into(),
860                MValue::from([("2".into(), "3".into()), ("4".into(), 2.0_f32.into())]).into(),
861            ),
862        ]);
863        let mapbox_value: MapboxProperties = value.clone().into();
864        assert_eq!(
865            mapbox_value,
866            MapboxProperties::from([("a".into(), "b".into()), ("c".into(), 2.0_f32.into()),])
867        );
868    }
869
870    #[test]
871    fn from_mapbox() {
872        let mapbox_value: MapboxProperties = MapboxProperties::from([("a".into(), "b".into())]);
873        let value: MValue = mapbox_value.clone().into();
874        assert_eq!(value, MValue::from([("a".into(), "b".into()),]));
875    }
876
877    #[test]
878    fn to_json_obj() {
879        let value: MValue = MValue::from([
880            ("a".into(), "b".into()),
881            ("c".into(), 2.0_f32.into()),
882            (
883                "d".into(),
884                MValue::from([("2".into(), "3".into()), ("4".into(), 2.0_f32.into())]).into(),
885            ),
886            (
887                "e".into(),
888                Vec::<ValuePrimitiveType>::from(["a".into(), "b".into(), "c".into()]).into(),
889            ),
890        ]);
891        let json_value: JSONProperties = value.clone().into();
892        assert_eq!(
893            json_value,
894            JSONProperties::from([
895                ("a".into(), JSONValue::Primitive(PrimitiveValue::String("b".into()))),
896                ("c".into(), JSONValue::Primitive(PrimitiveValue::F32(2.0))),
897                (
898                    "d".into(),
899                    JSONValue::Object(JSONProperties::from([
900                        ("2".into(), JSONValue::Primitive(PrimitiveValue::String("3".into()))),
901                        ("4".into(), JSONValue::Primitive(PrimitiveValue::F32(2.0))),
902                    ]))
903                ),
904                (
905                    "e".into(),
906                    JSONValue::Array(Vec::from([
907                        JSONValue::Primitive(PrimitiveValue::String("a".into())),
908                        JSONValue::Primitive(PrimitiveValue::String("b".into())),
909                        JSONValue::Primitive(PrimitiveValue::String("c".into())),
910                    ]))
911                ),
912            ])
913        );
914
915        // get prim
916        let prim_a = json_value.get("a").unwrap().to_prim().unwrap().to_string().unwrap();
917        assert_eq!(prim_a, "b");
918        let failed_to_prim = json_value.get("d").unwrap().to_prim();
919        assert_eq!(failed_to_prim, None);
920
921        // get array
922        let array_e = json_value.get("e").unwrap().to_vec().unwrap();
923        assert_eq!(
924            *array_e,
925            Vec::from([
926                JSONValue::Primitive(PrimitiveValue::String("a".into())),
927                JSONValue::Primitive(PrimitiveValue::String("b".into())),
928                JSONValue::Primitive(PrimitiveValue::String("c".into())),
929            ])
930        );
931        let array_fail = json_value.get("a").unwrap().to_vec();
932        assert_eq!(array_fail, None);
933
934        // get obj
935        let obj_d = json_value.get("d").unwrap().to_nested().unwrap();
936        assert_eq!(
937            *obj_d,
938            JSONProperties::from([
939                ("2".into(), JSONValue::Primitive(PrimitiveValue::String("3".into()))),
940                ("4".into(), JSONValue::Primitive(PrimitiveValue::F32(2.0))),
941            ])
942        );
943        let obj_fail = json_value.get("a").unwrap().to_nested();
944        assert_eq!(obj_fail, None);
945    }
946
947    #[test]
948    fn from_json_obj() {
949        let json_value = JSONProperties::from([
950            ("a".into(), JSONValue::Primitive(PrimitiveValue::String("b".into()))),
951            ("c".into(), JSONValue::Primitive(PrimitiveValue::F32(2.0))),
952            (
953                "d".into(),
954                JSONValue::Object(JSONProperties::from([
955                    ("2".into(), JSONValue::Primitive(PrimitiveValue::String("3".into()))),
956                    ("4".into(), JSONValue::Primitive(PrimitiveValue::F32(2.0))),
957                ])),
958            ),
959            (
960                "e".into(),
961                JSONValue::Array(Vec::from([
962                    JSONValue::Primitive(PrimitiveValue::String("a".into())),
963                    JSONValue::Primitive(PrimitiveValue::String("b".into())),
964                    JSONValue::Primitive(PrimitiveValue::String("c".into())),
965                ])),
966            ),
967        ]);
968        let value: MValue = json_value.clone().into();
969        assert_eq!(
970            value,
971            MValue::from([
972                ("a".into(), "b".into()),
973                ("c".into(), 2.0_f32.into()),
974                (
975                    "d".into(),
976                    MValue::from([("2".into(), "3".into()), ("4".into(), 2.0_f32.into())]).into(),
977                ),
978                (
979                    "e".into(),
980                    Vec::<ValuePrimitiveType>::from(["a".into(), "b".into(), "c".into()]).into(),
981                ),
982            ])
983        );
984    }
985
986    #[test]
987    fn test_prim_to_json() {
988        let json: JSONValue = (&PrimitiveValue::String("test".into())).into();
989        assert_eq!(json, JSONValue::Primitive(PrimitiveValue::String("test".into())));
990
991        let prim: PrimitiveValue = (&json).into();
992        assert_eq!(prim, PrimitiveValue::String("test".into()));
993
994        // to prim but json is not a prim
995        let json = JSONValue::Array(Vec::new());
996        let prim: PrimitiveValue = (&json).into();
997        assert_eq!(prim, PrimitiveValue::Null);
998    }
999
1000    #[test]
1001    fn test_value_prim_type_to_json() {
1002        let prim = ValuePrimitiveType::NestedPrimitive(Map::from([
1003            ("a".into(), "b".into()),
1004            ("c".into(), 2.0_f32.into()),
1005        ]));
1006        let json: JSONValue = (&prim).into();
1007        assert_eq!(
1008            json,
1009            JSONValue::Object(JSONProperties::from([
1010                ("a".into(), JSONValue::Primitive(PrimitiveValue::String("b".into()))),
1011                ("c".into(), JSONValue::Primitive(PrimitiveValue::F32(2.0))),
1012            ]))
1013        );
1014
1015        let json = JSONValue::Object(JSONProperties::from([
1016            ("2".into(), JSONValue::Primitive(PrimitiveValue::String("3".into()))),
1017            ("4".into(), JSONValue::Primitive(PrimitiveValue::F32(2.0))),
1018        ]));
1019
1020        let prim: ValuePrimitiveType = (&json).into();
1021        assert_eq!(
1022            prim,
1023            ValuePrimitiveType::NestedPrimitive(Map::from([
1024                ("2".into(), "3".into()),
1025                ("4".into(), 2.0_f32.into()),
1026            ]))
1027        );
1028
1029        // Array Fails
1030        let json = JSONValue::Array(Vec::from([
1031            JSONValue::Primitive(PrimitiveValue::String("c".into())),
1032            JSONValue::Primitive(PrimitiveValue::String("d".into())),
1033        ]));
1034
1035        let prim: ValuePrimitiveType = (&json).into();
1036        assert_eq!(prim, ValuePrimitiveType::Primitive(PrimitiveValue::Null));
1037    }
1038}