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
// =============================================================================
// Copyright (c) 2025 - 2026 Haixing Hu.
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Core generic accessors and state methods for `MultiValues`.
use qubit_datatype::DataType;
use crate::value_error::{
ValueError,
ValueResult,
};
use crate::{
IntoValueDefault,
Value,
};
use super::multi_values::{
MultiValues,
MultiValuesRepr,
};
use crate::value::ValueRepr;
macro_rules! multi_values_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)),+ $(,)?) => {
match &$value.repr {
MultiValuesRepr::Unset(dt) => *dt,
$($(#[$cfg])* MultiValuesRepr::$variant(_) => $data_type,)+
}
};
}
macro_rules! multi_values_count_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)),+ $(,)?) => {
match &$value.repr {
MultiValuesRepr::Unset(_) => 0,
$($(#[$cfg])* MultiValuesRepr::$variant(values) => values.len(),)+
}
};
}
macro_rules! multi_values_clear_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)),+ $(,)?) => {
match &mut $value.repr {
MultiValuesRepr::Unset(_) => {}
$($(#[$cfg])* MultiValuesRepr::$variant(values) => values.clear(),)+
}
};
}
macro_rules! multi_values_append_match {
($left:expr, $right:expr; $(([$($cfg:meta),*], $variant:ident, $type:ty, $data_type:expr, $materialization:ident, $json_class:ident, $number_projection:ident, $value_doc:literal, $multi_doc:literal)),+ $(,)?) => {
match (&mut $left.repr, &mut $right.repr) {
$(
$(#[$cfg])*
(MultiValuesRepr::$variant(values), MultiValuesRepr::$variant(other_values)) => {
values.append(other_values);
}
)+
(slot @ MultiValuesRepr::Unset(_), other_values) => {
*slot = std::mem::replace(other_values, MultiValuesRepr::Unset(DataType::String));
}
_ => unreachable!(),
}
};
}
macro_rules! multi_values_first_value_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)),+ $(,)?) => {
match &$value.repr {
MultiValuesRepr::Unset(data_type) => Value::new_unset(*data_type),
$(
$(#[$cfg])*
MultiValuesRepr::$variant(values) => values
.first()
.map(|value| materialize_stored!($materialization, value))
.map(Value::$variant)
.unwrap_or(Value::new_unset($data_type)),
)+
}
};
}
macro_rules! multi_values_into_first_value_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)),+ $(,)?) => {
match $value.repr {
MultiValuesRepr::Unset(data_type) => Value::new_unset(data_type),
$(
$(#[$cfg])*
MultiValuesRepr::$variant(values) => values
.into_iter()
.next()
.map(Value::$variant)
.unwrap_or(Value::new_unset($data_type)),
)+
}
};
}
macro_rules! multi_values_merge_match {
($left:expr, $right:expr; $(([$($cfg:meta),*], $variant:ident, $type:ty, $data_type:expr, $materialization:ident, $json_class:ident, $number_projection:ident, $value_doc:literal, $multi_doc:literal)),+ $(,)?) => {
match (&mut $left.repr, &$right.repr) {
$(
$(#[$cfg])*
(MultiValuesRepr::$variant(values), MultiValuesRepr::$variant(other_values)) => {
values.extend_from_slice(other_values)
}
)+
(slot @ MultiValuesRepr::Unset(_), other_values) => *slot = other_values.clone(),
_ => unreachable!(),
}
};
}
macro_rules! value_into_multi_values_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)),+ $(,)?) => {
match $value.repr {
ValueRepr::Unset(data_type) => MultiValues::new_unset(data_type),
$($(#[$cfg])* ValueRepr::$variant(value) => {
MultiValues::$variant(vec![value_storage_into_multi!($variant, value)])
},)+
}
};
}
impl MultiValues {
/// Generic constructor method
///
/// Creates `MultiValues` from any supported input form, avoiding direct
/// use of enum variants at call sites.
///
/// Supported input forms include single values, vectors, slices, arrays,
/// borrowed vectors, and borrowed string collections for supported element
/// types.
///
/// # Type Parameters
///
/// * `S` - Input type convertible into [`MultiValues`].
///
/// # Parameters
///
/// * `values` - Values to convert into a collection.
///
/// # Returns
///
/// Returns `MultiValues` wrapping the converted input values.
///
/// # Examples
///
/// ```rust
/// use qubit_value::MultiValues;
///
/// // Basic types
/// let mv = MultiValues::new(vec![1, 2, 3]);
/// assert_eq!(mv.len(), 3);
///
/// // Strings
/// let mv = MultiValues::new(vec!["a".to_string(), "b".to_string()]);
/// assert_eq!(mv.len(), 2);
/// ```
#[inline(always)]
pub fn new<S>(values: S) -> Self
where
S: Into<Self>,
{
values.into()
}
/// Generic getter method for multiple values.
///
/// Performs a strict typed read of all stored values as `Vec<T>`.
///
/// # Type Parameters
///
/// * `T` - The target element type to retrieve.
///
/// # Returns
///
/// Returns the list of values when the stored type matches `T`.
///
/// # Errors
///
/// Returns [`ValueError::Missing`] when the container is unset with the
/// requested type, or [`ValueError::TypeMismatch`] when the stored type
/// differs from `T`.
///
/// # Examples
///
/// ```rust
/// use qubit_value::MultiValues;
///
/// let multi = MultiValues::Int32(vec![1, 2, 3]);
///
/// // Through type inference
/// let nums: Vec<i32> = multi.get().unwrap();
/// assert_eq!(nums, vec![1, 2, 3]);
///
/// // Explicitly specify type parameter
/// let nums = multi.get::<i32>().unwrap();
/// assert_eq!(nums, vec![1, 2, 3]);
/// ```
#[inline(always)]
pub fn get<T>(&self) -> ValueResult<Vec<T>>
where
for<'a> Vec<T>: TryFrom<&'a Self, Error = ValueError>,
{
Vec::<T>::try_from(self)
}
/// Generic getter method with a default value list.
///
/// Returns the supplied default only when this container is unset. A
/// concrete empty vector remains an empty result.
///
/// # Type Parameters
///
/// * `T` - Target element type for the strict read.
///
/// # Parameters
///
/// * `default` - Lazily materialized list used only for unset storage.
///
/// # Returns
///
/// The concrete stored list, or `default` for unset storage.
///
/// # Errors
///
/// Returns [`ValueError::TypeMismatch`] when the stored type differs from
/// `T`.
#[inline]
pub fn get_or<T>(
&self,
default: impl IntoValueDefault<Vec<T>>,
) -> ValueResult<Vec<T>>
where
for<'a> Vec<T>: TryFrom<&'a Self, Error = ValueError>,
{
match self.get() {
Err(ValueError::Missing(missing)) if missing.is_unset() => {
Ok(default.into_value_default())
}
result => result,
}
}
/// Strictly reads all values or calls `default` only when storage is unset.
///
/// A concrete empty collection is returned unchanged and type mismatches
/// are preserved without invoking the callback.
///
/// # Type Parameters
///
/// * `T` - Target element type.
/// * `F` - Deferred fallback producing the complete list.
///
/// # Parameters
///
/// * `default` - Callback invoked only for unset storage.
///
/// # Returns
///
/// The stored list or the callback result.
///
/// # Errors
///
/// Returns [`ValueError::TypeMismatch`] for an incompatible concrete
/// collection without invoking the callback.
#[inline]
pub fn get_or_else<T, F>(&self, default: F) -> ValueResult<Vec<T>>
where
for<'a> Vec<T>: TryFrom<&'a Self, Error = ValueError>,
F: FnOnce() -> Vec<T>,
{
match self.get() {
Err(ValueError::Missing(missing)) if missing.is_unset() => {
Ok(default())
}
result => result,
}
}
/// Generic getter method for the first value
///
/// Reads the first stored value as `T`, performing strict type checking.
///
/// `get_first<T>()` does not do cross-type conversion. When the `converter`
/// feature is enabled, use `to<T>()` for compatible cross-type conversion.
///
/// # Type Parameters
///
/// * `T` - The target element type to retrieve.
///
/// # Returns
///
/// Returns the first value when the stored type matches `T` and at least
/// one value exists.
///
/// # Errors
///
/// Returns [`ValueError::Missing`] when the requested type matches but no
/// value is stored, or [`ValueError::TypeMismatch`] when the stored type
/// differs from `T`.
///
/// # Examples
///
/// ```rust
/// use qubit_value::MultiValues;
///
/// let multi = MultiValues::Int32(vec![42, 100, 200]);
///
/// // Through type inference
/// let first: i32 = multi.get_first().unwrap();
/// assert_eq!(first, 42);
///
/// // Explicitly specify type parameter
/// let first = multi.get_first::<i32>().unwrap();
/// assert_eq!(first, 42);
///
/// // String type
/// let multi = MultiValues::String(vec!["hello".to_string(), "world".to_string()]);
/// let first: String = multi.get_first().unwrap();
/// assert_eq!(first, "hello");
/// ```
#[inline(always)]
pub fn get_first<T>(&self) -> ValueResult<T>
where
for<'a> T: TryFrom<&'a Self, Error = ValueError>,
{
T::try_from(self)
}
/// Generic first-value getter with a default value.
///
/// Returns the supplied default only when the container is unset. A
/// concrete empty vector returns [`ValueError::Missing`]; type mismatches
/// are also preserved.
///
/// # Type Parameters
///
/// * `T` - Target type for the strict first-item read.
///
/// # Parameters
///
/// * `default` - Lazily materialized value used only for unset storage.
///
/// # Returns
///
/// The first concrete item, or `default` for unset storage.
///
/// # Errors
///
/// Returns [`ValueError::Missing`] for a concrete empty collection or
/// [`ValueError::TypeMismatch`] when the stored type differs from `T`.
#[inline]
pub fn get_first_or<T>(
&self,
default: impl IntoValueDefault<T>,
) -> ValueResult<T>
where
for<'a> T: TryFrom<&'a Self, Error = ValueError>,
{
match self.get_first() {
Err(ValueError::Missing(missing)) if missing.is_unset() => {
Ok(default.into_value_default())
}
result => result,
}
}
/// Strictly reads the first value or calls `default` only when unset.
///
/// # Type Parameters
///
/// * `T` - Target element type.
/// * `F` - Deferred fallback producing one element.
///
/// # Parameters
///
/// * `default` - Callback invoked only for unset storage.
///
/// # Returns
///
/// The first stored item or the callback result.
///
/// # Errors
///
/// Preserves empty-collection and type-mismatch errors without invoking
/// the callback.
#[inline]
pub fn get_first_or_else<T, F>(&self, default: F) -> ValueResult<T>
where
for<'a> T: TryFrom<&'a Self, Error = ValueError>,
F: FnOnce() -> T,
{
match self.get_first() {
Err(ValueError::Missing(missing)) if missing.is_unset() => {
Ok(default())
}
result => result,
}
}
/// Generic setter method
///
/// Replaces the entire list with the converted input values.
///
/// This operation updates the stored type to the input element type and
/// does not validate runtime compatibility with the previous variant.
///
/// Supports any input that can be converted into [`MultiValues`], including
/// single values, vectors, slices, arrays, and borrowed vectors for
/// supported element types.
///
/// Existing values are replaced, and the stored type becomes the converted
/// input type.
///
/// # Type Parameters
///
/// * `S` - Input type convertible into [`MultiValues`].
///
/// # Parameters
///
/// * `values` - The values to set.
///
/// # Compile-time restriction
///
/// Unsupported input types fail to compile because they do not implement
/// `Into<MultiValues>`.
///
/// # Examples
///
/// ```rust
/// use qubit_datatype::DataType;
/// use qubit_value::MultiValues;
///
/// // 1) Vec<T>
/// let mut mv = MultiValues::Unset(DataType::Int32);
/// mv.set(vec![42, 100, 200]);
/// assert_eq!(mv.get_int32s().unwrap(), &[42, 100, 200]);
///
/// // 2) &[T]
/// let mut mv = MultiValues::Unset(DataType::Int32);
/// let slice = &[7, 8, 9][..];
/// mv.set(slice);
/// assert_eq!(mv.get_int32s().unwrap(), &[7, 8, 9]);
///
/// // 3) Single T
/// let mut mv = MultiValues::Unset(DataType::Int32);
/// mv.set(42);
/// assert_eq!(mv.get_int32s().unwrap(), &[42]);
///
/// // String example
/// let mut mv = MultiValues::Unset(DataType::String);
/// mv.set(vec!["hello".to_string(), "world".to_string()]);
/// assert_eq!(mv.get_strings().unwrap(), &["hello", "world"]);
/// ```
#[inline(always)]
pub fn set<S>(&mut self, values: S)
where
S: Into<Self>,
{
*self = values.into();
}
/// Generic add method
///
/// Appends converted input values to the existing list with strict type
/// checking.
///
/// Supports any input that can be converted into [`MultiValues`], including
/// single values, vectors, slices, arrays, and borrowed vectors for
/// supported element types.
///
/// The converted input must have the same data type as the current
/// container. An empty container keeps its declared type until
/// non-empty values of the same type are appended.
///
/// # Type Parameters
///
/// * `S` - Input type convertible into [`MultiValues`].
///
/// # Parameters
///
/// * `values` - Values to append.
///
/// # Returns
///
/// `Ok(())` after appending, including when the input is empty.
///
/// # Errors
///
/// Returns [`ValueError::TypeMismatch`] when the converted input data type
/// differs from the current container data type.
///
/// # Examples
///
/// ```rust
/// use qubit_datatype::DataType;
/// use qubit_value::MultiValues;
///
/// // 1) Single T
/// let mut mv = MultiValues::Int32(vec![42]);
/// mv.add(100).unwrap();
/// assert_eq!(mv.get_int32s().unwrap(), &[42, 100]);
///
/// // 2) Vec<T>
/// mv.add(vec![200, 300]).unwrap();
/// assert_eq!(mv.get_int32s().unwrap(), &[42, 100, 200, 300]);
///
/// // 3) &[T]
/// let slice = &[400, 500][..];
/// mv.add(slice).unwrap();
/// assert_eq!(mv.get_int32s().unwrap(), &[42, 100, 200, 300, 400, 500]);
/// ```
pub fn add<S>(&mut self, values: S) -> ValueResult<()>
where
S: Into<Self>,
{
let mut other = values.into();
if self.data_type() != other.data_type() {
return Err(ValueError::TypeMismatch {
expected: self.data_type(),
actual: other.data_type(),
});
}
if other.is_empty() {
return Ok(());
}
for_each_value_type!(multi_values_append_match, self, other);
Ok(())
}
/// Get the data type of the values
///
/// # Returns
///
/// Returns the data type corresponding to these multiple values
///
/// # Examples
///
/// ```rust
/// use qubit_datatype::DataType;
/// use qubit_value::MultiValues;
///
/// let values = MultiValues::Int32(vec![1, 2, 3]);
/// assert_eq!(values.data_type(), DataType::Int32);
/// ```
#[inline(always)]
pub fn data_type(&self) -> DataType {
for_each_value_type!(multi_values_data_type_match, self)
}
/// Returns the number of values.
///
/// # Returns
///
/// The number of values contained in these multiple values. An unset
/// collection has length zero.
///
/// # Examples
///
/// ```rust
/// use qubit_datatype::DataType;
/// use qubit_value::MultiValues;
///
/// let values = MultiValues::Int32(vec![1, 2, 3]);
/// assert_eq!(values.len(), 3);
///
/// let empty = MultiValues::Unset(DataType::String);
/// assert_eq!(empty.len(), 0);
/// ```
#[inline(always)]
#[must_use]
pub fn len(&self) -> usize {
for_each_value_type!(multi_values_count_match, self)
}
/// Tests whether this collection contains no values.
///
/// An unset collection and a concrete empty vector both have length zero.
/// Use [`MultiValues::is_unset`] when the distinction between no collection
/// and a concrete empty collection matters.
///
/// # Returns
///
/// `true` when [`Self::len`] is zero; otherwise, `false`.
#[inline(always)]
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Tests whether this container has no concrete vector.
///
/// # Returns
///
/// Returns `true` only for [`MultiValues::Unset`]. A concrete empty vector
/// returns `false`.
///
/// # Examples
///
/// ```rust
/// use qubit_datatype::DataType;
/// use qubit_value::MultiValues;
///
/// let values = MultiValues::Int32(vec![]);
/// assert!(!values.is_unset());
///
/// let empty = MultiValues::Unset(DataType::String);
/// assert!(empty.is_unset());
/// ```
#[inline(always)]
#[must_use]
pub fn is_unset(&self) -> bool {
matches!(self.repr, MultiValuesRepr::Unset(_))
}
/// Tests whether a concrete collection belongs to the numeric type family.
///
/// A concrete empty numeric vector returns `true`; an unset collection
/// returns `false`, even when its declared type is numeric.
///
/// # Returns
///
/// `true` for concrete collections with a numeric element type.
#[inline(always)]
#[must_use]
pub fn is_numeric(&self) -> bool {
!self.is_unset() && self.data_type().is_numeric()
}
/// Removes the concrete vector while preserving its declared data type.
#[inline(always)]
pub fn unset(&mut self) {
*self = MultiValues::new_unset(self.data_type());
}
/// Clears all values while preserving a concrete collection and its type.
/// An unset collection remains unset because it has no concrete vector to
/// clear.
///
/// # Examples
///
/// ```rust
/// use qubit_datatype::DataType;
/// use qubit_value::MultiValues;
///
/// let mut values = MultiValues::Int32(vec![1, 2, 3]);
/// values.clear();
/// assert_eq!(values.len(), 0);
/// assert_eq!(values.data_type(), DataType::Int32);
/// ```
#[inline(always)]
pub fn clear(&mut self) {
for_each_value_type!(multi_values_clear_match, self)
}
/// Set the data type
///
/// If the new type differs from the current type, clears all values and
/// sets the new type.
///
/// # Parameters
///
/// * `data_type` - The data type to set
///
/// # Examples
///
/// ```rust
/// use qubit_datatype::DataType;
/// use qubit_value::MultiValues;
///
/// let mut values = MultiValues::Int32(vec![1, 2, 3]);
/// values.set_type(DataType::String);
/// assert!(values.is_unset());
/// assert_eq!(values.data_type(), DataType::String);
/// ```
#[inline]
pub fn set_type(&mut self, data_type: DataType) {
if self.data_type() != data_type {
*self = MultiValues::new_unset(data_type);
}
}
/// Converts the first element to a single [`Value`].
///
/// Returns `Value::Unset` with the same declared type when no element is
/// stored.
///
/// # Returns
///
/// A cloned first item, or a typed unset value when no item exists.
pub fn first_value(&self) -> Value {
for_each_value_type!(multi_values_first_value_match, self)
}
/// Consumes this collection and returns its first item as a [`Value`].
///
/// Empty and unset collections become [`Value::Unset`] with the same data
/// type. Owned element storage is moved instead of cloned.
///
/// # Returns
///
/// The owned first item, or a typed unset value when no item exists.
pub fn into_first_value(self) -> Value {
for_each_value_type!(multi_values_into_first_value_match, self)
}
/// Appends all values from another container with the same data type.
///
/// # Parameters
///
/// * `other` - Collection whose values are cloned and appended.
///
/// # Returns
///
/// `Ok(())` after appending, including when `other` is empty.
///
/// # Errors
///
/// Returns [`ValueError::TypeMismatch`] when `other` has a different data
/// type.
pub fn merge(&mut self, other: &MultiValues) -> ValueResult<()> {
if self.data_type() != other.data_type() {
return Err(ValueError::TypeMismatch {
expected: self.data_type(),
actual: other.data_type(),
});
}
if other.is_empty() {
return Ok(());
}
for_each_value_type!(multi_values_merge_match, self, other);
Ok(())
}
}
impl From<Value> for MultiValues {
fn from(value: Value) -> Self {
for_each_value_type!(value_into_multi_values_match, value)
}
}