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

//! Canonical Serde payload adapters for value variants.

#[cfg(any(feature = "chrono", feature = "url"))]
use serde::Deserialize;
#[cfg(any(feature = "chrono", feature = "url"))]
use serde::Deserializer;
#[cfg(any(feature = "chrono", feature = "url"))]
use serde::Serializer;

pub(crate) use crate::finite_float::float32;
pub(crate) use crate::finite_float::float32_vec;
pub(crate) use crate::finite_float::float64;
pub(crate) use crate::finite_float::float64_vec;
pub(crate) use crate::wide_integer::int128;
pub(crate) use crate::wide_integer::int128_vec;
pub(crate) use crate::wide_integer::uint128;
pub(crate) use crate::wide_integer::uint128_vec;

pub(crate) mod string_map;
pub(crate) mod string_map_vec;

/// Serializes JSON values by recursively ordering every object key.
#[cfg(feature = "json")]
pub(crate) mod json;

/// Serializes JSON collections by recursively ordering every object key.
#[cfg(feature = "json")]
pub(crate) mod json_vec;

#[cfg(feature = "big-integer")]
mod decimal;

mod internal;

#[cfg(feature = "big-decimal")]
use self::internal::BigDecimalPayload;
use self::internal::DurationPayload;

/// Largest decimal exponent magnitude accepted by the V1 wire format.
#[cfg(feature = "big-decimal")]
pub(crate) const MAX_BIG_DECIMAL_ABSOLUTE_SCALE: i64 = 150_000;

/// Returns whether a decimal exponent is representable by the bounded V1
/// format.
///
/// # Parameters
///
/// * `scale` - Signed decimal scale to compare with the V1 bound.
///
/// # Returns
///
/// `true` when the absolute scale is within the inclusive V1 limit.
#[must_use]
#[cfg(feature = "big-decimal")]
#[inline(always)]
pub(crate) const fn is_valid_big_decimal_scale(scale: i64) -> bool {
    scale.unsigned_abs() <= MAX_BIG_DECIMAL_ABSOLUTE_SCALE as u64
}

/// Serializes and validates canonical scalar string payloads.
///
/// # Type Parameters
///
/// * `S` - Destination serializer type.
/// * `T` - Source value type.
/// * `F` - Canonical formatter type.
///
/// # Parameters
///
/// * `value` - Source value to format.
/// * `serializer` - Destination serializer.
/// * `format` - Formatter producing the canonical V1 string.
///
/// # Returns
///
/// The destination serializer's result.
///
/// # Errors
///
/// Returns `S::Error` when the serializer rejects the canonical string.
#[cfg(any(feature = "chrono", feature = "url"))]
fn serialize_canonical<S, T, F>(value: &T, serializer: S, format: F) -> Result<S::Ok, S::Error>
where
    S: Serializer,
    F: FnOnce(&T) -> String,
{
    serializer.serialize_str(&format(value))
}

/// Deserializes a scalar string only when it is already in canonical form.
///
/// # Type Parameters
///
/// * `D` - Source deserializer type.
/// * `T` - Decoded value type.
/// * `P` - Parser type.
/// * `F` - Canonical formatter type.
///
/// # Parameters
///
/// * `deserializer` - Source deserializer.
/// * `parse` - Parser converting source text into `T`.
/// * `format` - Formatter reproducing canonical text from `T`.
///
/// # Returns
///
/// The decoded value when its input text is canonical.
///
/// # Errors
///
/// Returns `D::Error` for deserialization, parsing, or non-canonical text.
#[cfg(any(feature = "chrono", feature = "url"))]
fn deserialize_canonical<'de, D, T, P, F>(deserializer: D, parse: P, format: F) -> Result<T, D::Error>
where
    D: Deserializer<'de>,
    P: FnOnce(&str) -> Result<T, String>,
    F: FnOnce(&T) -> String,
{
    use serde::de::Error as _;

    let input = String::deserialize(deserializer)?;
    let value = parse(&input).map_err(D::Error::custom)?;
    if format(&value) != input {
        return Err(D::Error::custom("non-canonical V1 string payload"));
    }
    Ok(value)
}

