gc_value 0.1.0

Generic value type, capturing the data model of common formats such as JSON, YAML and CBOR, based on Arc for cheap cloning.
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
//! [`GcValue`] (for Garbage-collected Value) is a generic value type,
//! capturing the data model of common formats such as [JSON], [YAML], [CBOR],
//! and the [INFRA] API.
//!
//! It uses [`Arc`] for cheap shallow cloning,
//! mimicking the assumptions of garbage-collected language (such as Javascript).
//!
//! It also supports serialization/deserialization via [`serde`].
//!
//! [JSON]: https://www.json.org/json-en.html
//! [YAML]: https://yaml.org/spec/
//! [CBOR]: https://cbor.io/
//! [INFRA]: https://infra.spec.whatwg.org/
//!
//! # Construction
//!
//! [`GcValue`] provides a constructor for each variant
//! (e.g. [`GcValue::new_text`], [`GcValue::new_int`], etc.),
//! which accept any type directly convertible (with [`From`]) to the underlying data.
//! For composite variants (like [`GcValue::Array`] or [`GcValue::Map`]),
//! it also provides "collecting" constructors (e.g. [`GcValue::collect_array`])
//! that accepts any iterable of convertible types.
//!
//! [`GcValue`] also implements [`From`] and [`FromIterator`] for a number of types.
//!
//! # Comparison
//!
//! This type implements usual comparison traits such as [`Eq`], [`Ord`] and [`Hash`].
//! It should be noted that:
//! - the implementation of [`Ord`] is mostly for internal use,
//!   (sorting key-value pairs in the [`GcValue::Map`] variant).
//! - the implementation of [`Eq`] and [`Hash`] for the [`GcValue::Float`]
//!   variant use bit-wise comparison, not IEE754-compliant comparison.
//!   In particular, two [`GcValue::Float`] with value `NaN` are considered equal.
//!
//! [`GcValue`] also implements [`PartialEq`] with common types, in the expected way:
//! * comparing with `&`[`str`] for [`GcValue::Text`];
//! * comparing with most integer types for [`GcValue::Int`].
//! * comparing with [`f64`] and [`f32`] for [`GcValue::Float`] (using bit-wise comparison, *not* numeric comparison);
//! * comparing with [`bool`] for [`GcValue::Boolean`],
//! * comparing with `[T]` for [`GcValue::Array`], where `T` is any type comparable to [`GcValue`];
//! * comparing with [`Map`] for [`GcValue::Map`];
//! * comparing with `(T, U)` for [`GcValue::Tag`], where `T` and `U` are any types comparable to [`GcValue`].
//!
//! Note that, for regularity, a `[`[`u8`]`]` will match a [`GcValue::Array`], **not** a [`GcValue::Bytes`].
//!
//! # Tagged value
//!
//! [`GcValue`] has the notion of [tagged value](GcValue::Tag),
//! because this notion exists in both [CBOR] (with integers as tags) and [YAML] (with strings as tags).
//! Note however that this notions does not have any direct correspondence in [`serde`],
//! and is currently not supported by the implementation of [`serde:Serializer`](https://docs.rs/serde/latest/serde/trait.Serializer.html).
//! (consistently with [`serde_cbor`](https://docs.rs/serde_cbor/latest/serde_cbor/), for example).
#![deny(missing_docs)]

use std::sync::Arc;

mod cmp_impl;
mod from_impl;
mod map;
mod serde_impl;

pub use map::Map;

/// See [crate] documentation.
#[derive(Clone, Debug, Default)]
pub enum GcValue {
    /// A string
    Text(Arc<str>),
    /// A signed integer
    Int(i128),
    /// A floating point number
    Float(f64),
    /// A boolean
    Boolean(bool),
    /// An array
    Array(Arc<[GcValue]>),
    /// An unordered map
    Map(Arc<map::Map>),
    /// A tagged value
    Tag(Arc<(GcValue, GcValue)>),
    /// A bytes sequence
    Bytes(Arc<[u8]>),
    /// A null value
    #[default]
    Null,
}

