jasn-core 0.2.0

Core data types for JASN and JAML serialization formats
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
use std::{borrow::Cow, collections::BTreeMap};

mod binary;
pub use binary::Binary;
mod timestamp;
pub use timestamp::Timestamp;

#[cfg(feature = "serde")]
pub mod de;
#[cfg(feature = "serde")]
pub mod ser;

/// Represents a valid JASN value.
#[derive(Debug, Clone, PartialEq, Default)]
pub enum Value {
    /// Null value.
    #[default]
    Null,
    /// Boolean value (true or false).
    Bool(bool),
    /// 64-bit signed integer.
    Int(i64),
    /// 64-bit floating-point number.
    Float(f64),
    /// UTF-8 string.
    String(String),
    /// Binary data (byte array).
    Binary(Binary),
    /// Timestamp with timezone (ISO8601/RFC3339 compatible).
    Timestamp(Timestamp),
    /// Ordered list of values.
    List(Vec<Value>),
    /// Map of string keys to values.
    Map(BTreeMap<String, Value>),
}

/// Display implementation for Value using debug formatting.
///
/// For proper JASN formatting, use the `jasn` crate's formatting functions.
impl std::fmt::Display for Value {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", self)
    }
}

impl Value {
    /// Returns true if the value is [`Self::Null`].
    pub fn is_null(&self) -> bool {
        matches!(self, Value::Null)
    }

    /// Returns true if the value is [`Self::Bool`].
    pub fn is_bool(&self) -> bool {
        matches!(self, Value::Bool(_))
    }

    /// Returns true if the value is [`Self::Int`].
    pub fn is_int(&self) -> bool {
        matches!(self, Value::Int(_))
    }

    /// Returns true if the value is [`Self::Float`].
    pub fn is_float(&self) -> bool {
        matches!(self, Value::Float(_))
    }

    /// Returns true if the value is [`Self::String`].
    pub fn is_string(&self) -> bool {
        matches!(self, Value::String(_))
    }

    /// Returns true if the value is [`Self::Binary`].
    pub fn is_binary(&self) -> bool {
        matches!(self, Value::Binary(_))
    }

    /// Returns true if the value is [`Self::Timestamp`].
    pub fn is_timestamp(&self) -> bool {
        matches!(self, Value::Timestamp(_))
    }

    /// Returns true if the value is [`Self::List`].
    pub fn is_list(&self) -> bool {
        matches!(self, Value::List(_))
    }

    /// Returns true if the value is [`Self::Map`].
    pub fn is_map(&self) -> bool {
        matches!(self, Value::Map(_))
    }

    /// Returns the [`bool`] value if this is a [`Self::Bool`], otherwise `None`.
    pub fn as_bool(&self) -> Option<bool> {
        match self {
            Value::Bool(b) => Some(*b),
            _ => None,
        }
    }

    /// Returns the [`i64`] value if this is a [`Self::Int`], otherwise `None`.
    pub fn as_int(&self) -> Option<i64> {
        match self {
            Value::Int(i) => Some(*i),
            _ => None,
        }
    }

    /// Returns the [`f64`] value if this is a [`Self::Float`], otherwise `None`.
    pub fn as_float(&self) -> Option<f64> {
        match self {
            Value::Float(f) => Some(*f),
            _ => None,
        }
    }

    /// Returns the [`str`] if this is a [`Self::String`], otherwise `None`.
    pub fn as_string(&self) -> Option<&str> {
        match self {
            Value::String(s) => Some(s),
            _ => None,
        }
    }

    /// Returns the [`Binary`] if this is a [`Self::Binary`], otherwise `None`.
    pub fn as_binary(&self) -> Option<&Binary> {
        match self {
            Value::Binary(b) => Some(b),
            _ => None,
        }
    }

    /// Returns the [`Timestamp`] value if this is a [`Self::Timestamp`], otherwise `None`.
    pub fn as_timestamp(&self) -> Option<&Timestamp> {
        match self {
            Value::Timestamp(t) => Some(t),
            _ => None,
        }
    }

