qubit-value 0.11.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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
// =============================================================================
//    Copyright (c) 2025 - 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! # Single Value Container
//!
//! Provides type-safe storage and access functionality for single values.
// qubit-style: allow multiple-public-types

use std::cmp::Ordering;
use std::collections::HashMap;
use std::fmt;
#[cfg(feature = "json")]
use std::hash::Hash;
#[cfg(feature = "json")]
use std::hash::Hasher;
use std::time::Duration;

#[cfg(feature = "big-decimal")]
use bigdecimal::BigDecimal;
#[cfg(feature = "chrono")]
use chrono::DateTime;
#[cfg(feature = "chrono")]
use chrono::NaiveDate;
#[cfg(feature = "chrono")]
use chrono::NaiveDateTime;
#[cfg(feature = "chrono")]
use chrono::NaiveTime;
#[cfg(feature = "chrono")]
use chrono::Utc;
#[cfg(feature = "big-integer")]
use num_bigint::BigInt;
#[cfg(feature = "json")]
use qubit_budget::MeasuredBudgetError;
#[cfg(feature = "json")]
use qubit_budget::ResourceQuantity;
#[cfg(feature = "json")]
use qubit_budget::json::JsonValueBudget;
#[cfg(feature = "converter")]
use qubit_datatype::ConversionLimits;
#[cfg(feature = "converter")]
use qubit_datatype::ConversionPolicy;
#[cfg(feature = "converter")]
use qubit_datatype::ConversionSession;
#[cfg(all(feature = "converter", feature = "json"))]
use qubit_datatype::DataConversionError;
#[cfg(feature = "converter")]
use qubit_datatype::DataConversionTarget;
#[cfg(all(feature = "converter", feature = "json"))]
use qubit_datatype::DataFormat;
use qubit_datatype::DataType;
#[cfg(all(feature = "converter", feature = "json"))]
use qubit_datatype::InvalidValueReason;
use qubit_datatype::NumberRef;
use qubit_datatype::NumericComparisonPolicy;
#[cfg(all(feature = "converter", feature = "json"))]
use qubit_json::encode::JsonSerializationErrorKind;
#[cfg(all(feature = "converter", feature = "json"))]
use qubit_json::value::JsonValueEncoder;
#[cfg(all(feature = "converter", feature = "json"))]
use serde::Deserialize;
#[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 super::internal::ValueRepr;
use super::value_ref::ValueRef;
use crate::IntoValueDefault;
use crate::NumericComparisonError;
use crate::ValueError;
use crate::ValueMissing;
#[cfg(feature = "json")]
use crate::identity::hash_json;
#[cfg(feature = "json")]
use crate::identity::preflight_json;
#[cfg(feature = "json")]
use crate::value::value_identity::hash_value_payload_with_json_budget;
use crate::value_error::ValueResult;

/// Single typed runtime value with private storage representation.
///
/// Construction and access are expressed through methods and conversions. The
/// concrete enum representation is private so storage optimizations do not
/// become part of the public API.
///
/// # Examples
///
/// ```
/// use qubit_value::Value;
///
/// let value = Value::from(42_i32);
/// assert_eq!(value.get_int32().unwrap(), 42);
/// ```
#[must_use]
#[derive(Clone)]
pub struct Value {
    /// Private typed storage backing the stable public accessor API.
    pub(crate) repr: ValueRepr,
}

impl fmt::Debug for Value {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.view().fmt(formatter)
    }
}

