qubit-value 0.10.0

Type-safe containers for single, multi-valued, and named runtime values
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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
// =============================================================================
//    Copyright (c) 2025 - 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================

//! Strict typed accessors for scalar runtime values.
// qubit-style: allow source-test-pair
// Tests are intentionally distributed across behavior-specific files under
// tests/value/ rather than collected in value_accessors_tests.rs.

use std::collections::HashMap;
use std::time::Duration;

#[cfg(feature = "big-decimal")]
use bigdecimal::BigDecimal;
#[cfg(feature = "chrono")]
use chrono::{
    DateTime,
    NaiveDate,
    NaiveDateTime,
    NaiveTime,
    Utc,
};
#[cfg(feature = "big-integer")]
use num_bigint::BigInt;
#[cfg(all(feature = "converter", feature = "json"))]
use serde::Serialize;
#[cfg(all(feature = "converter", feature = "json"))]
use serde::de::DeserializeOwned;
#[cfg(feature = "url")]
use url::Url;

use qubit_datatype::DataType;
#[cfg(all(feature = "converter", feature = "json"))]
use qubit_datatype::{
    DataConversionError,
    DataFormat,
    InvalidValueReason,
};

use super::value::{
    Value,
    ValueRepr,
};
use crate::ValueMissing;
use crate::value_error::{
    ValueError,
    ValueResult,
};

