qubit-value 0.13.1

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
// =============================================================================
//    Copyright (c) 2025 - 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================

//! Explicit scalar-or-collection value storage.

use std::mem::replace;
use std::slice::from_ref;

#[cfg(feature = "converter")]
use qubit_datatype::ConversionLimits;
#[cfg(feature = "converter")]
use qubit_datatype::ConversionPolicy;
#[cfg(feature = "converter")]
use qubit_datatype::ConversionSession;
#[cfg(feature = "converter")]
use qubit_datatype::DataConversionTarget;
use qubit_datatype::DataType;
#[cfg(feature = "converter")]
use qubit_datatype::ScalarStringDataConverters;
#[cfg(all(feature = "converter", feature = "json"))]
use serde_json::Value as JsonValue;

use crate::MultiValues;
use crate::StrictValueRead;
use crate::Value;
use crate::ValueError;
use crate::ValueResult;
use crate::multi_values::MultiValuesRepr;
#[cfg(feature = "converter")]
use crate::value::ValueRef;
use crate::value::ValueRepr;

/// A typed value whose scalar or collection shape is explicit.
///
/// The shape is never inferred from collection length. In particular,
/// `Scalar(Value::Int32(42))` and
/// `Collection(MultiValues::Int32(vec![42]))` remain distinguishable through
/// conversion and serialization boundaries.
///
/// # Examples
///
/// ```
/// use qubit_value::ValueContainer;
///
/// let scalar = ValueContainer::from(42_i32);
/// let collection = ValueContainer::from(vec![42_i32]);
/// assert!(scalar.is_scalar());
/// assert!(collection.is_collection());
/// ```
#[must_use]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ValueContainer {
    /// One typed value.
    Scalar(
        /// Stored scalar value.
        Value,
    ),
    /// A homogeneous typed collection.
    Collection(
        /// Stored homogeneous collection.
        MultiValues,
    ),
}