impl GcValue {
    /// Construct a new [`GcValue::Text`]
    pub fn new_text<T: Into<Arc<str>>>(v: T) -> Self {
        Self::Text(v.into())
    }

    /// Construct a new [`GcValue::Int`]
    pub fn new_int<T: Into<i128>>(v: T) -> Self {
        Self::Int(v.into())
    }

    /// Construct a new [`GcValue::Float`]
    pub fn new_float<T: Into<f64>>(v: T) -> Self {
        Self::Float(v.into())
    }

    /// Construct a new [`GcValue::Boolean`]
    pub fn new_boolean<T: Into<bool>>(v: T) -> Self {
        Self::Boolean(v.into())
    }

    /// Construct a new [`GcValue::Array`]
    ///
    /// See also [`GcValue::collect_array`]
    pub fn new_array<T: Into<Arc<[GcValue]>>>(v: T) -> Self {
        Self::Array(v.into())
    }

    /// Construct a new [`GcValue::Map`]
    ///
    /// See also [`GcValue::collect_map`]
    pub fn new_map<T: Into<Arc<Map>>>(v: T) -> Self {
        Self::Map(v.into())
    }

    /// Construct a new [`GcValue::Tag`]
    ///
    /// See also [`GcValue::collect_tag`]
    pub fn new_tag<T: Into<Arc<(GcValue, GcValue)>>>(v: T) -> Self {
        Self::Tag(v.into())
    }

    /// Construct a new [`GcValue::Tag`]
    pub fn new_bytes<T: Into<Arc<[u8]>>>(v: T) -> Self {
        Self::Bytes(v.into())
    }

    /// Construct a new [`GcValue::Null`]
    pub fn new_null() -> Self {
        Self::Null
    }

    /// Construct a new [`GcValue::Array`]
    ///
    /// See also [`GcValue::new_array`]
    pub fn collect_array<T, U>(values: T) -> Self
    where
        T: IntoIterator<Item = U>,
        GcValue: From<U>,
    {
        Self::Array(values.into_iter().map(From::from).collect())
    }

    /// Construct a new [`GcValue::Map`]
    ///
    /// See also [`GcValue::new_array`]
    pub fn collect_map<T, K, V>(pairs: T) -> Self
    where
        T: IntoIterator<Item = (K, V)>,
        GcValue: From<K> + From<V>,
    {
        Self::Map(Arc::new(pairs.into_iter().collect()))
    }

    /// Construct a new [`GcValue::Tag`]
    ///
    /// See also [`GcValue::new_array`]
    pub fn collect_tag<T, U>(tag: T, value: U) -> Self
    where
        GcValue: From<T> + From<U>,
    {
        Self::Tag(Arc::new((tag.into(), value.into())))
    }

    /// Construct a new [`GcValue::Bytes`]
    ///
    /// See also [`GcValue::new_bytes`]
    pub fn collect_bytes<T>(values: T) -> Self
    where
        T: IntoIterator<Item = u8>,
    {
        Self::Bytes(values.into_iter().collect())
    }

    /// Return the value of this [`GcValue`] if it is a text.
    pub fn as_text(&self) -> Option<&Arc<str>> {
        if let Self::Text(ret) = self {
            Some(ret)
        } else {
            None
        }
    }

    /// Return the value of this [`GcValue`] if it is an int.
    pub fn as_int(&self) -> Option<i128> {
        if let Self::Int(ret) = self {
            Some(*ret)
        } else {
            None
        }
    }

    /// Return the value of this [`GcValue`] if it is an float.
    pub fn as_float(&self) -> Option<f64> {
        if let Self::Float(ret) = self {
            Some(*ret)
        } else {
            None
        }
    }

    /// Return the value of this [`GcValue`] if it is an boolean.
    pub fn as_boolean(&self) -> Option<bool> {
        if let Self::Boolean(ret) = self {
            Some(*ret)
        } else {
            None
        }
    }

    /// Return the value of this [`GcValue`] if it is an array.
    pub fn as_array(&self) -> Option<&[GcValue]> {
        if let Self::Array(ret) = self {
            Some(ret.as_ref())
        } else {
            None
        }
    }

