qubit-value 0.10.0

Type-safe containers for single, multi-valued, and named runtime values
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
// =============================================================================
//    Copyright (c) 2025 - 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================

//! Internal conversion and interoperability implementations for `MultiValues`.
//!
//! This module keeps generic conversion logic (`to_first` and `to_list`).

use qubit_datatype::{
    DataConversionError,
    DataConversionOptions,
    DataConversionTarget,
    DataConverter,
    DataConverters,
};

use crate::IntoValueDefault;
use crate::value_error::{
    ValueError,
    ValueResult,
};

use super::multi_values::{
    MultiValues,
    MultiValuesRepr,
};

macro_rules! multi_values_convert_first_match {
    ($value:expr, $options: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(from) => {
                Err(DataConversionError::missing(*from, T::DATA_TYPE).into())
            }
            $(
                $(#[$cfg])*
                MultiValuesRepr::$variant(values) => {
                    convert_first_with(DataConverters::from(values), $options)
                }
            )+
        }
    };
}

macro_rules! multi_values_convert_list_match {
    ($value:expr, $options: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(from) => {
                Err(DataConversionError::missing(*from, T::DATA_TYPE).into())
            }
            $(
                $(#[$cfg])*
                MultiValuesRepr::$variant(values) => {
                    convert_values_with(DataConverters::from(values), $options)
                }
            )+
        }
    };
}

// ============================================================================
// Inherent conversion APIs
// ============================================================================

/// Converts the first item from a batch converter using conversion options.
///
/// # Type Parameters
///
/// * `T` - Target type.
/// * `I` - Iterator type wrapped by `DataConverters`.
///
/// # Parameters
///
/// * `values` - Batch converter containing source values.
/// * `options` - Conversion options forwarded to `qubit_datatype`.
///
/// # Returns
///
/// Returns the converted first value.
///
/// # Errors
///
/// Returns the mapped single-value conversion error for an empty source or an
/// invalid first source value.
#[inline(always)]
fn convert_first_with<'a, T, I>(
    values: DataConverters<I>,
    options: &DataConversionOptions,
) -> ValueResult<T>
where
    T: DataConversionTarget,
    I: Iterator,
    I::Item: Into<DataConverter<'a>>,
{
    values.to_first_with(options).map_err(ValueError::from)
}

/// Converts every item from a batch converter using conversion options.
///
/// # Type Parameters
///
/// * `T` - Target element type.
/// * `I` - Iterator type wrapped by `DataConverters`.
///
/// # Parameters
///
/// * `values` - Batch converter containing source values.
/// * `options` - Conversion options forwarded to `qubit_datatype`.
///
/// # Returns
///
/// Returns converted values in the original order.
///
/// # Errors
///
/// Returns a mapped batch conversion error containing the failing source index.
#[inline(always)]
fn convert_values_with<'a, T, I>(
    values: DataConverters<I>,
    options: &DataConversionOptions,
) -> ValueResult<Vec<T>>
where
    T: DataConversionTarget,
    I: Iterator,
    I::Item: Into<DataConverter<'a>>,
{
    values.to_vec_with(options).map_err(ValueError::from)
}

impl MultiValues {
    /// Converts the first stored value to `T`.
    ///
    /// Unlike [`Self::get_first`], this method uses shared `DataConverter`
    /// conversion rules instead of strict type matching. For example, a stored
    /// `String("1")` can be converted to `bool`.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Target type.
    ///
    /// # Returns
    ///
    /// The converted first value.
    ///
    /// # Errors
    ///
    /// Returns a structured missing-value conversion error when the container
    /// is unset, an empty-collection error for a concrete empty vector, or a
    /// conversion error when the first value cannot be converted to `T`.
    #[inline(always)]
    pub fn to_first<T>(&self) -> ValueResult<T>
    where
        T: DataConversionTarget,
    {
        self.to_first_with(DataConversionOptions::default_ref())
    }