/// Serializes a collection through a canonical scalar formatter.
///
/// # Type Parameters
///
/// * `S` - Destination serializer type.
/// * `T` - Source element type.
/// * `F` - Canonical formatter type.
///
/// # Parameters
///
/// * `values` - Source elements to serialize in order.
/// * `serializer` - Destination serializer.
/// * `format` - Formatter producing each canonical V1 string.
///
/// # Returns
///
/// The destination serializer's sequence result.
///
/// # Errors
///
/// Returns `S::Error` when sequence serialization fails.
#[cfg(any(feature = "chrono", feature = "url"))]
fn serialize_canonical_vec<S, T, F>(values: &[T], serializer: S, format: F) -> Result<S::Ok, S::Error>
where
    S: Serializer,
    F: Fn(&T) -> String,
{
    serializer.collect_seq(values.iter().map(format))
}

/// Deserializes canonical string collection payloads.
///
/// # Type Parameters
///
/// * `D` - Source deserializer type.
/// * `T` - Decoded element type.
/// * `P` - Parser type.
/// * `F` - Canonical formatter type.
///
/// # Parameters
///
/// * `deserializer` - Source deserializer.
/// * `parse` - Parser converting each source string into `T`.
/// * `format` - Formatter reproducing canonical text from `T`.
///
/// # Returns
///
/// Decoded elements in their source order.
///
/// # Errors
///
/// Returns `D::Error` for deserialization, parsing, or non-canonical text.
#[cfg(any(feature = "chrono", feature = "url"))]
fn deserialize_canonical_vec<'de, D, T, P, F>(deserializer: D, parse: P, format: F) -> Result<Vec<T>, D::Error>
where
    D: Deserializer<'de>,
    P: Fn(&str) -> Result<T, String>,
    F: Fn(&T) -> String,
{
    use serde::de::Error as _;

    Vec::<String>::deserialize(deserializer)?
        .into_iter()
        .map(|input| {
            let value = parse(&input).map_err(D::Error::custom)?;
            if format(&value) != input {
                return Err(D::Error::custom("non-canonical V1 string payload"));
            }
            Ok(value)
        })
        .collect()
}

/// Defines canonical scalar and vector wire adapters for one chrono type.
#[cfg(feature = "chrono")]
macro_rules! define_chrono_wire {
    ($scalar:ident, $vector:ident, $type:ty, $parse:expr, $format:expr) => {
        /// Canonical scalar wire adapter generated for one chrono type.
        pub(crate) mod $scalar {
            use serde::Deserializer;
            use serde::Serializer;

            /// Serializes the chrono value through the crate-owned V1 format.
            ///
            /// # Type Parameters
            ///
            /// * `S` - Destination serializer type.
            ///
            /// # Parameters
            ///
            /// * `value` - Chrono value to serialize.
            /// * `serializer` - Destination serializer.
            ///
            /// # Returns
            ///
            /// The destination serializer's result.
            ///
            /// # Errors
            ///
            /// Returns `S::Error` when serialization fails.
            pub(crate) fn serialize<S>(value: &$type, serializer: S) -> Result<S::Ok, S::Error>
            where
                S: Serializer,
            {
                super::serialize_canonical(value, serializer, $format)
            }

            /// Deserializes the chrono value only from its canonical V1 format.
            ///
            /// # Type Parameters
            ///
            /// * `D` - Source deserializer type.
            ///
            /// # Parameters
            ///
            /// * `deserializer` - Source deserializer.
            ///
            /// # Returns
            ///
            /// The decoded chrono value.
            ///
            /// # Errors
            ///
            /// Returns `D::Error` for malformed or non-canonical input.
            pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<$type, D::Error>
            where
                D: Deserializer<'de>,
            {
                super::deserialize_canonical(deserializer, $parse, $format)
            }
        }

        /// Canonical collection wire adapter generated for one chrono type.
        pub(crate) mod $vector {
            use serde::Deserializer;
            use serde::Serializer;

            /// Serializes chrono values through the crate-owned V1 format.
            ///
            /// # Type Parameters
            ///
            /// * `S` - Destination serializer type.
            ///
            /// # Parameters
            ///
            /// * `values` - Chrono values to serialize in order.
            /// * `serializer` - Destination serializer.
            ///
            /// # Returns
            ///
            /// The destination serializer's sequence result.
            ///
            /// # Errors
            ///
            /// Returns `S::Error` when sequence serialization fails.
            pub(crate) fn serialize<S>(values: &[$type], serializer: S) -> Result<S::Ok, S::Error>
            where
                S: Serializer,
            {
                super::serialize_canonical_vec(values, serializer, $format)
            }

            /// Deserializes chrono values only from their canonical V1 format.
            ///
            /// # Type Parameters
            ///
            /// * `D` - Source deserializer type.
            ///
            /// # Parameters
            ///
            /// * `deserializer` - Source deserializer.
            ///
            /// # Returns
            ///
            /// Decoded chrono values in source order.
            ///
            /// # Errors
            ///
            /// Returns `D::Error` for malformed or non-canonical input.
            pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<Vec<$type>, D::Error>
            where
                D: Deserializer<'de>,
            {
                super::deserialize_canonical_vec(deserializer, $parse, $format)
            }
        }
    };
}