    /// Returns the list of values if this is a [`Self::List`], otherwise `None`.
    pub fn as_list(&self) -> Option<&[Value]> {
        match self {
            Value::List(l) => Some(l),
            _ => None,
        }
    }

    /// Returns the map of key-value pairs if this is a [`Self::Map`], otherwise `None`.
    pub fn as_map(&self) -> Option<&BTreeMap<String, Value>> {
        match self {
            Value::Map(m) => Some(m),
            _ => None,
        }
    }

    /// Returns a mutable reference to the list of values if this is a [`Self::List`], otherwise `None`.
    pub fn as_list_mut(&mut self) -> Option<&mut Vec<Value>> {
        match self {
            Value::List(l) => Some(l),
            _ => None,
        }
    }

    /// Returns a mutable reference to the map of key-value pairs if this is a [`Self::Map`], otherwise `None`.
    pub fn as_map_mut(&mut self) -> Option<&mut BTreeMap<String, Value>> {
        match self {
            Value::Map(m) => Some(m),
            _ => None,
        }
    }

    /// Takes the value, leaving [`Self::Null`] in its place.
    pub fn take(&mut self) -> Value {
        std::mem::replace(self, Value::Null)
    }
}

impl From<()> for Value {
    fn from(_: ()) -> Self {
        Value::Null
    }
}

impl From<bool> for Value {
    fn from(value: bool) -> Self {
        Value::Bool(value)
    }
}

impl From<i64> for Value {
    fn from(value: i64) -> Self {
        Value::Int(value)
    }
}

impl From<f64> for Value {
    fn from(value: f64) -> Self {
        Value::Float(value)
    }
}

impl From<String> for Value {
    fn from(value: String) -> Self {
        Value::String(value)
    }
}

impl From<&str> for Value {
    fn from(value: &str) -> Self {
        Value::String(value.to_string())
    }
}

impl<'a> From<Cow<'a, str>> for Value {
    fn from(value: Cow<'a, str>) -> Self {
        Value::String(value.into_owned())
    }
}

impl From<Binary> for Value {
    fn from(value: Binary) -> Self {
        Value::Binary(value)
    }
}

impl From<Timestamp> for Value {
    fn from(value: Timestamp) -> Self {
        Value::Timestamp(value)
    }
}

impl<V> From<Vec<V>> for Value
where
    V: Into<Value>,
{
    fn from(vec: Vec<V>) -> Self {
        vec.into_iter().collect()
    }
}

impl<V> From<&[V]> for Value
where
    V: Into<Value> + Clone,
{
    fn from(slice: &[V]) -> Self {
        slice.iter().cloned().collect()
    }
}

impl<V, const N: usize> From<[V; N]> for Value
where
    V: Into<Value>,
{
    fn from(arr: [V; N]) -> Self {
        arr.into_iter().collect()
    }
}

impl<V, const N: usize> From<&[V; N]> for Value
where
    V: Into<Value> + Clone,
{
    fn from(arr: &[V; N]) -> Self {
        arr.iter().cloned().collect()
    }
}

impl<V> FromIterator<V> for Value
where
    V: Into<Value>,
{
    fn from_iter<I: IntoIterator<Item = V>>(iter: I) -> Self {
        Value::List(iter.into_iter().map(Into::into).collect())
    }
}

impl<K, V> FromIterator<(K, V)> for Value
where
    K: Into<String>,
    V: Into<Value>,
{
    fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
        Value::Map(
            iter.into_iter()
                .map(|(k, v)| (k.into(), v.into()))
                .collect(),
        )
    }
}

impl<K, V> From<&[(K, V)]> for Value
where
    K: Into<String> + Clone,
    V: Into<Value> + Clone,
{
    fn from(slice: &[(K, V)]) -> Self {
        slice.iter().cloned().collect()
    }
}