    /// Converts the first stored value to `T`, or returns `default` when the
    /// container is unset or conversion reports a missing value.
    ///
    /// A concrete empty collection remains an error and does not use the
    /// default.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Target type.
    ///
    /// # Parameters
    ///
    /// * `default` - Value returned for unset storage or a conversion-missing
    ///   result.
    ///
    /// # Returns
    ///
    /// The converted first value, or `default` for unset or conversion-missing
    /// storage.
    ///
    /// # Errors
    ///
    /// Returns an empty-collection error for a concrete empty vector, or a
    /// conversion error when the first value cannot be converted to `T`.
    #[inline]
    pub fn to_first_or<T>(
        &self,
        default: impl IntoValueDefault<T>,
    ) -> ValueResult<T>
    where
        T: DataConversionTarget,
    {
        match self.to_first() {
            Err(ValueError::Missing(missing))
                if missing.is_defaultable_for_conversion() =>
            {
                Ok(default.into_value_default())
            }
            result => result,
        }
    }

    /// Converts the first value 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 for unset storage or a conversion-missing
    ///   result.
    ///
    /// # Returns
    ///
    /// The converted first item or the callback result.
    ///
    /// # Errors
    ///
    /// Preserves empty-collection and concrete-value conversion errors without
    /// invoking the callback.
    #[inline]
    pub fn to_first_or_else<T, F>(&self, default: F) -> ValueResult<T>
    where
        T: DataConversionTarget,
        F: FnOnce() -> T,
    {
        match self.to_first() {
            Err(ValueError::Missing(missing))
                if missing.is_defaultable_for_conversion() =>
            {
                Ok(default())
            }
            result => result,
        }
    }

    /// Converts the first stored value to `T` using conversion options.
    ///
    /// Stored strings are collection items and are never split again by scalar
    /// string collection options.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Target type.
    ///
    /// # Parameters
    ///
    /// * `options` - Conversion options forwarded to `qubit_datatype`.
    ///
    /// # Returns
    ///
    /// The converted first value.
    ///
    /// # Errors
    ///
    /// Returns a structured missing-value conversion error when the container
    /// is unset, an empty-collection error for a concrete empty vector, or a
    /// conversion error when the first value cannot be converted to `T`.
    pub fn to_first_with<T>(
        &self,
        options: &DataConversionOptions,
    ) -> ValueResult<T>
    where
        T: DataConversionTarget,
    {
        for_each_value_type!(multi_values_convert_first_match, self, options)
    }

    /// Converts the first stored value to `T` using conversion options, or
    /// returns `default` when storage is unset or conversion reports a missing
    /// value.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Target conversion type.
    ///
    /// # Parameters
    ///
    /// * `default` - Lazily materialized value used for unset storage or a
    ///   conversion-missing result.
    /// * `options` - Conversion options forwarded to `qubit_datatype`.
    ///
    /// # Returns
    ///
    /// The converted first item, or `default` for unset or conversion-missing
    /// storage.
    ///
    /// # Errors
    ///
    /// Returns an empty-collection error or a conversion error for concrete
    /// values that cannot be converted under `options`.
    #[inline]
    pub fn to_first_or_with<T>(
        &self,
        default: impl IntoValueDefault<T>,
        options: &DataConversionOptions,
    ) -> ValueResult<T>
    where
        T: DataConversionTarget,
    {
        match self.to_first_with(options) {
            Err(ValueError::Missing(missing))
                if missing.is_defaultable_for_conversion() =>
            {
                Ok(default.into_value_default())
            }
            result => result,
        }
    }

    /// Converts the first value with `options`, 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 for unset storage or a conversion-missing
    ///   result.
    /// * `options` - Conversion options forwarded to the shared converter.
    ///
    /// # Returns
    ///
    /// The converted first item or the callback result.
    ///
    /// # Errors
    ///
    /// Preserves concrete-value conversion errors without invoking the
    /// callback.
    #[inline]
    pub fn to_first_or_else_with<T, F>(
        &self,
        default: F,
        options: &DataConversionOptions,
    ) -> ValueResult<T>
    where
        T: DataConversionTarget,
        F: FnOnce() -> T,
    {
        match self.to_first_with(options) {
            Err(ValueError::Missing(missing))
                if missing.is_defaultable_for_conversion() =>
            {
                Ok(default())
            }
            result => result,
        }
    }