#[cfg(feature = "chrono")]
define_chrono_wire!(
    date,
    date_vec,
    chrono::NaiveDate,
    |input| chrono::NaiveDate::parse_from_str(input, "%F").map_err(|error| error.to_string()),
    |value: &chrono::NaiveDate| value.format("%F").to_string()
);

#[cfg(feature = "chrono")]
define_chrono_wire!(
    time,
    time_vec,
    chrono::NaiveTime,
    |input| chrono::NaiveTime::parse_from_str(input, "%H:%M:%S%.f").map_err(|error| error.to_string()),
    |value: &chrono::NaiveTime| value.format("%H:%M:%S%.f").to_string()
);

#[cfg(feature = "chrono")]
define_chrono_wire!(
    datetime,
    datetime_vec,
    chrono::NaiveDateTime,
    |input| chrono::NaiveDateTime::parse_from_str(input, "%Y-%m-%dT%H:%M:%S%.f").map_err(|error| error.to_string()),
    |value: &chrono::NaiveDateTime| value.format("%Y-%m-%dT%H:%M:%S%.f").to_string()
);

#[cfg(feature = "chrono")]
define_chrono_wire!(
    instant,
    instant_vec,
    chrono::DateTime<chrono::Utc>,
    |input| chrono::DateTime::parse_from_rfc3339(input)
        .map(|value| value.with_timezone(&chrono::Utc))
        .map_err(|error| error.to_string()),
    |value: &chrono::DateTime<chrono::Utc>| value.to_rfc3339_opts(chrono::SecondsFormat::AutoSi, true)
);