impl<K, V, const N: usize> From<[(K, V); N]> for Value
where
    K: Into<String>,
    V: Into<Value>,
{
    fn from(arr: [(K, V); N]) -> Self {
        arr.into_iter().collect()
    }
}

impl<K, V, const N: usize> From<&[(K, V); N]> for Value
where
    K: Into<String> + Clone,
    V: Into<Value> + Clone,
{
    fn from(arr: &[(K, V); N]) -> Self {
        arr.iter().cloned().collect()
    }
}

impl<V> From<Option<V>> for Value
where
    V: Into<Value>,
{
    fn from(opt: Option<V>) -> Self {
        match opt {
            Some(v) => v.into(),
            None => Value::Null,
        }
    }
}

impl PartialEq<str> for Value {
    fn eq(&self, other: &str) -> bool {
        self.as_string() == Some(other)
    }
}

impl PartialEq<&str> for Value {
    fn eq(&self, other: &&str) -> bool {
        self.as_string() == Some(*other)
    }
}

impl PartialEq<String> for Value {
    fn eq(&self, other: &String) -> bool {
        self.as_string() == Some(other.as_str())
    }
}

impl PartialEq<i64> for Value {
    fn eq(&self, other: &i64) -> bool {
        self.as_int() == Some(*other)
    }
}

impl PartialEq<f64> for Value {
    fn eq(&self, other: &f64) -> bool {
        self.as_float() == Some(*other)
    }
}

impl PartialEq<bool> for Value {
    fn eq(&self, other: &bool) -> bool {
        self.as_bool() == Some(*other)
    }
}

#[cfg(test)]
mod tests {
    use rstest::rstest;

    use super::*;

    #[rstest]
    #[case(Value::Null, "null")]
    #[case(Value::Bool(true), "bool")]
    #[case(Value::Int(42), "int")]
    #[case(Value::Float(2.5), "float")]
    #[case(Value::String("hello".to_string()), "string")]
    #[case(Value::Binary(Binary(vec![1, 2, 3])), "binary")]
    #[case(Value::Timestamp(Timestamp::from_unix_timestamp(1234567890).unwrap()), "timestamp")]
    #[case(Value::List(vec![Value::Null]), "list")]
    #[case(Value::Map(BTreeMap::new()), "map")]
    fn test_is_methods(#[case] value: Value, #[case] value_type: &str) {
        assert_eq!(value.is_null(), value_type == "null");
        assert_eq!(value.is_bool(), value_type == "bool");
        assert_eq!(value.is_int(), value_type == "int");
        assert_eq!(value.is_float(), value_type == "float");
        assert_eq!(value.is_string(), value_type == "string");
        assert_eq!(value.is_binary(), value_type == "binary");
        assert_eq!(value.is_timestamp(), value_type == "timestamp");
        assert_eq!(value.is_list(), value_type == "list");
        assert_eq!(value.is_map(), value_type == "map");
    }

    #[test]
    fn test_as_bool() {
        assert_eq!(Value::Bool(true).as_bool(), Some(true));
        assert_eq!(Value::Null.as_bool(), None);
    }

    #[test]
    fn test_as_int() {
        assert_eq!(Value::Int(42).as_int(), Some(42));
        assert_eq!(Value::Float(2.5).as_int(), None);
    }

    #[test]
    fn test_as_float() {
        assert_eq!(Value::Float(2.5).as_float(), Some(2.5));
        assert_eq!(Value::Int(42).as_float(), None);
    }

    #[test]
    fn test_as_string() {
        assert_eq!(
            Value::String("hello".to_string()).as_string(),
            Some("hello")
        );
        assert_eq!(Value::Null.as_string(), None);
    }

    #[test]
    fn test_as_binary() {
        let binary = Binary(vec![1, 2, 3]);
        let binary_val = Value::Binary(binary.clone());
        assert_eq!(binary_val.as_binary(), Some(&binary));
        assert_eq!(Value::Null.as_binary(), None);
    }