/// Implements named scalar constructors from the shared value table.
macro_rules! impl_value_constructors {
    (
        ;
        $(
            (
                [$($cfg:meta),*],
                $variant:ident,
                $type:ty,
                $data_type:expr,
                $materialization:ident,
                $json_class:ident,
                $number_projection:ident,
                $value_doc:literal,
                $multi_doc:literal
                $(, $_wire:tt)*
            )
        ),+ $(,)?
    ) => {
        impl Value {
            /// Creates an unset value with an explicit declared type.
            ///
            /// # Parameters
            ///
            /// * `data_type` - Runtime type retained while the value is unset.
            ///
            /// # Returns
            ///
            /// An unset scalar retaining `data_type`.
            #[allow(non_snake_case)]
            #[inline(always)]
            pub const fn Unset(data_type: DataType) -> Self {
                Self::new_unset(data_type)
            }

            /// Creates an unset value with an explicit declared type.
            ///
            /// # Parameters
            ///
            /// * `data_type` - Runtime type retained while the value is unset.
            ///
            /// # Returns
            ///
            /// An unset scalar retaining `data_type`.
            #[inline(always)]
            pub const fn new_unset(data_type: DataType) -> Self {
                Self { repr: ValueRepr::Unset(data_type) }
            }

            $(
                #[doc = concat!("Creates a ", $value_doc, ".")]
                ///
                /// # Parameters
                ///
                /// * `value` - Concrete payload stored by the returned scalar.
                ///
                /// # Returns
                ///
                /// A typed scalar containing `value`.
                $(#[$cfg])*
                #[allow(non_snake_case)]
                #[inline(always)]
                pub fn $variant(value: $type) -> Self {
                    Self { repr: ValueRepr::$variant(value_storage_new!($variant, value)) }
                }
            )+
        }
    };
}

/// Borrows owned storage through the shared type table.
macro_rules! owned_view_match {
    ($value:expr; $(([$($cfg:meta),*], $variant:ident, $type:ty, $data_type:expr, $materialization:ident, $json_class:ident, $number_projection:ident, $value_doc:literal, $multi_doc:literal $(, $_wire:tt)*)),+ $(,)?) => {
        match &$value.repr {
            ValueRepr::Unset(data_type) => ValueRef::Unset(*data_type),
            $($(#[$cfg])* ValueRepr::$variant(value) => ValueRef::$variant(
                value_view_payload!($variant, $number_projection, value_storage_ref!($variant, value))
            ),)+
        }
    };
}

for_each_value_type!(impl_value_constructors);

impl Value {
    /// Strictly borrows a stored scalar without allocating.
    #[must_use = "the borrowed strict value result should be handled"]
    #[inline(always)]
    pub fn get_ref<'a, T: ?Sized>(&'a self) -> ValueResult<&'a T>
    where
        &'a T: TryFrom<&'a Self, Error = ValueError>,
    {
        <&'a T>::try_from(self)
    }

    /// Hashes this value while applying `budget` to a JSON payload.
    ///
    /// # Type Parameters
    ///
    /// * `H` - Hasher receiving the semantic value identity.
    /// * `R` - Resource identifier used by the JSON budget.
    /// * `Q` - Quantity type used by the JSON budget.
    ///
    /// # Parameters
    ///
    /// * `state` - Hasher that receives the same identity representation as
    ///   [`Hash::hash`].
    /// * `budget` - Mutable JSON traversal budget, used only when this value
    ///   contains a JSON payload.
    ///
    /// # Returns
    ///
    /// `Ok(())` after the complete semantic identity is hashed.
    ///
    /// # Errors
    ///
    /// Returns [`qubit_budget::MeasuredBudgetError`] when the JSON payload
    /// exceeds a configured limit. On error, neither `state` nor the committed
    /// portion of `budget` is modified. A hasher panic also drops the
    /// staged budget transaction.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::collections::hash_map::DefaultHasher;
    ///
    /// use qubit_budget::{ResourceLimit, StructureLimits};
    /// use qubit_budget::json::{JsonResource, JsonValueBudget, JsonValueLimits};
    /// use qubit_value::Value;
    ///
    /// let value = Value::Json(serde_json::json!([null]));
    /// let structure = StructureLimits::<JsonResource, usize>::builder().nodes_limit(
    ///     ResourceLimit::new(JsonResource::Nodes, 1_usize),
    /// ).build();
    /// let mut budget = JsonValueBudget::new(
    ///     JsonValueLimits::builder().structure_limits(structure).build(),
    /// );
    /// let mut hasher = DefaultHasher::new();
    ///
    /// assert!(value.hash_with_json_budget(&mut hasher, &mut budget).is_err());
    /// drop(hasher);
    /// // The rejected value did not consume committed budget state.
    /// ```
    #[cfg(feature = "json")]
    pub fn hash_with_json_budget<H, R, Q>(
        &self,
        state: &mut H,
        budget: &mut JsonValueBudget<R, Q>,
    ) -> Result<(), MeasuredBudgetError<R, Q>>
    where
        H: Hasher,
        R: Clone,
        Q: ResourceQuantity,
    {
        match &self.repr {
            ValueRepr::Json(value) => {
                let mut transaction = budget.transaction();
                preflight_json(value, &mut transaction)?;
                std::mem::discriminant(&self.repr).hash(state);
                hash_json(value, state);
                transaction.commit()
            }
            _ => {
                std::mem::discriminant(&self.repr).hash(state);
                hash_value_payload_with_json_budget(&self.repr, state, budget)
            }
        }
    }

    /// Borrows the stable semantic view of this value.
    ///
    /// # Returns
    ///
    /// A non-owning view that hides private storage representation details.
    #[must_use = "the borrowed value view should be used"]
    #[inline(always)]
    pub fn view(&self) -> ValueRef<'_> {
        for_each_value_type!(owned_view_match, self)
    }
}