/// Defines canonical scalar and vector wire adapters for URL values.
#[cfg(feature = "url")]
macro_rules! define_url_wire {
    () => {
        /// Canonical scalar URL wire adapter.
        pub(crate) mod url {
            use serde::Deserializer;
            use serde::Serializer;

            /// Serializes a URL through its canonical normalized string.
            ///
            /// # Type Parameters
            ///
            /// * `S` - Destination serializer type.
            ///
            /// # Parameters
            ///
            /// * `value` - Parsed URL to serialize.
            /// * `serializer` - Destination serializer.
            ///
            /// # Returns
            ///
            /// The destination serializer's result.
            ///
            /// # Errors
            ///
            /// Returns `S::Error` when serialization fails.
            pub(crate) fn serialize<S>(value: &::url::Url, serializer: S) -> Result<S::Ok, S::Error>
            where
                S: Serializer,
            {
                super::serialize_canonical(value, serializer, |value: &::url::Url| value.as_str().to_owned())
            }

            /// Deserializes only a canonical normalized URL string.
            ///
            /// # Type Parameters
            ///
            /// * `D` - Source deserializer type.
            ///
            /// # Parameters
            ///
            /// * `deserializer` - Source deserializer.
            ///
            /// # Returns
            ///
            /// The parsed canonical URL.
            ///
            /// # Errors
            ///
            /// Returns `D::Error` for invalid or non-canonical URL text.
            pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<::url::Url, D::Error>
            where
                D: Deserializer<'de>,
            {
                super::deserialize_canonical(
                    deserializer,
                    |input| ::url::Url::parse(input).map_err(|error| error.to_string()),
                    |value: &::url::Url| value.as_str().to_owned(),
                )
            }
        }

        /// Canonical URL collection wire adapter.
        pub(crate) mod url_vec {
            use serde::Deserializer;
            use serde::Serializer;

            /// Serializes URLs through their canonical normalized strings.
            ///
            /// # Type Parameters
            ///
            /// * `S` - Destination serializer type.
            ///
            /// # Parameters
            ///
            /// * `values` - Parsed URLs to serialize in order.
            /// * `serializer` - Destination serializer.
            ///
            /// # Returns
            ///
            /// The destination serializer's sequence result.
            ///
            /// # Errors
            ///
            /// Returns `S::Error` when sequence serialization fails.
            pub(crate) fn serialize<S>(values: &[::url::Url], serializer: S) -> Result<S::Ok, S::Error>
            where
                S: Serializer,
            {
                super::serialize_canonical_vec(values, serializer, |value: &::url::Url| value.as_str().to_owned())
            }

            /// Deserializes only canonical normalized URL strings.
            ///
            /// # Type Parameters
            ///
            /// * `D` - Source deserializer type.
            ///
            /// # Parameters
            ///
            /// * `deserializer` - Source deserializer.
            ///
            /// # Returns
            ///
            /// Parsed canonical URLs in source order.
            ///
            /// # Errors
            ///
            /// Returns `D::Error` for invalid or non-canonical URL text.
            pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<Vec<::url::Url>, D::Error>
            where
                D: Deserializer<'de>,
            {
                super::deserialize_canonical_vec(
                    deserializer,
                    |input| ::url::Url::parse(input).map_err(|error| error.to_string()),
                    |value: &::url::Url| value.as_str().to_owned(),
                )
            }
        }
    };
}

#[cfg(feature = "url")]
define_url_wire!();

/// Defines canonical scalar and vector wire adapters for a decimal-backed type.
#[cfg(feature = "big-integer")]
macro_rules! define_decimal_serde {
    ($scalar_module:ident, $vector_module:ident, $type:ty) => {
        /// Canonical scalar wire adapter generated for one decimal-backed type.
        pub(crate) mod $scalar_module {
            use serde::Deserializer;
            use serde::Serializer;

            use super::decimal;

            /// Serializes a decimal value as a canonical decimal string.
            ///
            /// # Type Parameters
            ///
            /// * `S` - Destination serializer type.
            ///
            /// # Parameters
            ///
            /// * `value` - Decimal-backed value to serialize.
            /// * `serializer` - Destination serializer.
            ///
            /// # Returns
            ///
            /// The destination serializer's result.
            ///
            /// # Errors
            ///
            /// Returns `S::Error` when serialization fails.
            pub(crate) fn serialize<S>(value: &$type, serializer: S) -> Result<S::Ok, S::Error>
            where
                S: Serializer,
            {
                decimal::serialize(value, serializer)
            }

            /// Deserializes a decimal value from a canonical decimal string.
            ///
            /// # Type Parameters
            ///
            /// * `D` - Source deserializer type.
            ///
            /// # Parameters
            ///
            /// * `deserializer` - Source deserializer.
            ///
            /// # Returns
            ///
            /// The decoded decimal-backed value.
            ///
            /// # Errors
            ///
            /// Returns `D::Error` for malformed or non-canonical input.
            pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<$type, D::Error>
            where
                D: Deserializer<'de>,
            {
                decimal::deserialize(deserializer)
            }
        }

        /// Canonical collection wire adapter generated for one decimal-backed type.
        pub(crate) mod $vector_module {
            use serde::Deserializer;
            use serde::Serializer;

            use super::decimal;

            /// Serializes decimal values as canonical decimal strings.
            ///
            /// # Type Parameters
            ///
            /// * `S` - Destination serializer type.
            ///
            /// # Parameters
            ///
            /// * `values` - Decimal-backed values to serialize in order.
            /// * `serializer` - Destination serializer.
            ///
            /// # Returns
            ///
            /// The destination serializer's sequence result.
            ///
            /// # Errors
            ///
            /// Returns `S::Error` when sequence serialization fails.
            pub(crate) fn serialize<S>(values: &[$type], serializer: S) -> Result<S::Ok, S::Error>
            where
                S: Serializer,
            {
                decimal::serialize_vec(values, serializer)
            }

            /// Deserializes decimal values from canonical decimal strings.
            ///
            /// # Type Parameters
            ///
            /// * `D` - Source deserializer type.
            ///
            /// # Parameters
            ///
            /// * `deserializer` - Source deserializer.
            ///
            /// # Returns
            ///
            /// Decoded decimal-backed values in source order.
            ///
            /// # Errors
            ///
            /// Returns `D::Error` for malformed or non-canonical input.
            pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<Vec<$type>, D::Error>
            where
                D: Deserializer<'de>,
            {
                decimal::deserialize_vec(deserializer)
            }
        }
    };
}