    /// Return the value of this [`GcValue`] if it is a map.
    pub fn as_map(&self) -> Option<&Arc<Map>> {
        if let Self::Map(ret) = self {
            Some(ret)
        } else {
            None
        }
    }

    /// Return the value of this [`GcValue`] if it is a tagged value.
    pub fn as_tag(&self) -> Option<(&GcValue, &GcValue)> {
        if let Self::Tag(ret) = self {
            let (t, v) = ret.as_ref();
            Some((t, v))
        } else {
            None
        }
    }

    /// Return the value of this [`GcValue`] if it is a bytes sequence.
    pub fn as_bytes(&self) -> Option<&[u8]> {
        if let Self::Bytes(ret) = self {
            Some(ret.as_ref())
        } else {
            None
        }
    }

    /// Return the value of this [`GcValue`] as `()` if it is null.
    pub fn as_null(&self) -> Option<()> {
        if let Self::Null = self {
            Some(())
        } else {
            None
        }
    }

    /// Return whether the value of this [`GcValue`] is a text.
    pub fn is_text(&self) -> bool {
        self.as_text().is_some()
    }

    /// Return whether the value of this [`GcValue`] is an int.
    pub fn is_int(&self) -> bool {
        self.as_int().is_some()
    }

    /// Return whether the value of this [`GcValue`] is an float.
    pub fn is_float(&self) -> bool {
        self.as_float().is_some()
    }

    /// Return whether the value of this [`GcValue`] is an boolean.
    pub fn is_boolean(&self) -> bool {
        self.as_boolean().is_some()
    }

    /// Return whether the value of this [`GcValue`] is an array.
    pub fn is_array(&self) -> bool {
        self.as_array().is_some()
    }

    /// Return whether the value of this [`GcValue`] is a map.
    pub fn is_map(&self) -> bool {
        self.as_map().is_some()
    }

    /// Return whether the value of this [`GcValue`] is a tagged value.
    pub fn is_tag(&self) -> bool {
        self.as_tag().is_some()
    }

    /// Return whether the value of this [`GcValue`] is a bytes sequence.
    pub fn is_bytes(&self) -> bool {
        self.as_bytes().is_some()
    }

    /// Return whether the value of this [`GcValue`] is null.
    pub fn is_null(&self) -> bool {
        self.as_null().is_some()
    }

    /// Return whether the value of this [`GcValue`] is a text, and satisfies the predicate `p`.
    pub fn is_text_and<F: FnOnce(&str) -> bool>(&self, p: F) -> bool {
        self.as_text().map(|txt| p(txt)).is_some()
    }

    /// Return whether the value of this [`GcValue`] is an int, and satisfies the predicate `p`.
    pub fn is_int_and<F: FnOnce(i128) -> bool>(&self, p: F) -> bool {
        self.as_int().map(p).is_some()
    }

    /// Return whether the value of this [`GcValue`] is an float, and satisfies the predicate `p`.
    pub fn is_float_and<F: FnOnce(f64) -> bool>(&self, p: F) -> bool {
        self.as_float().map(p).is_some()
    }

    /// Return whether the value of this [`GcValue`] is an boolean, and satisfies the predicate `p`.
    pub fn is_boolean_and<F: FnOnce(bool) -> bool>(&self, p: F) -> bool {
        self.as_boolean().map(p).is_some()
    }

    /// Return whether the value of this [`GcValue`] is an array, and satisfies the predicate `p`.
    pub fn is_array_and<F: FnOnce(&[GcValue]) -> bool>(&self, p: F) -> bool {
        self.as_array().map(p).is_some()
    }

    /// Return whether the value of this [`GcValue`] is a map, and satisfies the predicate `p`.
    pub fn is_map_and<F: FnOnce(&Map) -> bool>(&self, p: F) -> bool {
        self.as_map().map(|m| p(m)).is_some()
    }

    /// Return whether the value of this [`GcValue`] is a tagged value, and satisfies the predicate `p`.
    pub fn is_tag_and<F: FnOnce((&GcValue, &GcValue)) -> bool>(&self, p: F) -> bool {
        self.as_tag().map(p).is_some()
    }