/// Maps private scalar storage variants to their runtime data types.
macro_rules! value_data_type_match {
    ($value:expr; $(([$($cfg:meta),*], $variant:ident, $type:ty, $data_type:expr, $materialization:ident, $json_class:ident, $number_projection:ident, $value_doc:literal, $multi_doc:literal $(, $_wire:tt)*)),+ $(,)?) => {
        match &$value.repr {
            ValueRepr::Unset(data_type) => *data_type,
            $($(#[$cfg])* ValueRepr::$variant(_) => $data_type,)+
        }
    };
}

// ============================================================================
// Getter method generation macro
// ============================================================================

/// Unified getter generation macro
///
/// Supports two modes:
/// 1. `copy:` - For types implementing the Copy trait, directly returns the
///    value
/// 2. `ref:` - For non-Copy types, returns a reference
///
/// # Documentation Comment Support
///
/// The macro automatically extracts preceding documentation comments, so
/// you can add `///` comments before macro invocations.
impl Value {
    /// Generic constructor method
    ///
    /// Creates a `Value` from any supported type, avoiding direct use of
    /// enum variants.
    ///
    /// # Supported Generic Types
    ///
    /// `Value::new<T>(value)` currently supports the following `T`:
    ///
    /// - `bool`
    /// - `char`
    /// - `i8`, `i16`, `i32`, `i64`, `i128`
    /// - `u8`, `u16`, `u32`, `u64`, `u128`
    /// - `f32`, `f64`
    /// - `String`, `&str`
    /// - `NaiveDate`, `NaiveTime`, `NaiveDateTime`, `DateTime<Utc>`
    /// - `BigInt`, `BigDecimal`
    /// - `Duration`
    /// - `Url`
    /// - `HashMap<String, String>`
    /// - `serde_json::Value`
    ///
    /// # Type Parameters
    ///
    /// * `T` - The type of the value to wrap
    ///
    /// # Parameters
    ///
    /// * `value` - Value to wrap.
    ///
    /// # Returns
    ///
    /// Returns a `Value` wrapping the given value
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qubit_value::Value;
    ///
    /// // Basic types
    /// let v = Value::new(42i32);
    /// assert_eq!(v.get_int32().unwrap(), 42);
    ///
    /// let v = Value::new(true);
    /// assert_eq!(v.get_bool().unwrap(), true);
    ///
    /// // String
    /// let v = Value::new("hello".to_string());
    /// assert_eq!(v.get_string().unwrap(), "hello");
    /// ```
    #[inline(always)]
    pub fn new<T>(value: T) -> Self
    where
        T: Into<Self>,
    {
        value.into()
    }

    /// Generic getter method.
    ///
    /// Performs a strict typed read of the stored value as `T`.
    ///
    /// `get<T>()` performs strict type matching. It does not do cross-type
    /// conversion.
    ///
    /// For example, `Value::Int32(42).get::<i64>()` fails, while
    /// `Value::Int32(42).to::<i64>()` succeeds.
    ///
    /// # Supported Generic Types
    ///
    /// `Value::get<T>()` currently supports the following `T`:
    ///
    /// - `bool`
    /// - `char`
    /// - `i8`, `i16`, `i32`, `i64`, `i128`
    /// - `u8`, `u16`, `u32`, `u64`, `u128`
    /// - `f32`, `f64`
    /// - `String`
    /// - `NaiveDate`, `NaiveTime`, `NaiveDateTime`, `DateTime<Utc>`
    /// - `BigInt`, `BigDecimal`
    /// - `Duration`
    /// - `Url`
    /// - `HashMap<String, String>`
    /// - `serde_json::Value`
    ///
    /// # Type Parameters
    ///
    /// * `T` - The target type to retrieve
    ///
    /// # Returns
    ///
    /// Returns the stored value when its type matches `T`.
    ///
    /// # Errors
    ///
    /// Returns [`ValueError::Missing`] when the value is unset with the
    /// requested type, or [`ValueError::TypeMismatch`] when the stored type
    /// differs from `T`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qubit_value::Value;
    ///
    /// let value = Value::Int32(42);
    ///
    /// // Through type inference
    /// let num: i32 = value.get().unwrap();
    /// assert_eq!(num, 42);
    ///
    /// // Explicitly specify type parameter
    /// let num = value.get::<i32>().unwrap();
    /// assert_eq!(num, 42);
    ///
    /// // Different type
    /// let text = Value::String("hello".to_string());
    /// let s: String = text.get().unwrap();
    /// assert_eq!(s, "hello");
    ///
    /// // Boolean value
    /// let flag = Value::Bool(true);
    /// let b: bool = flag.get().unwrap();
    /// assert_eq!(b, true);
    /// ```
    #[must_use = "the strict value read result should be handled"]
    #[inline(always)]
    pub fn get<T>(&self) -> ValueResult<T>
    where
        for<'a> T: TryFrom<&'a Self, Error = ValueError>,
    {
        T::try_from(self)
    }

    /// Generic getter method with a default value.
    ///
    /// Returns the supplied default only when this value is unset. Type
    /// mismatches and conversion errors are still returned as errors.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Target type for the strict read and default value.
    ///
    /// # Parameters
    ///
    /// * `default` - Lazily materialized value used only when `self` is unset.
    ///
    /// # Returns
    ///
    /// The stored value, or `default` when the value is unset.
    ///
    /// # Errors
    ///
    /// Returns [`ValueError::TypeMismatch`] when the stored type differs from
    /// `T`.
    #[must_use = "the strict value read result should be handled"]
    #[inline(always)]
    pub fn get_or<T>(&self, default: impl IntoValueDefault<T>) -> ValueResult<T>
    where
        for<'a> T: TryFrom<&'a Self, Error = ValueError>,
    {
        match self.get() {
            Err(ValueError::Missing(missing)) if missing.is_defaultable_for_strict_read() => {
                Ok(default.into_value_default())
            }
            result => result,
        }
    }

    /// Strictly reads this value or calls `default` only when it is unset.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Target type for the strict read and fallback value.
    /// * `F` - Deferred fallback producing `T`.
    ///
    /// # Parameters
    ///
    /// * `default` - Callback invoked only when this value is unset.
    ///
    /// # Returns
    ///
    /// The stored value, or the callback result for an unset value.
    ///
    /// # Errors
    ///
    /// Returns [`ValueError::TypeMismatch`] when the stored type differs from
    /// `T`; the callback is not invoked in that case.
    #[must_use = "the strict value read result should be handled"]
    #[inline(always)]
    pub fn get_or_else<T, F>(&self, default: F) -> ValueResult<T>
    where
        for<'a> T: TryFrom<&'a Self, Error = ValueError>,
        F: FnOnce() -> T,
    {
        match self.get() {
            Err(ValueError::Missing(missing)) if missing.is_defaultable_for_strict_read() => Ok(default()),
            result => result,
        }
    }

    /// Converts the stored value to another supported data type.
    ///
    /// This method delegates to the authoritative conversion contract in
    /// [`qubit-datatype`](https://docs.rs/qubit-datatype/latest/qubit_datatype/).
    /// The enabled rich-type features determine which source and target
    /// families are available. An unset value is reported as a structured
    /// missing-value conversion error.
    ///
    /// Unlike [`Self::get`], this method permits conversions supported by
    /// [`qubit_datatype::DataConverter`] and applies
    /// [`qubit_datatype::ConversionPolicy`] and
    /// [`qubit_datatype::ConversionLimits`].
    ///
    /// # Type Parameters
    ///
    /// * `T` - Target type supported by the shared conversion layer.
    ///
    /// # Returns
    ///
    /// The converted value.
    ///
    /// # Errors
    ///
    /// Returns a mapped conversion error when the value is unset, the
    /// conversion is unsupported, or the source is invalid for `T`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qubit_value::Value;
    ///
    /// let value = Value::Int32(42);
    /// assert_eq!(value.to::<i64>().unwrap(), 42);
    /// assert_eq!(value.to::<String>().unwrap(), "42");
    /// ```
    #[inline(always)]
    #[cfg(feature = "converter")]
    pub fn to<T>(&self) -> ValueResult<T>
    where
        T: DataConversionTarget,
    {
        self.to_with(ConversionPolicy::default_ref(), ConversionLimits::default_ref())
    }

    /// Converts this value to `T`, or returns `default` when storage is unset
    /// or conversion reports a missing value.
    ///
    /// Conversion failures from concrete values are preserved.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Target conversion type.
    ///
    /// # Parameters
    ///
    /// * `default` - Lazily materialized value used for unset or conversion-
    ///   missing storage.
    ///
    /// # Returns
    ///
    /// The converted value, or `default` for an unset or conversion-missing
    /// value.
    ///
    /// # Errors
    ///
    /// Returns a mapped conversion error for concrete values that cannot be
    /// converted to `T`.
    #[inline]
    #[cfg(feature = "converter")]
    pub fn to_or<T>(&self, default: impl IntoValueDefault<T>) -> ValueResult<T>
    where
        T: DataConversionTarget,
    {
        match self.to() {
            Err(ValueError::Missing(missing)) if missing.is_defaultable_for_conversion() => {
                Ok(default.into_value_default())
            }
            result => result,
        }
    }

    /// Converts this value to `T`, or calls `default` when storage is unset or
    /// conversion reports a missing value.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Target conversion type.
    /// * `F` - Deferred fallback producing `T`.
    ///
    /// # Parameters
    ///
    /// * `default` - Callback invoked only when conversion reports a missing
    ///   value.
    ///
    /// # Returns
    ///
    /// The converted value, or the callback result for an unset or
    /// conversion-missing value.
    ///
    /// # Errors
    ///
    /// Preserves conversion errors from concrete values without invoking the
    /// callback.
    #[inline]
    #[cfg(feature = "converter")]
    pub fn to_or_else<T, F>(&self, default: F) -> ValueResult<T>
    where
        T: DataConversionTarget,
        F: FnOnce() -> T,
    {
        match self.to() {
            Err(ValueError::Missing(missing)) if missing.is_defaultable_for_conversion() => Ok(default()),
            result => result,
        }
    }

    /// Converts this value to `T` using the provided conversion policy and
    /// limits.
    ///
    /// This method uses the shared [`qubit_datatype`] conversion layer
    /// directly, so policy settings such as string trimming, blank string
    /// handling, and boolean aliases are applied consistently with other
    /// value containers.
    ///
    /// # Type Parameters
    ///
    /// * `T` - The target type to convert to.
    ///
    /// # Parameters
    ///
    /// * `policy` - Conversion policy forwarded to the shared converter.
    /// * `limits` - Conversion limits forwarded to the shared converter.
    ///
    /// # Returns
    ///
    /// Returns the converted value on success.
    ///
    /// # Errors
    ///
    /// Returns a [`crate::ValueError`] when the value is missing, unsupported,
    /// or invalid for `T` under the provided policy and limits.
    #[inline(always)]
    #[cfg(feature = "converter")]
    pub fn to_with<T>(&self, policy: &ConversionPolicy, limits: &ConversionLimits) -> ValueResult<T>
    where
        T: DataConversionTarget,
    {
        super::value_converters::convert_with_data_converter_with(self, policy, limits)
    }

    /// Converts this value to `T` while charging an existing conversion
    /// session.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Target type supported by the shared conversion layer.
    ///
    /// # Parameters
    ///
    /// * `session` - Caller-owned session providing policy, limits, and budget.
    ///
    /// # Returns
    ///
    /// The converted value.
    ///
    /// # Errors
    ///
    /// Returns a mapped conversion error when the value is missing,
    /// unsupported, invalid, or exceeds the session budget.
    #[inline(always)]
    #[cfg(feature = "converter")]
    pub fn to_in<T>(&self, session: &mut ConversionSession<'_>) -> ValueResult<T>
    where
        T: DataConversionTarget,
    {
        super::value_converters::convert_with_data_converter_in(self, session)
    }

    /// Converts this value to `T` using conversion policy and limits, or
    /// returns `default` when storage is unset or conversion reports a
    /// missing value.
    ///
    /// Conversion failures from concrete values are preserved.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Target conversion type.
    ///
    /// # Parameters
    ///
    /// * `default` - Lazily materialized value used for unset or conversion-
    ///   missing storage.
    /// * `policy` - Conversion policy forwarded to the shared converter.
    /// * `limits` - Conversion limits forwarded to the shared converter.
    ///
    /// # Returns
    ///
    /// The converted value, or `default` for an unset or conversion-missing
    /// value.
    ///
    /// # Errors
    ///
    /// Returns a mapped conversion error for concrete values that cannot be
    /// converted under the provided policy and limits.
    #[inline]
    #[cfg(feature = "converter")]
    pub fn to_or_with<T>(
        &self,
        default: impl IntoValueDefault<T>,
        policy: &ConversionPolicy,
        limits: &ConversionLimits,
    ) -> ValueResult<T>
    where
        T: DataConversionTarget,
    {
        match self.to_with(policy, limits) {
            Err(ValueError::Missing(missing)) if missing.is_defaultable_for_conversion() => {
                Ok(default.into_value_default())
            }
            result => result,
        }
    }

    /// Converts this value with the provided policy and limits, or calls
    /// `default` when storage is unset or conversion reports a missing
    /// value.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Target conversion type.
    /// * `F` - Deferred fallback producing `T`.
    ///
    /// # Parameters
    ///
    /// * `default` - Callback invoked only for a missing source value.
    /// * `policy` - Conversion policy forwarded to the shared converter.
    /// * `limits` - Conversion limits forwarded to the shared converter.
    ///
    /// # Returns
    ///
    /// The converted value, or the callback result for an unset or
    /// conversion-missing value.
    ///
    /// # Errors
    ///
    /// Preserves concrete-value conversion errors without invoking the
    /// callback.
    #[inline]
    #[cfg(feature = "converter")]
    pub fn to_or_else_with<T, F>(
        &self,
        default: F,
        policy: &ConversionPolicy,
        limits: &ConversionLimits,
    ) -> ValueResult<T>
    where
        T: DataConversionTarget,
        F: FnOnce() -> T,
    {
        match self.to_with(policy, limits) {
            Err(ValueError::Missing(missing)) if missing.is_defaultable_for_conversion() => Ok(default()),
            result => result,
        }
    }

    /// Generic setter method
    ///
    /// Replaces the current value with any supported input value.
    ///
    /// This operation updates the stored type to `T` when needed. It does not
    /// perform runtime type-mismatch validation against the previous variant.
    ///
    /// # Supported Generic Types
    ///
    /// `Value::set<T>(value)` currently supports the following `T`:
    ///
    /// - `bool`
    /// - `char`
    /// - `i8`, `i16`, `i32`, `i64`, `i128`
    /// - `u8`, `u16`, `u32`, `u64`, `u128`
    /// - `f32`, `f64`
    /// - `String`, `&str`
    /// - `NaiveDate`, `NaiveTime`, `NaiveDateTime`, `DateTime<Utc>`
    /// - `BigInt`, `BigDecimal`
    /// - `Duration`
    /// - `Url`
    /// - `HashMap<String, String>`
    /// - `serde_json::Value`
    ///
    /// # Type Parameters
    ///
    /// * `T` - Input type convertible into [`Value`].
    ///
    /// # Parameters
    ///
    /// * `value` - The value to set
    ///
    /// # Compile-time restriction
    ///
    /// Unsupported input types fail to compile because they do not implement
    /// `Into<Value>`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qubit_datatype::DataType;
    /// use qubit_value::Value;
    ///
    /// let mut value = Value::Unset(DataType::Int32);
    ///
    /// // Through type inference
    /// value.set(42i32);
    /// assert_eq!(value.get_int32().unwrap(), 42);
    ///
    /// // Explicitly specify type parameter
    /// value.set::<i32>(100);
    /// assert_eq!(value.get_int32().unwrap(), 100);
    ///
    /// // String type
    /// let mut text = Value::Unset(DataType::String);
    /// text.set("hello".to_string());
    /// assert_eq!(text.get_string().unwrap(), "hello");
    /// ```
    #[inline(always)]
    pub fn set<T>(&mut self, value: T)
    where
        T: Into<Self>,
    {
        *self = value.into();
    }

    /// Get the data type of the value
    ///
    /// # Returns
    ///
    /// Returns the data type corresponding to this value
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qubit_datatype::DataType;
    /// use qubit_value::Value;
    ///
    /// let value = Value::Int32(42);
    /// assert_eq!(value.data_type(), DataType::Int32);
    ///
    /// let empty = Value::Unset(DataType::String);
    /// assert_eq!(empty.data_type(), DataType::String);
    /// ```
    ///
    /// ```compile_fail
    /// #![deny(unused_must_use)]
    /// use qubit_value::Value;
    ///
    /// Value::new(42_i32).data_type();
    /// ```
    #[must_use = "the runtime data type should be used"]
    #[inline(always)]
    pub fn data_type(&self) -> DataType {
        for_each_value_type!(value_data_type_match, self)
    }

    /// Tests whether this container has no concrete value.
    ///
    /// # Returns
    ///
    /// Returns `true` only for [`Value::Unset`]. An empty string, map, or JSON
    /// container is still a concrete value and returns `false`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qubit_datatype::DataType;
    /// use qubit_value::Value;
    ///
    /// let value = Value::Int32(42);
    /// assert!(!value.is_unset());
    ///
    /// let empty = Value::Unset(DataType::String);
    /// assert!(empty.is_unset());
    /// ```
    #[inline(always)]
    #[must_use]
    pub fn is_unset(&self) -> bool {
        matches!(self.repr, ValueRepr::Unset(_))
    }

    /// Tests whether a concrete value belongs to the numeric type family.
    ///
    /// An unset value returns `false`, even when its declared type is numeric.
    ///
    /// # Returns
    ///
    /// `true` for concrete numeric variants; otherwise `false`.
    #[inline(always)]
    #[must_use]
    pub fn is_numeric(&self) -> bool {
        !self.is_unset() && self.data_type().is_numeric()
    }

    /// Removes the concrete value while preserving its declared data type.
    #[inline(always)]
    pub fn unset(&mut self) {
        *self = Value::new_unset(self.data_type());
    }

    /// Set the data type
    ///
    /// If the new type differs from the current type, clears the value
    /// and sets the new type.
    ///
    /// # Parameters
    ///
    /// * `data_type` - The data type to set
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qubit_datatype::DataType;
    /// use qubit_value::Value;
    ///
    /// let mut value = Value::Int32(42);
    /// value.set_type(DataType::String);
    /// assert!(value.is_unset());
    /// assert_eq!(value.data_type(), DataType::String);
    /// ```
    #[inline(always)]
    pub fn set_type(&mut self, data_type: DataType) {
        if self.data_type() != data_type {
            *self = Value::new_unset(data_type);
        }
    }
}

#[cfg(all(feature = "converter", feature = "json"))]
impl Value {
    /// Projects this typed value to its natural JSON representation.
    ///
    /// This differs from the tagged [`crate::ValueWireV1`] representation: for
    /// example, `Value::Int32(42)` projects to the JSON number `42`.
    ///
    /// # Returns
    ///
    /// The natural JSON representation of this value.
    ///
    /// # Errors
    ///
    /// Returns a structured conversion error for values JSON cannot represent,
    /// including non-finite floating-point values and inexact durations.
    #[inline(always)]
    pub fn to_json_value(&self) -> ValueResult<serde_json::Value> {
        self.to_json_value_with(ConversionPolicy::default_ref(), ConversionLimits::default_ref())
    }

    /// Projects this typed value using explicit conversion policy and limits.
    ///
    /// # Parameters
    ///
    /// * `policy` - Controls duration units and precision-loss behavior.
    /// * `limits` - Bounds conversion resource consumption.
    ///
    /// # Returns
    ///
    /// The natural JSON representation of this value.
    ///
    /// # Errors
    ///
    /// Returns a structured conversion error when JSON projection or duration
    /// formatting violates the requested policy or limits.
    #[inline(always)]
    pub fn to_json_value_with(
        &self,
        policy: &ConversionPolicy,
        limits: &ConversionLimits,
    ) -> ValueResult<serde_json::Value> {
        crate::json::value_to_json_value_with(self, policy, limits)
    }
}

/// Implements one strict typed getter from the shared value table.
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."]
        #[must_use = "the strict value read result should be handled"]
        #[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::unset_scalar(*dt, *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."]
        #[must_use = "the strict value read result should be handled"]
        #[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::unset_scalar(*dt, *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
    /// A non-finite reason is returned when any nested float is non-finite, an
    /// out-of-range reason when an integer exceeds the strict JSON range, or a
    /// serialization reason for every other unsupported Serde representation.
    #[cfg(all(feature = "converter", feature = "json"))]
    pub fn from_serializable<T: ?Sized + Serialize>(value: &T) -> ValueResult<Self> {
        let json = JsonValueEncoder::new().encode(value).map_err(|error| {
            let reason = match error.kind() {
                JsonSerializationErrorKind::NonFiniteFloat => InvalidValueReason::NonFinite,
                JsonSerializationErrorKind::IntegerOutOfRange { .. } => InvalidValueReason::OutOfRange,
                _ => 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")]
    #[must_use = "the strict value read result should be handled"]
    #[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::unset_scalar(*dt, *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")]
    #[must_use = "the strict value read result should be handled"]
    #[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::unset_scalar(*dt, *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")]
    #[must_use = "the strict value read result should be handled"]
    #[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::unset_scalar(*dt, *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.
    #[must_use = "the strict value read result should be handled"]
    #[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::unset_scalar(*dt, *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")]
    #[must_use = "the strict value read result should be handled"]
    #[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::unset_scalar(*dt, *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) => 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::unset_scalar(*dt, *dt)))
            }
            ValueRepr::Unset(dt) => Err(ValueError::TypeMismatch {
                expected: DataType::Json,
                actual: *dt,
            }),
            _ => Err(ValueError::TypeMismatch {
                expected: DataType::Json,
                actual: self.data_type(),
            }),
        }
    }
}

/// Projects one stored value according to its type-table numeric strategy.
macro_rules! project_number_ref {
    (number_copy, $value:expr) => {
        Some(NumberRef::from(*$value))
    };
    (number_ref, $value:expr) => {
        Some(NumberRef::from($value))
    };
    (not_number, $value:expr) => {{
        let _ = $value;
        None
    }};
}

/// Generates the exhaustive numeric projection from the value type table.
macro_rules! value_number_ref_match {
    ($value:expr; $(([$($cfg:meta),*], $variant:ident, $type:ty, $data_type:expr, $materialization:ident, $json_class:ident, $number_projection:ident, $value_doc:literal, $multi_doc:literal $(, $_wire:tt)*)),+ $(,)?) => {
        match &$value.repr {
            ValueRepr::Unset(_) => None,
            $(
                $(#[$cfg])*
                ValueRepr::$variant(value) => {
                    project_number_ref!($number_projection, value)
                }
            )+
        }
    };
}

impl Value {
    /// Tests whether this value is a concrete floating-point NaN.
    ///
    /// Non-floating-point values and unset values return `false`.
    ///
    /// # Returns
    ///
    /// `true` only for concrete `Float32` or `Float64` NaN values.
    #[inline(always)]
    #[must_use]
    pub fn is_nan(&self) -> bool {
        self.as_number_ref().is_some_and(|value| value.is_nan())
    }

    /// Compares concrete numeric values across representation variants.
    ///
    /// This operation is separate from [`PartialEq`]: equality preserves enum
    /// representation identity, while numeric comparison compares mathematical
    /// values under an explicit policy.
    ///
    /// [`NumericComparisonPolicy::Approximate`] orders primitive infinities
    /// separately. When a finite primitive float participates, it attempts to
    /// project both operands to finite `f64` values; if either operand cannot
    /// be projected that way, comparison falls back to the exact path.
    /// Projected comparison is pair-dependent and not transitive across
    /// mixed representations. Do not use it to implement [`Ord`], sort or
    /// group values, or construct ordered-map or ordered-set keys. Use
    /// [`NumericComparisonPolicy::Exact`] for deterministic ordering.
    ///
    /// Validation is deterministic: missing operands are checked from left to
    /// right, followed by concrete operand types from left to right, and then
    /// NaN positions.
    ///
    /// # Parameters
    ///
    /// * `other` - Right numeric operand.
    /// * `policy` - Exact or approximate numeric comparison policy.
    ///
    /// # Returns
    ///
    /// The mathematical ordering of the two concrete, non-NaN numeric
    /// operands.
    ///
    /// # Errors
    ///
    /// Returns [`NumericComparisonError::LeftMissing`] or
    /// [`NumericComparisonError::RightMissing`] when the corresponding operand
    /// is unset. Returns [`NumericComparisonError::LeftNotNumeric`] or
    /// [`NumericComparisonError::RightNotNumeric`] when the corresponding
    /// concrete operand is not numeric. Returns
    /// [`NumericComparisonError::LeftNaN`],
    /// [`NumericComparisonError::RightNaN`], or
    /// [`NumericComparisonError::BothNaN`] according to the position of NaN
    /// operands. Missing operands are checked left-to-right, then concrete
    /// operand types are checked left-to-right, and finally NaN positions are
    /// classified. After these checks the lower-level comparator must be able
    /// to order the remaining numeric operands.
    pub fn numeric_cmp(
        &self,
        other: &Self,
        policy: NumericComparisonPolicy,
    ) -> Result<Ordering, NumericComparisonError> {
        if let ValueRepr::Unset(declared) = &self.repr {
            return Err(NumericComparisonError::LeftMissing { declared: *declared });
        }
        if let ValueRepr::Unset(declared) = &other.repr {
            return Err(NumericComparisonError::RightMissing { declared: *declared });
        }

        let left = self
            .as_number_ref()
            .ok_or_else(|| NumericComparisonError::LeftNotNumeric {
                actual: self.data_type(),
            })?;
        let right = other
            .as_number_ref()
            .ok_or_else(|| NumericComparisonError::RightNotNumeric {
                actual: other.data_type(),
            })?;

        match (left.is_nan(), right.is_nan()) {
            (true, true) => return Err(NumericComparisonError::BothNaN),
            (true, false) => return Err(NumericComparisonError::LeftNaN),
            (false, true) => return Err(NumericComparisonError::RightNaN),
            (false, false) => {}
        }

        match left.compare(right, policy) {
            Some(ordering) => Ok(ordering),
            None => unreachable!("validated non-NaN numeric values must be orderable"),
        }
    }

    /// Borrows this value as a lower-level numeric representation.
    ///
    /// # Returns
    ///
    /// A borrowed numeric representation for every concrete numeric variant,
    /// or `None` for unset and non-numeric variants.
    #[must_use]
    fn as_number_ref(&self) -> Option<NumberRef<'_>> {
        for_each_value_type!(value_number_ref_match, self)
    }
}