#[cfg(feature = "big-integer")]
define_decimal_serde!(big_integer, big_integer_vec, num_bigint::BigInt);

/// Canonical arbitrary-precision decimal scalar payload adapter.
#[cfg(feature = "big-decimal")]
pub(crate) mod big_decimal {
    use bigdecimal::BigDecimal;
    use serde::Deserialize;
    use serde::Deserializer;
    use serde::Serialize;
    use serde::Serializer;
    use serde::de::Error as _;
    use serde::ser::Error as _;

    use super::BigDecimalPayload;

    /// Serializes a decimal as an exact `{ coefficient, scale }` payload.
    ///
    /// # Type Parameters
    ///
    /// * `S` - Destination serializer type.
    ///
    /// # Parameters
    ///
    /// * `value` - Decimal value to serialize exactly.
    /// * `serializer` - Destination serializer.
    ///
    /// # Returns
    ///
    /// The destination serializer's result.
    ///
    /// # Errors
    ///
    /// Returns `S::Error` when the scale is out of range or serialization
    /// fails.
    pub(crate) fn serialize<S>(value: &BigDecimal, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        BigDecimalPayload::try_from(value)
            .map_err(S::Error::custom)?
            .serialize(serializer)
    }

    /// Deserializes and validates an exact decimal payload.
    ///
    /// # Type Parameters
    ///
    /// * `D` - Source deserializer type.
    ///
    /// # Parameters
    ///
    /// * `deserializer` - Source deserializer.
    ///
    /// # Returns
    ///
    /// The exact decoded decimal value.
    ///
    /// # Errors
    ///
    /// Returns `D::Error` for malformed payloads or invalid decimal scales.
    pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<BigDecimal, D::Error>
    where
        D: Deserializer<'de>,
    {
        BigDecimalPayload::deserialize(deserializer)?
            .try_into()
            .map_err(D::Error::custom)
    }
}

/// Canonical arbitrary-precision decimal collection payload adapter.
#[cfg(feature = "big-decimal")]
pub(crate) mod big_decimal_vec {
    use bigdecimal::BigDecimal;
    use serde::Deserialize;
    use serde::Deserializer;
    use serde::Serializer;
    use serde::de::Error as _;
    use serde::ser::Error as _;
    use serde::ser::SerializeSeq;

    use super::BigDecimalPayload;

    /// Serializes decimals as exact `{ coefficient, scale }` payloads.
    ///
    /// # Type Parameters
    ///
    /// * `S` - Destination serializer type.
    ///
    /// # Parameters
    ///
    /// * `values` - Decimal values to serialize in order.
    /// * `serializer` - Destination serializer.
    ///
    /// # Returns
    ///
    /// The destination serializer's sequence result.
    ///
    /// # Errors
    ///
    /// Returns `S::Error` for an out-of-range scale or serialization failure.
    pub(crate) fn serialize<S>(values: &[BigDecimal], serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut sequence = serializer.serialize_seq(Some(values.len()))?;
        for value in values {
            let payload = BigDecimalPayload::try_from(value).map_err(S::Error::custom)?;
            sequence.serialize_element(&payload)?;
        }
        sequence.end()
    }