macro_rules! impl_get_value {
    // Copy type: directly dereference and return
    ($(#[$attr:meta])* copy: $method:ident, $variant:ident, $type:ty, $data_type:expr) => {
        $(#[$attr])*
        #[doc = ""]
        #[doc = "# Errors"]
        #[doc = ""]
        #[doc = "Returns [`ValueError::Missing`] when the value is unset with"]
        #[doc = "the requested type, or [`ValueError::TypeMismatch`] when the"]
        #[doc = "stored data type differs."]
        #[inline(always)]
        pub fn $method(&self) -> ValueResult<$type> {
            match &self.repr {
                ValueRepr::$variant(v) => Ok(*v),
                ValueRepr::Unset(dt) if *dt == $data_type => {
                    Err(ValueError::Missing($crate::ValueMissing::UnsetScalar {
                        data_type: *dt,
                    }))
                }
                ValueRepr::Unset(dt) => Err(ValueError::TypeMismatch {
                    expected: $data_type,
                    actual: *dt,
                }),
                _ => Err(ValueError::TypeMismatch {
                    expected: $data_type,
                    actual: self.data_type(),
                }),
            }
        }
    };

    // Reference type: use conversion function to return reference,
    // fixing lifetime issues
    ($(#[$attr:meta])* ref: $method:ident, $variant:ident, $ret_type:ty, $data_type:expr, $conversion:expr) => {
        $(#[$attr])*
        #[doc = ""]
        #[doc = "# Errors"]
        #[doc = ""]
        #[doc = "Returns [`ValueError::Missing`] when the value is unset with"]
        #[doc = "the requested type, or [`ValueError::TypeMismatch`] when the"]
        #[doc = "stored data type differs."]
        #[inline(always)]
        pub fn $method(&self) -> ValueResult<$ret_type> {
            match &self.repr {
                ValueRepr::$variant(v) => {
                    let conv_fn: fn(&_) -> $ret_type = $conversion;
                    Ok(conv_fn(v))
                },
                ValueRepr::Unset(dt) if *dt == $data_type => {
                    Err(ValueError::Missing($crate::ValueMissing::UnsetScalar {
                        data_type: *dt,
                    }))
                }
                ValueRepr::Unset(dt) => Err(ValueError::TypeMismatch {
                    expected: $data_type,
                    actual: *dt,
                }),
                _ => Err(ValueError::TypeMismatch {
                    expected: $data_type,
                    actual: self.data_type(),
                }),
            }
        }
    };
}

impl Value {
    /// Creates a `Value` from a `serde_json::Value`.
    ///
    /// # Parameters
    ///
    /// * `json` - The JSON value to wrap.
    ///
    /// # Returns
    ///
    /// A `Value::Json` wrapping the given JSON value.
    #[inline(always)]
    #[cfg(feature = "json")]
    pub fn from_json_value(json: serde_json::Value) -> Self {
        Value::Json(json)
    }

    /// Creates a `Value` from any serializable value by converting it to JSON.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Any type implementing `Serialize`.
    ///
    /// # Parameters
    ///
    /// * `value` - The value to serialize into JSON.
    ///
    /// # Returns
    ///
    /// A `Value::Json` containing the serialized representation.
    ///
    /// # Errors
    ///
    /// Returns [`ValueError::Conversion`] with
    /// [`InvalidValueReason::NonFinite`] when any nested float is non-finite,
    /// or [`InvalidValueReason::Serialization`] when Serde cannot represent
    /// the input as JSON.
    #[cfg(all(feature = "converter", feature = "json"))]
    pub fn from_serializable<T: ?Sized + Serialize>(
        value: &T,
    ) -> ValueResult<Self> {
        let json = crate::strict_json::to_value(value).map_err(|error| {
            let reason = match error {
                crate::strict_json::StrictJsonError::NonFinite => {
                    InvalidValueReason::NonFinite
                }
                crate::strict_json::StrictJsonError::Serialization => {
                    InvalidValueReason::Serialization {
                        format: DataFormat::Json,
                    }
                }
            };
            ValueError::from(DataConversionError::invalid(
                DataType::Json,
                DataType::Json,
                reason,
            ))
        })?;
        Ok(Value::Json(json))
    }

    // ========================================================================
    // Type-checking getters (strict type matching)
    // ========================================================================

    impl_get_value! {
        /// Get boolean value
        ///
        /// # Returns
        ///
        /// If types match, returns the boolean value; see `# Errors`.
        ///
        /// # Examples
        ///
        /// ```rust
        /// use qubit_value::Value;
        ///
        /// let value = Value::Bool(true);
        /// assert_eq!(value.get_bool().unwrap(), true);
        /// ```
        copy: get_bool, Bool, bool, DataType::Bool
    }

    impl_get_value! {
        /// Get character value
        ///
        /// # Returns
        ///
        /// If types match, returns the character value; see `# Errors`.
        ///
        /// # Examples
        ///
        /// ```rust
        /// use qubit_value::Value;
        ///
        /// let value = Value::Char('A');
        /// assert_eq!(value.get_char().unwrap(), 'A');
        /// ```
        copy: get_char, Char, char, DataType::Char
    }

    impl_get_value! {
        /// Get int8 value
        ///
        /// # Returns
        ///
        /// If types match, returns the int8 value; see `# Errors`.
        copy: get_int8, Int8, i8, DataType::Int8
    }

    impl_get_value! {
        /// Get int16 value
        ///
        /// # Returns
        ///
        /// If types match, returns the int16 value; see `# Errors`.
        copy: get_int16, Int16, i16, DataType::Int16
    }

    impl_get_value! {
        /// Get int32 value
        ///
        /// # Returns
        ///
        /// If types match, returns the int32 value; see `# Errors`.
        copy: get_int32, Int32, i32, DataType::Int32
    }

    impl_get_value! {
        /// Get int64 value
        ///
        /// # Returns
        ///
        /// If types match, returns the int64 value; see `# Errors`.
        copy: get_int64, Int64, i64, DataType::Int64
    }

    impl_get_value! {
        /// Get int128 value
        ///
        /// # Returns
        ///
        /// If types match, returns the int128 value; see `# Errors`.
        copy: get_int128, Int128, i128, DataType::Int128
    }

    impl_get_value! {
        /// Get uint8 value
        ///
        /// # Returns
        ///
        /// If types match, returns the uint8 value; see `# Errors`.
        copy: get_uint8, UInt8, u8, DataType::UInt8
    }

    impl_get_value! {
        /// Get uint16 value
        ///
        /// # Returns
        ///
        /// If types match, returns the uint16 value; see `# Errors`.
        copy: get_uint16, UInt16, u16, DataType::UInt16
    }

    impl_get_value! {
        /// Get uint32 value
        ///
        /// # Returns
        ///
        /// If types match, returns the uint32 value; see `# Errors`.
        copy: get_uint32, UInt32, u32, DataType::UInt32
    }

    impl_get_value! {
        /// Get uint64 value
        ///
        /// # Returns
        ///
        /// If types match, returns the uint64 value; see `# Errors`.
        copy: get_uint64, UInt64, u64, DataType::UInt64
    }

    impl_get_value! {
        /// Get uint128 value
        ///
        /// # Returns
        ///
        /// If types match, returns the uint128 value; see `# Errors`.
        copy: get_uint128, UInt128, u128, DataType::UInt128
    }

    impl_get_value! {
        /// Get float32 value
        ///
        /// # Returns
        ///
        /// If types match, returns the float32 value; see `# Errors`.
        copy: get_float32, Float32, f32, DataType::Float32
    }

    impl_get_value! {
        /// Get float64 value
        ///
        /// # Returns
        ///
        /// If types match, returns the float64 value; see `# Errors`.
        copy: get_float64, Float64, f64, DataType::Float64
    }

    impl_get_value! {
        /// Get string reference
        ///
        /// # Returns
        ///
        /// If types match, returns a reference to the string; see `# Errors`.
        ///
        /// # Examples
        ///
        /// ```rust
        /// use qubit_value::Value;
        ///
        /// let value = Value::String("hello".to_string());
        /// assert_eq!(value.get_string().unwrap(), "hello");
        /// ```
        ref: get_string, String, &str, DataType::String, |s: &String| s.as_str()
    }

    #[cfg(feature = "chrono")]
    impl_get_value! {
        /// Get date value
        ///
        /// # Returns
        ///
        /// If types match, returns the date value; see `# Errors`.
        copy: get_date, Date, NaiveDate, DataType::Date
    }

    #[cfg(feature = "chrono")]
    impl_get_value! {
        /// Get time value
        ///
        /// # Returns
        ///
        /// If types match, returns the time value; see `# Errors`.
        copy: get_time, Time, NaiveTime, DataType::Time
    }

    #[cfg(feature = "chrono")]
    impl_get_value! {
        /// Get datetime value
        ///
        /// # Returns
        ///
        /// If types match, returns the datetime value; see `# Errors`.
        copy: get_datetime, DateTime, NaiveDateTime, DataType::DateTime
    }

    #[cfg(feature = "chrono")]
    impl_get_value! {
        /// Get UTC instant value
        ///
        /// # Returns
        ///
        /// If types match, returns the UTC instant value; see `# Errors`.
        copy: get_instant, Instant, DateTime<Utc>, DataType::Instant
    }

    #[cfg(feature = "big-integer")]
    impl_get_value! {
        /// Get big integer value.
        ///
        /// This method returns a cloned [`BigInt`]. Use
        /// [`Value::get_biginteger_ref`] to borrow the stored value without
        /// cloning.
        ///
        /// # Returns
        ///
        /// If types match, returns the big integer value; see `# Errors`.
        ///
        /// # Examples
        ///
        /// ```rust
        /// use qubit_value::Value;
        /// use num_bigint::BigInt;
        ///
        /// let value = Value::BigInteger(BigInt::from(123456789));
        /// assert_eq!(value.get_biginteger().unwrap(), BigInt::from(123456789));
        /// ```
        ref: get_biginteger, BigInteger, BigInt, DataType::BigInteger, |v: &BigInt| v.clone()
    }

    #[cfg(feature = "big-decimal")]
    impl_get_value! {
        /// Get big decimal value.
        ///
        /// This method returns a cloned [`BigDecimal`]. Use
        /// [`Value::get_bigdecimal_ref`] to borrow the stored value without
        /// cloning.
        ///
        /// # Returns
        ///
        /// If types match, returns the big decimal value; see `# Errors`.
        ///
        /// # Examples
        ///
        /// ```rust
        /// use std::str::FromStr;
        ///
        /// use bigdecimal::BigDecimal;
        /// use qubit_value::Value;
        ///
        /// let bd = BigDecimal::from_str("123.456").unwrap();
        /// let value = Value::BigDecimal(bd.clone());
        /// assert_eq!(value.get_bigdecimal().unwrap(), bd);
        /// ```
        ref: get_bigdecimal, BigDecimal, BigDecimal, DataType::BigDecimal, |v: &BigDecimal| v.clone()
    }

    impl_get_value! {
        /// Get Duration value
        ///
        /// # Returns
        ///
        /// If types match, returns the Duration value; see `# Errors`.
        copy: get_duration, Duration, Duration, DataType::Duration
    }

    #[cfg(feature = "url")]
    impl_get_value! {
        /// Get URL value.
        ///
        /// This method returns a cloned [`Url`]. Use [`Value::get_url_ref`] to
        /// borrow the stored value without cloning.
        ///
        /// # Returns
        ///
        /// If types match, returns the URL value; see `# Errors`.
        ref: get_url, Url, Url, DataType::Url, Url::clone
    }

    impl_get_value! {
        /// Get string map value.
        ///
        /// This method returns a cloned `HashMap<String, String>`. Use
        /// [`Value::get_string_map_ref`] to borrow the stored value without
        /// cloning.
        ///
        /// # Returns
        ///
        /// If types match, returns the string map value; see `# Errors`.
        ref: get_string_map, StringMap, HashMap<String, String>, DataType::StringMap,
            |v: &HashMap<String, String>| v.clone()
    }

    #[cfg(feature = "json")]
    impl_get_value! {
        /// Get JSON value.
        ///
        /// This method returns a cloned [`serde_json::Value`]. Use
        /// [`Value::get_json_ref`] to borrow the stored value without cloning.
        ///
        /// # Returns
        ///
        /// If types match, returns the JSON value; see `# Errors`.
        ref: get_json, Json, serde_json::Value, DataType::Json,
            |v: &serde_json::Value| v.clone()
    }

    /// Borrow the inner `BigInt` without cloning.
    ///
    /// # Returns
    ///
    /// A shared reference to the stored integer.
    ///
    /// # Errors
    ///
    /// Returns [`ValueError::Missing`] when the value is unset with
    /// `DataType::BigInteger`, or [`ValueError::TypeMismatch`] when the stored
    /// data type differs.
    #[cfg(feature = "big-integer")]
    #[inline(always)]
    pub fn get_biginteger_ref(&self) -> ValueResult<&BigInt> {
        match &self.repr {
            ValueRepr::BigInteger(v) => Ok(v),
            ValueRepr::Unset(dt) if *dt == DataType::BigInteger => {
                Err(ValueError::Missing(ValueMissing::UnsetScalar {
                    data_type: *dt,
                }))
            }
            ValueRepr::Unset(dt) => Err(ValueError::TypeMismatch {
                expected: DataType::BigInteger,
                actual: *dt,
            }),
            _ => Err(ValueError::TypeMismatch {
                expected: DataType::BigInteger,
                actual: self.data_type(),
            }),
        }
    }

    /// Borrow the inner `BigDecimal` without cloning.
    ///
    /// # Returns
    ///
    /// A shared reference to the stored decimal.
    ///
    /// # Errors
    ///
    /// Returns [`ValueError::Missing`] when the value is unset with
    /// `DataType::BigDecimal`, or [`ValueError::TypeMismatch`] when the stored
    /// data type differs.
    #[cfg(feature = "big-decimal")]
    #[inline(always)]
    pub fn get_bigdecimal_ref(&self) -> ValueResult<&BigDecimal> {
        match &self.repr {
            ValueRepr::BigDecimal(v) => Ok(v),
            ValueRepr::Unset(dt) if *dt == DataType::BigDecimal => {
                Err(ValueError::Missing(ValueMissing::UnsetScalar {
                    data_type: *dt,
                }))
            }
            ValueRepr::Unset(dt) => Err(ValueError::TypeMismatch {
                expected: DataType::BigDecimal,
                actual: *dt,
            }),
            _ => Err(ValueError::TypeMismatch {
                expected: DataType::BigDecimal,
                actual: self.data_type(),
            }),
        }
    }

    /// Borrow the inner `Url` without cloning.
    ///
    /// # Returns
    ///
    /// A shared reference to the stored URL.
    ///
    /// # Errors
    ///
    /// Returns [`ValueError::Missing`] when the value is unset with
    /// `DataType::Url`, or [`ValueError::TypeMismatch`] when the stored data
    /// type differs.
    #[cfg(feature = "url")]
    #[inline(always)]
    pub fn get_url_ref(&self) -> ValueResult<&Url> {
        match &self.repr {
            ValueRepr::Url(v) => Ok(v.as_ref()),
            ValueRepr::Unset(dt) if *dt == DataType::Url => {
                Err(ValueError::Missing(ValueMissing::UnsetScalar {
                    data_type: *dt,
                }))
            }
            ValueRepr::Unset(dt) => Err(ValueError::TypeMismatch {
                expected: DataType::Url,
                actual: *dt,
            }),
            _ => Err(ValueError::TypeMismatch {
                expected: DataType::Url,
                actual: self.data_type(),
            }),
        }
    }

    /// Borrow the inner `HashMap<String, String>` without cloning.
    ///
    /// # Returns
    ///
    /// A shared reference to the stored string map.
    ///
    /// # Errors
    ///
    /// Returns [`ValueError::Missing`] when the value is unset with
    /// `DataType::StringMap`, or [`ValueError::TypeMismatch`] when the stored
    /// data type differs.
    #[inline(always)]
    pub fn get_string_map_ref(&self) -> ValueResult<&HashMap<String, String>> {
        match &self.repr {
            ValueRepr::StringMap(v) => Ok(v),
            ValueRepr::Unset(dt) if *dt == DataType::StringMap => {
                Err(ValueError::Missing(ValueMissing::UnsetScalar {
                    data_type: *dt,
                }))
            }
            ValueRepr::Unset(dt) => Err(ValueError::TypeMismatch {
                expected: DataType::StringMap,
                actual: *dt,
            }),
            _ => Err(ValueError::TypeMismatch {
                expected: DataType::StringMap,
                actual: self.data_type(),
            }),
        }
    }

    /// Borrow the inner JSON value without cloning.
    ///
    /// # Returns
    ///
    /// A shared reference to the stored JSON value.
    ///
    /// # Errors
    ///
    /// Returns [`ValueError::Missing`] when the value is unset with
    /// `DataType::Json`, or [`ValueError::TypeMismatch`] when the stored data
    /// type differs.
    #[cfg(feature = "json")]
    #[inline(always)]
    pub fn get_json_ref(&self) -> ValueResult<&serde_json::Value> {
        match &self.repr {
            ValueRepr::Json(v) => Ok(v),
            ValueRepr::Unset(dt) if *dt == DataType::Json => {
                Err(ValueError::Missing(ValueMissing::UnsetScalar {
                    data_type: *dt,
                }))
            }
            ValueRepr::Unset(dt) => Err(ValueError::TypeMismatch {
                expected: DataType::Json,
                actual: *dt,
            }),
            _ => Err(ValueError::TypeMismatch {
                expected: DataType::Json,
                actual: self.data_type(),
            }),
        }
    }

    /// Deserialize the inner JSON value into a target type.
    ///
    /// Only works when `self` is `Value::Json(...)`.
    ///
    /// # Type Parameters
    ///
    /// * `T` - The target type implementing `DeserializeOwned`.
    ///
    /// # Returns
    ///
    /// Returns `Ok(T)` on success.
    ///
    /// # Errors
    ///
    /// Returns [`ValueError::Missing`] when this value is
    /// `Value::Unset(DataType::Json)`,
    /// [`ValueError::TypeMismatch`] when this value has a non-JSON data type,
    /// or [`ValueError::Conversion`] when JSON deserialization fails.
    #[cfg(all(feature = "converter", feature = "json"))]
    pub fn deserialize_json<T: DeserializeOwned>(&self) -> ValueResult<T> {
        match &self.repr {
            ValueRepr::Json(v) => {
                serde::Deserialize::deserialize(v).map_err(|_| {
                    ValueError::from(DataConversionError::invalid(
                        DataType::Json,
                        DataType::Json,
                        InvalidValueReason::Deserialization {
                            format: DataFormat::Json,
                        },
                    ))
                })
            }
            ValueRepr::Unset(dt) if *dt == DataType::Json => {
                Err(ValueError::Missing(ValueMissing::UnsetScalar {
                    data_type: *dt,
                }))
            }
            ValueRepr::Unset(dt) => Err(ValueError::TypeMismatch {
                expected: DataType::Json,
                actual: *dt,
            }),
            _ => Err(ValueError::TypeMismatch {
                expected: DataType::Json,
                actual: self.data_type(),
            }),
        }
    }
}