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
570
// =============================================================================
//    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.

/// serde_json's private arbitrary-precision number marker.
///
/// A real JSON object can use the same key, but serde_json then cannot
/// distinguish that object from an arbitrary-precision number when using
/// `deserialize_any`. V1 rejects this key in JSON payload objects before
/// encoding them.
#[cfg(feature = "json")]
pub(crate) const JSON_NUMBER_TOKEN: &str = "$serde_json::private::Number";

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

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

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

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

#[cfg(feature = "json")]
pub(crate) mod json_vec;

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

mod internal;

#[cfg(feature = "big-decimal")]
use internal::BigDecimalPayload;
use 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.
#[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.
#[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: serde::Serializer,
    F: FnOnce(&T) -> String,
{
    serializer.serialize_str(&format(value))
}

/// Deserializes a scalar string only when it is already in canonical form.
#[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: serde::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.
#[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: serde::Serializer,
    F: Fn(&T) -> String,
{
    serializer.collect_seq(values.iter().map(format))
}

/// Deserializes canonical string collection payloads.
#[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: serde::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()
}

#[cfg(feature = "chrono")]
macro_rules! define_chrono_wire {
    ($scalar:ident, $vector:ident, $type:ty, $parse:expr, $format:expr) => {
        pub(crate) mod $scalar {
            use serde::{
                Deserializer,
                Serializer,
            };

            /// Serializes the chrono value through the crate-owned V1 format.
            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.
            pub(crate) fn deserialize<'de, D>(
                deserializer: D,
            ) -> Result<$type, D::Error>
            where
                D: Deserializer<'de>,
            {
                super::deserialize_canonical(deserializer, $parse, $format)
            }
        }

        pub(crate) mod $vector {
            use serde::{
                Deserializer,
                Serializer,
            };

            /// Serializes chrono values through the crate-owned V1 format.
            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.
            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)
);

#[cfg(feature = "url")]
macro_rules! define_url_wire {
    () => {
        pub(crate) mod url {
            use serde::{
                Deserializer,
                Serializer,
            };

            /// Serializes a URL through its canonical normalized string.
            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.
            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(),
                )
            }
        }

        pub(crate) mod url_vec {
            use serde::{
                Deserializer,
                Serializer,
            };

            /// Serializes URLs through their canonical normalized strings.
            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.
            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!();

#[cfg(feature = "big-integer")]
macro_rules! define_decimal_serde {
    ($scalar_module:ident, $vector_module:ident, $type:ty) => {
        pub(crate) mod $scalar_module {
            use serde::{
                Deserializer,
                Serializer,
            };

            use super::decimal;

            /// Serializes a decimal value as a canonical decimal string.
            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.
            pub(crate) fn deserialize<'de, D>(
                deserializer: D,
            ) -> Result<$type, D::Error>
            where
                D: Deserializer<'de>,
            {
                decimal::deserialize(deserializer)
            }
        }

        pub(crate) mod $vector_module {
            use serde::{
                Deserializer,
                Serializer,
            };

            use super::decimal;

            /// Serializes decimal values as canonical decimal strings.
            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.
            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::de::Error as _;
    use serde::ser::Error as _;
    use serde::{
        Deserialize,
        Deserializer,
        Serialize,
        Serializer,
    };

    use super::BigDecimalPayload;

    /// Serializes a decimal as an exact `{ coefficient, scale }` payload.
    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.
    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::de::Error as _;
    use serde::ser::{
        Error as _,
        SerializeSeq,
    };
    use serde::{
        Deserialize,
        Deserializer,
        Serializer,
    };

    use super::BigDecimalPayload;

    /// Serializes decimals as exact `{ coefficient, scale }` payloads.
    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.
    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::de::Error as _;
    use serde::{
        Deserialize,
        Deserializer,
        Serialize,
        Serializer,
    };

    use super::DurationPayload;

    /// Serializes a duration as `{ secs, nanos }`.
    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.
    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::de::Error as _;
    use serde::{
        Deserialize,
        Deserializer,
        Serializer,
    };

    use super::DurationPayload;

    /// Serializes durations as a sequence of `{ secs, nanos }` payloads.
    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.
    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()
    }
}