    /// Converts all stored values to `T`.
    ///
    /// Unlike [`Self::get`], this method uses shared `DataConverter` conversion
    /// rules for every element instead of strict type matching. A concrete
    /// empty vector returns an empty vector; an unset container reports a
    /// missing-value conversion error.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Target element type.
    ///
    /// # Returns
    ///
    /// A vector containing all converted values in the original order.
    ///
    /// # Errors
    ///
    /// Returns the first conversion error encountered while converting an
    /// element.
    pub fn to_list<T>(&self) -> ValueResult<Vec<T>>
    where
        T: DataConversionTarget,
    {
        self.to_list_with(DataConversionOptions::default_ref())
    }

    /// Converts all stored values to `T`, or returns `default` when storage is
    /// unset or conversion reports a missing value.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Target element type.
    ///
    /// # Parameters
    ///
    /// * `default` - Lazily materialized list used for unset storage or a
    ///   conversion-missing result.
    ///
    /// # Returns
    ///
    /// All converted items, or `default` for unset or conversion-missing
    /// storage.
    ///
    /// # Errors
    ///
    /// Returns the first item conversion error for concrete storage.
    #[inline]
    pub fn to_list_or<T>(
        &self,
        default: impl IntoValueDefault<Vec<T>>,
    ) -> ValueResult<Vec<T>>
    where
        T: DataConversionTarget,
    {
        match self.to_list() {
            Err(ValueError::Missing(missing))
                if missing.is_defaultable_for_conversion() =>
            {
                Ok(default.into_value_default())
            }
            result => result,
        }
    }

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

    /// Converts all stored values to `T` using conversion options.
    ///
    /// Stored strings are collection items and are never split again by scalar
    /// string collection options.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Target element type.
    ///
    /// # Parameters
    ///
    /// * `options` - Conversion options forwarded to `qubit_datatype`.
    ///
    /// # Returns
    ///
    /// A vector containing all converted values in the original order.
    ///
    /// # Errors
    ///
    /// Returns the first conversion error encountered while converting an
    /// element.
    pub fn to_list_with<T>(
        &self,
        options: &DataConversionOptions,
    ) -> ValueResult<Vec<T>>
    where
        T: DataConversionTarget,
    {
        for_each_value_type!(multi_values_convert_list_match, self, options)
    }

    /// Converts all stored values to `T` using conversion options, or returns
    /// `default` when storage is unset or conversion reports a missing value.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Target element type.
    ///
    /// # Parameters
    ///
    /// * `default` - Lazily materialized list used for unset storage or a
    ///   conversion-missing result.
    /// * `options` - Conversion options forwarded to `qubit_datatype`.
    ///
    /// # Returns
    ///
    /// All converted items, or `default` for unset or conversion-missing
    /// storage.
    ///
    /// # Errors
    ///
    /// Returns the first item conversion error for concrete storage.
    #[inline]
    pub fn to_list_or_with<T>(
        &self,
        default: impl IntoValueDefault<Vec<T>>,
        options: &DataConversionOptions,
    ) -> ValueResult<Vec<T>>
    where
        T: DataConversionTarget,
    {
        match self.to_list_with(options) {
            Err(ValueError::Missing(missing))
                if missing.is_defaultable_for_conversion() =>
            {
                Ok(default.into_value_default())
            }
            result => result,
        }
    }

    /// Converts all values with `options`, or calls `default` when storage is
    /// unset or conversion reports a missing value.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Target element conversion type.
    /// * `F` - Deferred fallback producing the complete list.
    ///
    /// # Parameters
    ///
    /// * `default` - Callback invoked for unset storage or a conversion-missing
    ///   result.
    /// * `options` - Conversion options forwarded to the shared converter.
    ///
    /// # Returns
    ///
    /// The converted list or the callback result.
    ///
    /// # Errors
    ///
    /// Preserves concrete-value conversion errors without invoking the
    /// callback.
    #[inline]
    pub fn to_list_or_else_with<T, F>(
        &self,
        default: F,
        options: &DataConversionOptions,
    ) -> ValueResult<Vec<T>>
    where
        T: DataConversionTarget,
        F: FnOnce() -> Vec<T>,
    {
        match self.to_list_with(options) {
            Err(ValueError::Missing(missing))
                if missing.is_defaultable_for_conversion() =>
            {
                Ok(default())
            }
            result => result,
        }
    }
}