/// Implements scalar and collection conversions from the shared value table.
macro_rules! impl_value_container_from_table {
    (
        ;
        $(
            (
                [$($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)*
            )
        ),+ $(,)?
    ) => {
        $(
            $(#[$cfg])*
            $(#[cfg_attr(docsrs, doc($cfg))])*
            impl From<$type> for ValueContainer {
                /// Creates a scalar container by taking ownership of `value`.
                ///
                /// # Parameters
                ///
                /// * `value` - Input converted with the ownership behavior described above.
                ///
                /// # Returns
                ///
                /// A container preserving the input data type and scalar or collection shape.
                #[inline(always)]
                fn from(value: $type) -> Self {
                    Self::Scalar(Value::$variant(value))
                }
            }

            $(#[$cfg])*
            $(#[cfg_attr(docsrs, doc($cfg))])*
            impl From<Vec<$type>> for ValueContainer {
                /// Takes ownership of the vector and its element storage without cloning elements.
                /// An empty vector creates a concrete empty collection.
                ///
                /// # Parameters
                ///
                /// * `values` - Input converted with the ownership behavior described above.
                ///
                /// # Returns
                ///
                /// A container preserving the input data type and scalar or collection shape.
                #[inline(always)]
                fn from(values: Vec<$type>) -> Self {
                    Self::Collection(MultiValues::$variant(values))
                }
            }

            $(#[$cfg])*
            $(#[cfg_attr(docsrs, doc($cfg))])*
            impl From<&[$type]> for ValueContainer {
                /// Clones the elements into an owned collection, preserving order.
                /// An empty slice creates a concrete empty collection.
                ///
                /// # Parameters
                ///
                /// * `values` - Input converted with the ownership behavior described above.
                ///
                /// # Returns
                ///
                /// A container preserving the input data type and scalar or collection shape.
                #[inline]
                fn from(values: &[$type]) -> Self {
                    Self::Collection(MultiValues::$variant(values.to_vec()))
                }
            }

            $(#[$cfg])*
            $(#[cfg_attr(docsrs, doc($cfg))])*
            impl From<&Vec<$type>> for ValueContainer {
                /// Clones the elements into an owned collection, preserving order.
                /// An empty vector creates a concrete empty collection.
                ///
                /// # Parameters
                ///
                /// * `values` - Input converted with the ownership behavior described above.
                ///
                /// # Returns
                ///
                /// A container preserving the input data type and scalar or collection shape.
                #[inline]
                fn from(values: &Vec<$type>) -> Self {
                    Self::Collection(MultiValues::$variant(values.clone()))
                }
            }

            $(#[$cfg])*
            $(#[cfg_attr(docsrs, doc($cfg))])*
            impl<const N: usize> From<[$type; N]> for ValueContainer {
                /// Moves the array elements into a newly allocated vector, preserving order.
                /// An empty array creates a concrete empty collection.
                ///
                /// # Type Parameters
                ///
                /// * `N` - Number of input array elements.
                ///
                /// # Parameters
                ///
                /// * `values` - Input converted with the ownership behavior described above.
                ///
                /// # Returns
                ///
                /// A container preserving the input data type and scalar or collection shape.
                #[inline]
                fn from(values: [$type; N]) -> Self {
                    Self::Collection(MultiValues::$variant(Vec::from(values)))
                }
            }

            $(#[$cfg])*
            $(#[cfg_attr(docsrs, doc($cfg))])*
            impl<const N: usize> From<&[$type; N]> for ValueContainer {
                /// Clones the elements into an owned collection, preserving order.
                /// An empty array creates a concrete empty collection.
                ///
                /// # Type Parameters
                ///
                /// * `N` - Number of input array elements.
                ///
                /// # Parameters
                ///
                /// * `values` - Input converted with the ownership behavior described above.
                ///
                /// # Returns
                ///
                /// A container preserving the input data type and scalar or collection shape.
                #[inline]
                fn from(values: &[$type; N]) -> Self {
                    Self::Collection(MultiValues::$variant(values.to_vec()))
                }
            }
        )+
    };
}

for_each_value_type!(impl_value_container_from_table);

/// Builds a typed collection from one or two same-typed scalar values.
macro_rules! value_container_pair_match {
    ($first:expr, $second: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 ($first.repr, $second.repr) {
            $(
                $(#[$cfg])*
                (ValueRepr::$variant(first), ValueRepr::$variant(second)) => {
                    MultiValues::$variant(vec![
                        value_storage_into_multi!($variant, first),
                        value_storage_into_multi!($variant, second),
                    ])
                }
            )+
            $(
                $(#[$cfg])*
                (ValueRepr::Unset(_), ValueRepr::$variant(second)) => {
                    MultiValues::$variant(vec![value_storage_into_multi!($variant, second)])
                }
            )+
            _ => unreachable!(),
        }
    };
}

/// Pushes a same-typed scalar directly into collection storage.
macro_rules! value_container_push_match {
    ($collection:expr, $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 (&mut $collection.repr, $value.repr) {
            $(
                $(#[$cfg])*
                (MultiValuesRepr::$variant(values), ValueRepr::$variant(value)) => {
                    values.push(value_storage_into_multi!($variant, value))
                },
            )+
            $(
                $(#[$cfg])*
                (slot @ MultiValuesRepr::Unset(_), ValueRepr::$variant(value)) => {
                    *slot = MultiValuesRepr::$variant(vec![value_storage_into_multi!($variant, value)]);
                }
            )+
            _ => unreachable!(),
        }
    };
}

impl From<&str> for ValueContainer {
    /// Copies the text into an owned scalar string.
    ///
    /// # Parameters
    ///
    /// * `value` - Input converted with the ownership behavior described above.
    ///
    /// # Returns
    ///
    /// A container preserving the input data type and scalar or collection
    /// shape.
    #[inline]
    fn from(value: &str) -> Self {
        Self::Scalar(Value::String(value.to_string()))
    }
}

impl<'a> From<Vec<&'a str>> for ValueContainer {
    /// Copies each string into an owned collection, preserving order.
    /// An empty vector creates a concrete empty collection.
    ///
    /// # Parameters
    ///
    /// * `values` - Input converted with the ownership behavior described
    ///   above.
    ///
    /// # Returns
    ///
    /// A container preserving the input data type and scalar or collection
    /// shape.
    #[inline]
    fn from(values: Vec<&'a str>) -> Self {
        Self::Collection(MultiValues::from(values))
    }
}

impl<'a, 'b> From<&'a [&'b str]> for ValueContainer {
    /// Copies each string into an owned collection, preserving order.
    /// An empty slice creates a concrete empty collection.
    ///
    /// # Parameters
    ///
    /// * `values` - Input converted with the ownership behavior described
    ///   above.
    ///
    /// # Returns
    ///
    /// A container preserving the input data type and scalar or collection
    /// shape.
    #[inline]
    fn from(values: &'a [&'b str]) -> Self {
        Self::Collection(MultiValues::from(values))
    }
}

impl<'a, 'b> From<&'a Vec<&'b str>> for ValueContainer {
    /// Copies each string into an owned collection, preserving order.
    /// An empty vector creates a concrete empty collection.
    ///
    /// # Parameters
    ///
    /// * `values` - Input converted with the ownership behavior described
    ///   above.
    ///
    /// # Returns
    ///
    /// A container preserving the input data type and scalar or collection
    /// shape.
    #[inline]
    fn from(values: &'a Vec<&'b str>) -> Self {
        Self::Collection(MultiValues::from(values))
    }
}

impl<'a, const N: usize> From<[&'a str; N]> for ValueContainer {
    /// Copies each string into an owned collection, preserving order.
    /// An empty array creates a concrete empty collection.
    ///
    /// # Type Parameters
    ///
    /// * `N` - Number of input array elements.
    ///
    /// # Parameters
    ///
    /// * `values` - Input converted with the ownership behavior described
    ///   above.
    ///
    /// # Returns
    ///
    /// A container preserving the input data type and scalar or collection
    /// shape.
    #[inline]
    fn from(values: [&'a str; N]) -> Self {
        Self::Collection(MultiValues::from(values))
    }
}

impl<'a, 'b, const N: usize> From<&'a [&'b str; N]> for ValueContainer {
    /// Copies each string into an owned collection, preserving order.
    /// An empty array creates a concrete empty collection.
    ///
    /// # Type Parameters
    ///
    /// * `N` - Number of input array elements.
    ///
    /// # Parameters
    ///
    /// * `values` - Input converted with the ownership behavior described
    ///   above.
    ///
    /// # Returns
    ///
    /// A container preserving the input data type and scalar or collection
    /// shape.
    #[inline]
    fn from(values: &'a [&'b str; N]) -> Self {
        Self::Collection(MultiValues::from(values))
    }
}

impl From<Value> for ValueContainer {
    /// Wraps the value as a scalar without cloning it.
    ///
    /// # Parameters
    ///
    /// * `value` - Input converted with the ownership behavior described above.
    ///
    /// # Returns
    ///
    /// A container preserving the input data type and scalar or collection
    /// shape.
    #[inline]
    fn from(value: Value) -> Self {
        Self::Scalar(value)
    }
}

impl From<MultiValues> for ValueContainer {
    /// Wraps the collection without cloning its elements.
    ///
    /// # Parameters
    ///
    /// * `values` - Input converted with the ownership behavior described
    ///   above.
    ///
    /// # Returns
    ///
    /// A container preserving the input data type and scalar or collection
    /// shape.
    #[inline]
    fn from(values: MultiValues) -> Self {
        Self::Collection(values)
    }
}

impl ValueContainer {
    /// Creates an unset scalar container for a declared data type.
    ///
    /// # Parameters
    ///
    /// * `data_type` - Declared scalar type while no value is set.
    ///
    /// # Returns
    ///
    /// A scalar `ValueContainer` with explicit unset storage.
    #[inline]
    pub const fn new_unset_scalar(data_type: DataType) -> Self {
        Self::Scalar(Value::new_unset(data_type))
    }

    /// Creates an unset collection container for a declared element type.
    ///
    /// # Parameters
    ///
    /// * `data_type` - Declared element type while no values are set.
    ///
    /// # Returns
    ///
    /// A collection `ValueContainer` with explicit unset storage.
    #[inline]
    pub const fn new_unset_collection(data_type: DataType) -> Self {
        Self::Collection(MultiValues::new_unset(data_type))
    }

    /// Strictly borrows the scalar or first collection item without allocating.
    ///
    /// The returned reference is tied to this container's lifetime. The
    /// requested type must match the scalar or collection element type.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Stored scalar or element type to borrow.
    ///
    /// # Returns
    ///
    /// A reference to the scalar or the first collection item.
    ///
    /// # Errors
    ///
    /// Returns [`ValueError::Missing`] when no item is available, or a type
    /// conversion error when the stored type does not match `T`.
    ///
    /// # Examples
    ///
    /// ```
    /// use qubit_value::ValueContainer;
    /// use qubit_value::ValueError;
    ///
    /// let values = ValueContainer::from(vec![String::from("a"), String::from("b")]);
    /// let first: &String = values.get_first_ref().unwrap();
    /// assert_eq!(first, "a");
    /// let empty = ValueContainer::from(Vec::<String>::new());
    /// assert!(matches!(empty.get_first_ref::<String>(), Err(ValueError::Missing(_))));
    /// ```
    #[inline(always)]
    pub fn get_first_ref<'a, T: ?Sized>(&'a self) -> ValueResult<&'a T>
    where
        &'a T:
            TryFrom<&'a Value, Error = ValueError> + TryFrom<&'a MultiValues, Error = ValueError>,
    {
        match self {
            Self::Scalar(value) => <&'a T>::try_from(value),
            Self::Collection(values) => <&'a T>::try_from(values),
        }
    }

    /// Strictly borrows a scalar as a one-item slice or a complete collection.
    ///
    /// The returned slice is tied to this container's lifetime. The requested
    /// element type must match the stored type.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Stored element type of the borrowed slice.
    ///
    /// # Returns
    ///
    /// A one-item slice for a scalar, or all collection items. An empty
    /// collection returns an empty slice.
    ///
    /// # Errors
    ///
    /// Returns [`ValueError::Missing`] when an unset scalar or collection has
    /// the requested type, or [`ValueError::TypeMismatch`] when the stored type
    /// does not match `T`. A concrete empty collection returns an empty slice.
    ///
    /// # Examples
    ///
    /// ```
    /// use qubit_datatype::DataType;
    ///
    /// use qubit_value::ValueContainer;
    /// use qubit_value::ValueError;
    ///
    /// let values = ValueContainer::from(vec![String::from("a"), String::from("b")]);
    /// let all: &[String] = values.get_slice().unwrap();
    /// assert_eq!(all.len(), 2);
    /// let empty = ValueContainer::from(Vec::<String>::new());
    /// assert!(empty.get_slice::<String>().unwrap().is_empty());
    /// let unset_scalar = ValueContainer::new_unset_scalar(DataType::String);
    /// let unset_collection = ValueContainer::new_unset_collection(DataType::String);
    /// assert!(matches!(unset_scalar.get_slice::<String>(), Err(ValueError::Missing(_))));
    /// assert!(matches!(unset_collection.get_slice::<String>(), Err(ValueError::Missing(_))));
    /// ```
    #[inline(always)]
    pub fn get_slice<'a, T>(&'a self) -> ValueResult<&'a [T]>
    where
        &'a T: TryFrom<&'a Value, Error = ValueError>,
        &'a [T]: TryFrom<&'a MultiValues, Error = ValueError>,
    {
        match self {
            Self::Scalar(value) => value.get_ref().map(from_ref),
            Self::Collection(values) => values.get_slice(),
        }
    }

    /// Returns the stored or declared data type.
    ///
    /// # Returns
    ///
    /// The scalar or collection element type, including the declared type of
    /// unset storage.
    #[inline]
    pub fn data_type(&self) -> DataType {
        match self {
            Self::Scalar(value) => value.data_type(),
            Self::Collection(values) => values.data_type(),
        }
    }

    /// Returns whether this container has scalar shape.
    ///
    /// # Returns
    ///
    /// `true` for [`ValueContainer::Scalar`].
    #[inline]
    #[must_use]
    pub const fn is_scalar(&self) -> bool {
        matches!(self, Self::Scalar(_))
    }

    /// Returns the contained scalar without consuming this container.
    ///
    /// # Returns
    ///
    /// `Some` for scalar storage, or `None` for collection storage.
    #[must_use]
    #[inline]
    pub const fn as_scalar(&self) -> Option<&Value> {
        match self {
            Self::Scalar(value) => Some(value),
            Self::Collection(_) => None,
        }
    }

    /// Returns whether this container has collection shape.
    ///
    /// # Returns
    ///
    /// `true` for [`ValueContainer::Collection`].
    #[inline]
    #[must_use]
    pub const fn is_collection(&self) -> bool {
        matches!(self, Self::Collection(_))
    }

    /// Returns the contained collection without consuming this container.
    ///
    /// # Returns
    ///
    /// `Some` for collection storage, or `None` for scalar storage.
    #[must_use]
    #[inline]
    pub const fn as_collection(&self) -> Option<&MultiValues> {
        match self {
            Self::Scalar(_) => None,
            Self::Collection(values) => Some(values),
        }
    }

    /// Returns whether the shape contains no concrete value or collection.
    ///
    /// # Returns
    ///
    /// `true` when the contained scalar or collection is unset.
    #[inline(always)]
    #[must_use]
    pub fn is_unset(&self) -> bool {
        match self {
            Self::Scalar(value) => value.is_unset(),
            Self::Collection(values) => values.is_unset(),
        }
    }

    /// Returns zero for unset storage, one for a concrete scalar, or the
    /// concrete collection length.
    ///
    /// # Returns
    ///
    /// The number of concrete values represented by this container.
    #[inline]
    #[must_use]
    #[allow(clippy::len_without_is_empty)]
    pub fn len(&self) -> usize {
        match self {
            Self::Scalar(value) => usize::from(!value.is_unset()),
            Self::Collection(values) => values.len(),
        }
    }

    /// Tests whether this container represents no concrete values.
    ///
    /// # Returns
    ///
    /// `true` for unset storage or a concrete empty collection.
    #[inline]
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Strictly reads a scalar or the first collection item as `T`.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Strict target type.
    ///
    /// # Returns
    ///
    /// The scalar value or first collection item.
    ///
    /// # Errors
    ///
    /// Returns [`ValueError::Missing`] for unset or empty matching storage and
    /// [`ValueError::TypeMismatch`] when the stored data type differs.
    #[inline(always)]
    pub fn get_first<T>(&self) -> ValueResult<T>
    where
        T: StrictValueRead,
    {
        match self {
            Self::Scalar(value) => T::read_scalar(value),
            Self::Collection(values) => T::read_collection_first(values),
        }
    }

    /// Strictly reads a scalar as a one-item list or all collection items.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Strict target element type.
    ///
    /// # Returns
    ///
    /// A one-item scalar list or all collection items.
    ///
    /// # Errors
    ///
    /// Returns [`ValueError::Missing`] for unset matching storage and
    /// [`ValueError::TypeMismatch`] when the stored data type differs.
    #[inline(always)]
    pub fn get_list<T>(&self) -> ValueResult<Vec<T>>
    where
        T: StrictValueRead,
    {
        match self {
            Self::Scalar(value) => T::read_scalar(value).map(|item| vec![item]),
            Self::Collection(values) => T::read_collection_list(values),
        }
    }

    /// Converts a scalar or the first collection item to `T`.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Target conversion type.
    ///
    /// # Returns
    ///
    /// The converted scalar or first collection item.
    ///
    /// # Errors
    ///
    /// Returns the mapped `qubit-datatype` conversion error.
    #[cfg(feature = "converter")]
    #[inline(always)]
    #[cfg_attr(docsrs, doc(cfg(feature = "converter")))]
    pub fn to_first<T>(&self) -> ValueResult<T>
    where
        T: DataConversionTarget,
    {
        self.to_first_with(
            ConversionPolicy::default_ref(),
            ConversionLimits::default_ref(),
        )
    }

    /// Converts a scalar or the first collection item using explicit policy and
    /// limits.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Target conversion type.
    ///
    /// # Parameters
    ///
    /// * `policy` - Conversion policy forwarded to the contained value.
    /// * `limits` - Conversion limits forwarded to the contained value.
    ///
    /// # Returns
    ///
    /// The converted scalar or first collection item.
    ///
    /// # Errors
    ///
    /// Returns the mapped `qubit-datatype` conversion error.
    #[cfg(feature = "converter")]
    #[inline(always)]
    #[cfg_attr(docsrs, doc(cfg(feature = "converter")))]
    pub fn to_first_with<T>(
        &self,
        policy: &ConversionPolicy,
        limits: &ConversionLimits,
    ) -> ValueResult<T>
    where
        T: DataConversionTarget,
    {
        match self {
            Self::Scalar(value) => value.to_with(policy, limits),
            Self::Collection(values) => values.to_first_with(policy, limits),
        }
    }

    /// Converts the scalar or first collection item using an existing
    /// conversion session.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Target conversion type.
    ///
    /// # Parameters
    ///
    /// * `session` - Caller-owned session providing policy, limits, and budget.
    ///
    /// # Returns
    ///
    /// The converted scalar or first collection item.
    ///
    /// # Errors
    ///
    /// Returns the mapped missing, conversion, or budget error.
    #[cfg(feature = "converter")]
    #[inline(always)]
    #[cfg_attr(docsrs, doc(cfg(feature = "converter")))]
    pub fn to_first_in<T>(&self, session: &mut ConversionSession<'_>) -> ValueResult<T>
    where
        T: DataConversionTarget,
    {
        match self {
            Self::Scalar(value) => value.to_in(session),
            Self::Collection(values) => values.to_first_in(session),
        }
    }

    /// Converts a scalar to a list or converts every collection item.
    ///
    /// Scalar strings may be split according to collection conversion policy;
    /// strings already stored in a collection are never split again.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Target list element type.
    ///
    /// # Returns
    ///
    /// A converted scalar list or all converted collection items.
    ///
    /// # Errors
    ///
    /// Returns the mapped single-value or indexed list conversion error.
    #[cfg(feature = "converter")]
    #[inline(always)]
    #[cfg_attr(docsrs, doc(cfg(feature = "converter")))]
    pub fn to_list<T>(&self) -> ValueResult<Vec<T>>
    where
        T: DataConversionTarget,
    {
        self.to_list_with(
            ConversionPolicy::default_ref(),
            ConversionLimits::default_ref(),
        )
    }

    /// Converts to a list using explicit conversion policy and limits.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Target list element type.
    ///
    /// # Parameters
    ///
    /// * `policy` - Conversion policy forwarded to the contained value.
    /// * `limits` - Conversion limits forwarded to the contained value.
    ///
    /// # Returns
    ///
    /// A converted scalar list or all converted collection items.
    ///
    /// # Errors
    ///
    /// Returns the mapped single-value or indexed list conversion error.
    #[cfg(feature = "converter")]
    #[cfg_attr(docsrs, doc(cfg(feature = "converter")))]
    pub fn to_list_with<T>(
        &self,
        policy: &ConversionPolicy,
        limits: &ConversionLimits,
    ) -> ValueResult<Vec<T>>
    where
        T: DataConversionTarget,
    {
        match self {
            Self::Scalar(value) => match value.view() {
                ValueRef::String(value) => ScalarStringDataConverters::from(value)
                    .to_vec_with(policy, limits)
                    .map_err(ValueError::from),
                _ => value.to_with(policy, limits).map(|value| vec![value]),
            },
            Self::Collection(values) => values.to_list_with(policy, limits),
        }
    }

    /// Converts this container to a list using an existing conversion session.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Target list element type.
    ///
    /// # Parameters
    ///
    /// * `session` - Caller-owned session providing policy, limits, and budget.
    ///
    /// # Returns
    ///
    /// A converted scalar list or all converted collection items.
    ///
    /// # Errors
    ///
    /// Returns the mapped missing, conversion, indexed-list, or budget error.
    #[cfg(feature = "converter")]
    #[cfg_attr(docsrs, doc(cfg(feature = "converter")))]
    pub fn to_list_in<T>(&self, session: &mut ConversionSession<'_>) -> ValueResult<Vec<T>>
    where
        T: DataConversionTarget,
    {
        match self {
            Self::Scalar(value) => match value.view() {
                ValueRef::String(value) => ScalarStringDataConverters::from(value)
                    .to_vec_in(session)
                    .map_err(ValueError::from),
                _ => value.to_in(session).map(|value| vec![value]),
            },
            Self::Collection(values) => values.to_list_in(session),
        }
    }

    /// Consumes this container and returns its scalar value.
    ///
    /// # Returns
    ///
    /// The contained scalar value when this container has scalar shape.
    ///
    /// # Errors
    ///
    /// Returns the original container unchanged when it has collection shape.
    #[inline(always)]
    pub fn into_scalar(self) -> Result<Value, Self> {
        match self {
            Self::Scalar(value) => Ok(value),
            Self::Collection(_) => Err(self),
        }
    }

    /// Consumes this container and returns its collection values.
    ///
    /// # Returns
    ///
    /// The contained values when this container has collection shape.
    ///
    /// # Errors
    ///
    /// Returns the original container unchanged when it has scalar shape.
    #[inline(always)]
    pub fn into_collection(self) -> Result<MultiValues, Self> {
        match self {
            Self::Scalar(_) => Err(self),
            Self::Collection(values) => Ok(values),
        }
    }

    /// Replaces this container, including its shape, from a supported input.
    ///
    /// # Type Parameters
    ///
    /// * `S` - Input type convertible into [`ValueContainer`].
    ///
    /// # Parameters
    ///
    /// * `value` - New scalar or collection value.
    #[inline(always)]
    pub fn set<S>(&mut self, value: S)
    where
        S: Into<Self>,
    {
        *self = value.into();
    }

    /// Appends values, promoting scalar storage to collection storage when the
    /// input contains at least one concrete value. Same-typed empty and unset
    /// input is a no-op.
    ///
    /// # Type Parameters
    ///
    /// * `S` - Input type convertible into [`ValueContainer`].
    ///
    /// # Parameters
    ///
    /// * `values` - Scalar or collection values to append.
    ///
    /// # Returns
    ///
    /// `Ok(())` after appending or accepting an empty same-typed input.
    ///
    /// # Errors
    ///
    /// Returns [`ValueError::TypeMismatch`] when the appended values have a
    /// different data type.
    pub fn add<S>(&mut self, values: S) -> ValueResult<()>
    where
        S: Into<Self>,
    {
        let other = values.into();
        let expected = self.data_type();
        let actual = other.data_type();
        if expected != actual {
            return Err(ValueError::TypeMismatch { expected, actual });
        }
        if other.is_empty() {
            return Ok(());
        }

        match other {
            Self::Scalar(value) => {
                self.add_scalar(value, expected);
                Ok(())
            }
            Self::Collection(other) => match self {
                Self::Scalar(value) => {
                    let value = replace(value, Value::new_unset(expected));
                    let mut collection = MultiValues::from(value);
                    collection.add(other)?;
                    *self = Self::Collection(collection);
                    Ok(())
                }
                Self::Collection(collection) => collection.add(other),
            },
        }
    }

    /// Removes concrete storage while preserving its shape and data type.
    #[inline(always)]
    pub fn unset(&mut self) {
        match self {
            Self::Scalar(value) => value.unset(),
            Self::Collection(values) => values.unset(),
        }
    }

    /// Appends a concrete scalar, promoting scalar storage to a collection.
    ///
    /// # Parameters
    ///
    /// * `value` - Concrete scalar to append.
    /// * `data_type` - Shared runtime type of `self` and `value`.
    ///
    /// # Constraints
    ///
    /// Callers must ensure `value` is concrete and has `data_type`; the public
    /// mutation entry points validate those invariants before calling this
    /// helper.
    #[inline]
    fn add_scalar(&mut self, value: Value, data_type: DataType) {
        match self {
            Self::Scalar(current) => {
                let current = replace(current, Value::new_unset(data_type));
                let collection = for_each_value_type!(value_container_pair_match, current, value);
                *self = Self::Collection(collection);
            }
            Self::Collection(collection) => {
                for_each_value_type!(value_container_push_match, collection, value);
            }
        }
    }
}

#[cfg(all(feature = "converter", feature = "json"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "converter", feature = "json"))))]
impl ValueContainer {
    /// Projects this container while preserving concrete collection shape.
    ///
    /// Scalar storage uses the natural scalar projection; concrete collection
    /// storage always uses a JSON array.
    ///
    /// # Returns
    ///
    /// The natural JSON representation, except scalar and collection unset
    /// values both project to `null`.
    ///
    /// For natural JSON projection, `max_text_bytes` bounds each string value
    /// and each formatted number or rich-value text by its UTF-8 byte length,
    /// including strings inside materialized JSON. Object keys are excluded
    /// from this per-item bound but still consume applicable key and
    /// cumulative input, output, and payload budgets. This is neither a
    /// cumulative text limit nor a limit on escaped JSON encoding size.
    ///
    /// # Errors
    ///
    /// Returns the same structured projection error as the contained value.
    #[inline(always)]
    pub fn to_json_value(&self) -> ValueResult<JsonValue> {
        self.to_json_value_with(
            ConversionPolicy::default_ref(),
            ConversionLimits::default_ref(),
        )
    }

    /// Projects this container 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, except scalar and collection unset
    /// values both project to `null`.
    ///
    /// # Errors
    ///
    /// Returns the same structured projection error as the contained value.
    #[inline]
    pub fn to_json_value_with(
        &self,
        policy: &ConversionPolicy,
        limits: &ConversionLimits,
    ) -> ValueResult<JsonValue> {
        crate::json::value_container_to_json_value_with(self, policy, limits)
    }
}