    #[test]
    fn test_as_timestamp() {
        let ts = Timestamp::from_unix_timestamp(1234567890).unwrap();
        let ts_val = Value::Timestamp(ts);
        assert_eq!(ts_val.as_timestamp(), Some(&ts));
        assert_eq!(Value::Int(42).as_timestamp(), None);
    }

    #[test]
    fn test_as_list() {
        let list = vec![Value::Int(1), Value::Int(2)];
        let list_val = Value::List(list.clone());
        assert_eq!(list_val.as_list(), Some(list.as_slice()));
        assert_eq!(Value::Null.as_list(), None);
    }

    #[test]
    fn test_as_map() {
        let mut map = BTreeMap::new();
        map.insert("key".to_string(), Value::Int(42));
        let map_val = Value::Map(map.clone());
        assert_eq!(map_val.as_map(), Some(&map));
        assert_eq!(Value::Null.as_map(), None);
    }

    #[rstest]
    #[case(Value::from(()), Value::Null)]
    #[case(Value::from(true), Value::Bool(true))]
    #[case(Value::from(42i64), Value::Int(42))]
    #[case(Value::from(2.5f64), Value::Float(2.5))]
    #[case(Value::from("hello".to_string()), Value::String("hello".to_string()))]
    #[case(Value::from("world"), Value::String("world".to_string()))]
    fn test_from_primitives(#[case] actual: Value, #[case] expected: Value) {
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_from_conversions() {
        // From primitives - tested via rstest above

        // From Cow
        let owned: Cow<str> = Cow::Owned("owned".to_string());
        assert_eq!(Value::from(owned), Value::String("owned".to_string()));
        let borrowed: Cow<str> = Cow::Borrowed("borrowed");
        assert_eq!(Value::from(borrowed), Value::String("borrowed".to_string()));

        // From Binary
        let binary = Binary(vec![1, 2, 3]);
        assert_eq!(Value::from(binary.clone()), Value::Binary(binary));

        // From Timestamp
        let dt = Timestamp::from_unix_timestamp(1234567890).unwrap();
        assert_eq!(Value::from(dt), Value::Timestamp(dt));

        // Value::Binary from byte literal
        let value = Value::Binary(b"data".into());
        assert_eq!(value, Value::Binary(Binary(b"data".to_vec())));

        // From Vec
        let vec = vec![1i64, 2, 3];
        let list_val = Value::from(vec);
        assert_eq!(
            list_val,
            Value::List(vec![Value::Int(1), Value::Int(2), Value::Int(3)])
        );

        // From &[V]
        let slice: &[i64] = &[1, 2, 3];
        let list_val = Value::from(slice);
        assert_eq!(
            list_val,
            Value::List(vec![Value::Int(1), Value::Int(2), Value::Int(3)])
        );

        // FromIterator for List
        let list_val: Value = vec![1i64, 2, 3].into_iter().collect();
        assert_eq!(
            list_val,
            Value::List(vec![Value::Int(1), Value::Int(2), Value::Int(3)])
        );

        // FromIterator for Map
        let map_val: Value = vec![("a", 1i64), ("b", 2)].into_iter().collect();
        let mut expected_map = BTreeMap::new();
        expected_map.insert("a".to_string(), Value::Int(1));
        expected_map.insert("b".to_string(), Value::Int(2));
        assert_eq!(map_val, Value::Map(expected_map));

        // From &[(K, V)]
        let slice: &[(&str, i64)] = &[("x", 10), ("y", 20)];
        let map_val = Value::from(slice);
        let mut expected_map = BTreeMap::new();
        expected_map.insert("x".to_string(), Value::Int(10));
        expected_map.insert("y".to_string(), Value::Int(20));
        assert_eq!(map_val, Value::Map(expected_map));

        // From [V; N] - owned array to List
        let list_val = Value::from([1i64, 2, 3]);
        assert_eq!(
            list_val,
            Value::List(vec![Value::Int(1), Value::Int(2), Value::Int(3)])
        );

        // From &[V; N] - array reference to List
        let arr = [4i64, 5, 6];
        let list_val = Value::from(&arr);
        assert_eq!(
            list_val,
            Value::List(vec![Value::Int(4), Value::Int(5), Value::Int(6)])
        );

        // From [(K, V); N] - owned array to Map
        let map_val = Value::from([("a", 1i64), ("b", 2)]);
        let mut expected_map = BTreeMap::new();
        expected_map.insert("a".to_string(), Value::Int(1));
        expected_map.insert("b".to_string(), Value::Int(2));
        assert_eq!(map_val, Value::Map(expected_map));

        // From &[(K, V); N] - array reference to Map
        let arr = [("c", 3i64), ("d", 4)];
        let map_val = Value::from(&arr);
        let mut expected_map = BTreeMap::new();
        expected_map.insert("c".to_string(), Value::Int(3));
        expected_map.insert("d".to_string(), Value::Int(4));
        assert_eq!(map_val, Value::Map(expected_map));

        // From Option
        assert_eq!(Value::from(Some(42i64)), Value::Int(42));
        assert_eq!(Value::from(None::<i64>), Value::Null);
    }

    #[test]
    fn test_default() {
        assert_eq!(Value::default(), Value::Null);
    }

    #[test]
    fn test_mutable_accessors() {
        // as_list_mut
        let mut list_val = Value::List(vec![Value::Int(1), Value::Int(2)]);
        if let Some(list) = list_val.as_list_mut() {
            list.push(Value::Int(3));
            list[0] = Value::Int(10);
        }
        assert_eq!(
            list_val,
            Value::List(vec![Value::Int(10), Value::Int(2), Value::Int(3)])
        );

        // as_list_mut returns None for non-list
        let mut int_val = Value::Int(42);
        assert_eq!(int_val.as_list_mut(), None);

        // as_map_mut
        let mut map_val = Value::Map(BTreeMap::new());
        if let Some(map) = map_val.as_map_mut() {
            map.insert("key".to_string(), Value::Int(42));
            if let Some(value) = map.get_mut("key") {
                *value = Value::Int(99);
            }
        }
        let mut expected = BTreeMap::new();
        expected.insert("key".to_string(), Value::Int(99));
        assert_eq!(map_val, Value::Map(expected));

        // as_map_mut returns None for non-map
        assert_eq!(int_val.as_map_mut(), None);
    }

    #[test]
    fn test_take() {
        let mut value = Value::Int(42);
        let taken = value.take();
        assert_eq!(taken, Value::Int(42));
        assert_eq!(value, Value::Null);

        let mut list = Value::List(vec![Value::Int(1), Value::Int(2)]);
        let taken = list.take();
        assert_eq!(taken, Value::List(vec![Value::Int(1), Value::Int(2)]));
        assert_eq!(list, Value::Null);

        // Taking from Null leaves Null
        let mut null = Value::Null;
        let taken = null.take();
        assert_eq!(taken, Value::Null);
        assert_eq!(null, Value::Null);
    }

    #[test]
    fn test_partial_eq_string() {
        let string_val = Value::String("hello".to_string());
        assert_eq!(string_val, "hello");
        assert_eq!(string_val, "hello".to_string());
        assert_ne!(string_val, "world");
    }

    #[test]
    fn test_partial_eq_int() {
        let int_val = Value::Int(42);
        assert_eq!(int_val, 42i64);
        assert_ne!(int_val, 43i64);
    }

    #[test]
    fn test_partial_eq_float() {
        let float_val = Value::Float(2.5);
        assert_eq!(float_val, 2.5f64);
        assert_ne!(float_val, 1.5f64);
    }

    #[test]
    fn test_partial_eq_bool() {
        let bool_val = Value::Bool(true);
        assert_eq!(bool_val, true);
        assert_ne!(bool_val, false);
    }

    #[test]
    fn test_partial_eq_mismatched_types() {
        let int_val = Value::Int(42);
        let string_val = Value::String("hello".to_string());
        assert_ne!(int_val, "42");
        assert_ne!(string_val, 42i64);
    }
}