    /// Deserializes and validates exact decimal payloads.
    ///
    /// # Type Parameters
    ///
    /// * `D` - Source deserializer type.
    ///
    /// # Parameters
    ///
    /// * `deserializer` - Source deserializer.
    ///
    /// # Returns
    ///
    /// Exact decoded decimal values in source order.
    ///
    /// # Errors
    ///
    /// Returns `D::Error` for malformed payloads or invalid decimal scales.
    pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<Vec<BigDecimal>, D::Error>
    where
        D: Deserializer<'de>,
    {
        Vec::<BigDecimalPayload>::deserialize(deserializer)?
            .into_iter()
            .map(|value| value.try_into().map_err(D::Error::custom))
            .collect()
    }
}

/// Canonical scalar duration payload adapter.
pub(crate) mod duration {
    use std::time::Duration;

    use serde::Deserialize;
    use serde::Deserializer;
    use serde::Serialize;
    use serde::Serializer;
    use serde::de::Error as _;

    use super::DurationPayload;

    /// Serializes a duration as `{ secs, nanos }`.
    ///
    /// # Type Parameters
    ///
    /// * `S` - Destination serializer type.
    ///
    /// # Parameters
    ///
    /// * `value` - Duration to decompose into seconds and nanoseconds.
    /// * `serializer` - Destination serializer.
    ///
    /// # Returns
    ///
    /// The destination serializer's result.
    ///
    /// # Errors
    ///
    /// Returns `S::Error` when serialization fails.
    pub(crate) fn serialize<S>(value: &Duration, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        DurationPayload::from(value).serialize(serializer)
    }

    /// Deserializes and validates a `{ secs, nanos }` duration payload.
    ///
    /// # Type Parameters
    ///
    /// * `D` - Source deserializer type.
    ///
    /// # Parameters
    ///
    /// * `deserializer` - Source deserializer.
    ///
    /// # Returns
    ///
    /// The decoded duration.
    ///
    /// # Errors
    ///
    /// Returns `D::Error` when decoding fails or nanoseconds are out of range.
    pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<Duration, D::Error>
    where
        D: Deserializer<'de>,
    {
        DurationPayload::deserialize(deserializer)?
            .try_into()
            .map_err(D::Error::custom)
    }
}

/// Canonical duration collection payload adapter.
pub(crate) mod duration_vec {
    use std::time::Duration;

    use serde::Deserialize;
    use serde::Deserializer;
    use serde::Serializer;
    use serde::de::Error as _;

    use super::DurationPayload;

    /// Serializes durations as a sequence of `{ secs, nanos }` payloads.
    ///
    /// # Type Parameters
    ///
    /// * `S` - Destination serializer type.
    ///
    /// # Parameters
    ///
    /// * `values` - Durations to serialize in order.
    /// * `serializer` - Destination serializer.
    ///
    /// # Returns
    ///
    /// The destination serializer's sequence result.
    ///
    /// # Errors
    ///
    /// Returns `S::Error` when sequence serialization fails.
    pub(crate) fn serialize<S>(values: &[Duration], serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.collect_seq(values.iter().map(DurationPayload::from))
    }

    /// Deserializes and validates a sequence of duration payloads.
    ///
    /// # Type Parameters
    ///
    /// * `D` - Source deserializer type.
    ///
    /// # Parameters
    ///
    /// * `deserializer` - Source deserializer.
    ///
    /// # Returns
    ///
    /// Decoded durations in source order.
    ///
    /// # Errors
    ///
    /// Returns `D::Error` when decoding fails or any nanoseconds field is out
    /// of range.
    pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<Vec<Duration>, D::Error>
    where
        D: Deserializer<'de>,
    {
        Vec::<DurationPayload>::deserialize(deserializer)?
            .into_iter()
            .map(|value| value.try_into().map_err(D::Error::custom))
            .collect()
    }
}