    /// Return whether the value of this [`GcValue`] is a bytes sequence, and satisfies the predicate `p`.
    pub fn is_bytes_and<F: FnOnce(&[u8]) -> bool>(&self, p: F) -> bool {
        self.as_bytes().map(p).is_some()
    }

    /// Return whether the value of this [`GcValue`] is null, and predicate `p` returns `true`.
    pub fn is_null_and<F: FnOnce() -> bool>(&self, p: F) -> bool {
        self.as_null().map(|_| p()).is_some()
    }

    /// Return whether the value is JSON-compatible.
    pub fn is_json(&self) -> bool {
        match self {
            GcValue::Text(_) => true,
            GcValue::Int(n) => n.abs() < 1_000_000_000_000_000_000_000,
            GcValue::Float(_) => true,
            GcValue::Boolean(_) => true,
            GcValue::Array(gc_values) => gc_values.iter().all(GcValue::is_json),
            GcValue::Map(map) => map.iter().all(|(k, v)| k.is_text() && v.is_json()),
            GcValue::Tag(_) => false,
            GcValue::Bytes(_) => false,
            GcValue::Null => true,
        }
    }

    /// Return whether the value is CBOR-compatible.
    pub fn is_cbor(&self) -> bool {
        match self {
            GcValue::Text(_) => true,
            GcValue::Int(n) => i64::MIN as i128 <= *n && *n <= i64::MAX as i128,
            GcValue::Float(_) => true,
            GcValue::Boolean(_) => true,
            GcValue::Array(gc_values) => gc_values.iter().all(GcValue::is_cbor),
            GcValue::Map(map) => map.iter().all(|(k, v)| k.is_cbor() && v.is_cbor()),
            GcValue::Tag(pair) => pair.0.is_u64() && pair.1.is_cbor(),
            GcValue::Bytes(_) => true,
            GcValue::Null => true,
        }
    }

    /// Return whether the value is an integer fitting the i64 datatype
    fn is_u64(&self) -> bool {
        self.is_int_and(|n| 0 <= n && n <= u64::MAX as i128)
    }

    /// Return the value of this [`GcValue`] if it is a text.
    pub fn to_text(self) -> Option<Arc<str>> {
        if let Self::Text(ret) = self {
            Some(ret)
        } else {
            None
        }
    }

    /// Return the value of this [`GcValue`] if it is an int.
    pub fn to_int(self) -> Option<i128> {
        if let Self::Int(ret) = self {
            Some(ret)
        } else {
            None
        }
    }

    /// Return the value of this [`GcValue`] if it is an float.
    pub fn to_float(self) -> Option<f64> {
        if let Self::Float(ret) = self {
            Some(ret)
        } else {
            None
        }
    }

    /// Return the value of this [`GcValue`] if it is an boolean.
    pub fn to_boolean(self) -> Option<bool> {
        if let Self::Boolean(ret) = self {
            Some(ret)
        } else {
            None
        }
    }

    /// Return the value of this [`GcValue`] if it is an array.
    pub fn to_array(self) -> Option<Arc<[GcValue]>> {
        if let Self::Array(ret) = self {
            Some(ret)
        } else {
            None
        }
    }

    /// Return the value of this [`GcValue`] if it is a map.
    pub fn to_map(self) -> Option<Arc<Map>> {
        if let Self::Map(ret) = self {
            Some(ret)
        } else {
            None
        }
    }

    /// Return the value of this [`GcValue`] if it is a tagged value.
    pub fn to_tag(self) -> Option<Arc<(GcValue, GcValue)>> {
        if let Self::Tag(ret) = self {
            Some(ret)
        } else {
            None
        }
    }

    /// Return the value of this [`GcValue`] if it is a bytes sequence.
    pub fn to_bytes(self) -> Option<Arc<[u8]>> {
        if let Self::Bytes(ret) = self {
            Some(ret)
        } else {
            None
        }
    }

    /// Return the value of this [`GcValue`] as `()` if it is null.
    pub fn to_null(self) -> Option<()> {
        if let Self::Null = self {
            Some(())
        } else {
            None
        }
    }
}