qubit-value 0.13.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.
// =============================================================================

//! Borrowed V1 payload serialization.

#[cfg(feature = "json")]
use std::io::Write;

#[cfg(feature = "chrono")]
use chrono::Datelike;
#[cfg(feature = "json")]
use qubit_budget::json::JsonEncodeLimits;
#[cfg(feature = "json")]
use qubit_budget::json::JsonEncodeSession;
#[cfg(feature = "json")]
use qubit_json::encode::JsonEncoder;
use serde::Serialize;
use serde::Serializer;

use super::ValueWireEncodeError;
#[cfg(feature = "json")]
use super::ValueWireEncodePreflight;
use super::WireShapeRef;
use super::internal::WireSourceRef;
use crate::MultiValues;
use crate::Value;
use crate::ValueContainer;
use crate::multi_values::MultiValuesRepr;
use crate::value::ValueRepr;
#[cfg(feature = "big-decimal")]
use crate::wire::MAX_BIG_DECIMAL_ABSOLUTE_SCALE;
#[cfg(feature = "big-decimal")]
use crate::wire::is_valid_big_decimal_scale;
#[cfg(feature = "json")]
use crate::wire::json::validate_numbers;
#[cfg(feature = "chrono")]
use crate::wire::validate_instant_year;

/// Borrowed unversioned V1 payload for serialization without cloning.
///
/// Runtime JSON numbers must round trip to the same `serde_json::Number` under
/// the strict `qubit-json` number model. A number that would change identity
/// returns the JSON-gated `JsonNumberNotRoundTrippable` error; the error does
/// not expose the number text.
///
/// Use one of the fallible constructors or the corresponding `TryFrom` impl
/// to create a payload. The private representation prevents callers from
/// bypassing V1 validation by constructing an unchecked shape directly.
///
/// # Type Parameters
///
/// * `'a` - Lifetime of the runtime payload borrowed for serialization.
///
/// # Examples
///
/// ```
/// use qubit_value::{Value, ValueWirePayloadRefV1};
///
/// let value = Value::from(42_i32);
/// let payload = ValueWirePayloadRefV1::from_value(&value).unwrap();
/// let encoded = serde_json::to_string(&payload).unwrap();
/// assert_eq!(encoded, r#"{"scalar":{"int32":42}}"#);
/// let owned = qubit_value::ValueWirePayloadV1::try_from(Value::from(42_i32)).unwrap();
/// assert_eq!(encoded, serde_json::to_string(&owned).unwrap());
/// ```
#[must_use]
pub struct ValueWirePayloadRefV1<'a> {
    /// Borrowed source validated for V1 serialization.
    source: WireSourceRef<'a>,
}

impl<'a> ValueWirePayloadRefV1<'a> {
    /// Borrows a scalar after validating the V1 wire representation
    /// constraints.
    ///
    /// # Parameters
    ///
    /// * `value` - Scalar runtime value to validate and borrow.
    ///
    /// # Returns
    ///
    /// A borrowed V1 payload preserving the scalar shape.
    ///
    /// # Errors
    ///
    /// Returns [`ValueWireEncodeError::NonFiniteFloat`] for a non-finite float,
    /// [`ValueWireEncodeError::BigDecimalScaleTooLarge`] for an unsupported
    /// decimal scale, or [`ValueWireEncodeError::InstantYearOutOfRange`] when
    /// an Instant's UTC year is outside 0 through 9999.
    /// With the `json` feature, returns `JsonNumberNotRoundTrippable` if a
    /// runtime JSON number, including a nested number, cannot preserve its
    /// `serde_json::Number` identity under the V1 number model.
    pub fn from_value(value: &'a Value) -> Result<Self, ValueWireEncodeError> {
        validate_value(value)?;
        Ok(Self {
            source: WireSourceRef::Scalar(value),
        })
    }

    /// Borrows a collection after validating the V1 wire representation
    /// constraints.
    ///
    /// # Parameters
    ///
    /// * `values` - Homogeneous runtime collection to validate and borrow.
    ///
    /// # Returns
    ///
    /// A borrowed V1 payload preserving the collection shape.
    ///
    /// # Errors
    ///
    /// Returns [`ValueWireEncodeError::NonFiniteFloat`] for a non-finite float
    /// element, [`ValueWireEncodeError::BigDecimalScaleTooLarge`] for an
    /// unsupported decimal scale, or
    /// [`ValueWireEncodeError::InstantYearOutOfRange`] when an Instant's
    /// UTC year is outside 0 through 9999.
    /// With the `json` feature, returns `JsonNumberNotRoundTrippable` if any
    /// runtime JSON number in the collection, including a nested number,
    /// cannot preserve its `serde_json::Number` identity under the V1 number
    /// model.
    pub fn from_values(values: &'a MultiValues) -> Result<Self, ValueWireEncodeError> {
        validate_values(values)?;
        Ok(Self {
            source: WireSourceRef::Collection(values),
        })
    }

    /// Borrows an explicit shape after validating the V1 wire representation
    /// constraints.
    ///
    /// # Parameters
    ///
    /// * `value` - Explicit scalar-or-collection value to validate and borrow.
    ///
    /// # Returns
    ///
    /// A borrowed V1 payload preserving the original shape.
    ///
    /// # Errors
    ///
    /// Returns [`ValueWireEncodeError::NonFiniteFloat`] for a non-finite float,
    /// [`ValueWireEncodeError::BigDecimalScaleTooLarge`] for an unsupported
    /// decimal scale, or [`ValueWireEncodeError::InstantYearOutOfRange`] when
    /// an Instant's UTC year is outside 0 through 9999.
    /// With the `json` feature, returns `JsonNumberNotRoundTrippable` if a
    /// runtime JSON number in either the scalar or collection shape, including
    /// a nested number, cannot preserve its `serde_json::Number` identity
    /// under the V1 number model.
    #[inline]
    pub fn from_container(value: &'a ValueContainer) -> Result<Self, ValueWireEncodeError> {
        match value {
            ValueContainer::Scalar(value) => Self::from_value(value),
            ValueContainer::Collection(values) => Self::from_values(values),
        }
    }

    /// Encodes the borrowed V1 payload into a compact JSON vector.
    ///
    /// # Returns
    ///
    /// Compact UTF-8 JSON bytes for this unversioned payload.
    ///
    /// # Errors
    ///
    /// Returns [`ValueWireEncodeError`] when encoding exceeds the default
    /// resource profile or Serde rejects the payload.
    #[cfg(feature = "json")]
    #[inline(always)]
    #[cfg_attr(docsrs, doc(cfg(feature = "json")))]
    pub fn to_json_vec(&self) -> Result<Vec<u8>, ValueWireEncodeError> {
        self.to_json_vec_with_limits(super::default_json_encode_limits())
    }

    /// Encodes the borrowed V1 payload with explicit JSON resource limits.
    ///
    /// # Parameters
    ///
    /// * `limits` - Resource limits enforced during JSON encoding.
    ///
    /// # Returns
    ///
    /// Compact UTF-8 JSON bytes for this unversioned payload.
    ///
    /// Runs a conservative payload preflight before encoding, then enforces
    /// `limits` authoritatively while encoding. The preflight may report a
    /// lower-bound budget error and does not bound every preparation
    /// allocation.
    ///
    /// # Errors
    ///
    /// Returns [`ValueWireEncodeError`] when the payload preflight or final
    /// encoding exceeds `limits`, or Serde rejects the payload.
    #[cfg(feature = "json")]
    #[inline]
    #[cfg_attr(docsrs, doc(cfg(feature = "json")))]
    pub fn to_json_vec_with_limits(&self, limits: JsonEncodeLimits) -> Result<Vec<u8>, ValueWireEncodeError> {
        self.check_encode_preflight(limits)?;
        let session = JsonEncodeSession::from_limits(limits);
        JsonEncoder::new(session)
            .to_vec(self)
            .map_err(ValueWireEncodeError::from)
    }

    /// Encodes the borrowed V1 payload to a writer with default limits.
    ///
    /// # Type Parameters
    ///
    /// * `W` - Destination writer type.
    ///
    /// # Parameters
    ///
    /// * `writer` - Destination receiving the complete JSON payload.
    ///
    /// # Returns
    ///
    /// `Ok(())` after the complete payload is written.
    ///
    /// The complete payload is buffered and admitted before this method writes
    /// its bytes to the destination. Preflight, serialization, or budget
    /// rejection does not write this payload. An I/O error may leave an
    /// accepted prefix in the writer; do not blindly retry a complete
    /// payload on the same destination.
    ///
    /// This method does not explicitly flush the writer. Success means the
    /// writer accepted all payload bytes, not that they were flushed,
    /// persisted, or received by a remote peer. Pass `&mut writer` to
    /// retain ownership of a buffered writer, then call `flush()` and
    /// handle its error separately. Passing an owned writer may invoke that
    /// writer's drop behavior; errors from an implicit drop-time flush are
    /// not returned by this method.
    ///
    /// # Errors
    ///
    /// Returns [`ValueWireEncodeError`] for resource, serialization, or writer
    /// failures.
    #[cfg(feature = "json")]
    #[inline(always)]
    #[cfg_attr(docsrs, doc(cfg(feature = "json")))]
    pub fn to_json_writer<W>(&self, writer: W) -> Result<(), ValueWireEncodeError>
    where
        W: Write,
    {
        self.to_json_writer_with_limits(writer, super::default_json_encode_limits())
    }

    /// Encodes the borrowed V1 payload to a writer with explicit limits.
    ///
    /// # Type Parameters
    ///
    /// * `W` - Destination writer type.
    ///
    /// # Parameters
    ///
    /// * `writer` - Destination receiving the complete JSON payload.
    /// * `limits` - Resource limits enforced during JSON encoding.
    ///
    /// # Returns
    ///
    /// `Ok(())` after the complete payload is written.
    ///
    /// Runs a conservative payload preflight before encoding, then enforces
    /// `limits` authoritatively while encoding. The preflight may report a
    /// lower-bound budget error and does not bound every preparation
    /// allocation.
    ///
    /// The complete payload is buffered and admitted before this method writes
    /// its bytes to the destination. Preflight, serialization, or budget
    /// rejection does not write this payload. An I/O error may leave an
    /// accepted prefix in the writer; do not blindly retry a complete
    /// payload on the same destination.
    ///
    /// This method does not explicitly flush the writer. Success means the
    /// writer accepted all payload bytes, not that they were flushed,
    /// persisted, or received by a remote peer. Pass `&mut writer` to
    /// retain ownership of a buffered writer, then call `flush()` and
    /// handle its error separately. Passing an owned writer may invoke that
    /// writer's drop behavior; errors from an implicit drop-time flush are
    /// not returned by this method.
    ///
    /// # Errors
    ///
    /// Returns [`ValueWireEncodeError`] when the payload preflight or final
    /// encoding exceeds `limits`, Serde rejects the payload, or `writer`
    /// rejects output.
    #[cfg(feature = "json")]
    #[inline]
    #[cfg_attr(docsrs, doc(cfg(feature = "json")))]
    pub fn to_json_writer_with_limits<W>(
        &self,
        mut writer: W,
        limits: JsonEncodeLimits,
    ) -> Result<(), ValueWireEncodeError>
    where
        W: Write,
    {
        self.check_encode_preflight(limits)?;
        let session = JsonEncodeSession::from_limits(limits);
        JsonEncoder::new(session)
            .write_buffered(&mut writer, self)
            .map_err(ValueWireEncodeError::from)
    }

    /// Returns the borrowed internal shape used by V1 serialization.
    ///
    /// # Returns
    ///
    /// A copyable borrowed view of the validated scalar-or-collection shape.
    #[must_use]
    #[inline(always)]
    pub(in crate::value_wire) fn shape(&self) -> WireShapeRef<'a> {
        match self.source {
            WireSourceRef::Scalar(value) => WireShapeRef::Scalar(value.into()),
            WireSourceRef::Collection(values) => WireShapeRef::Collection(values.into()),
        }
    }

    /// Checks the borrowed runtime payload against conservative JSON limits.
    ///
    /// # Parameters
    ///
    /// * `limits` - JSON resource limits used to check payload preparation.
    ///
    /// # Returns
    ///
    /// `Ok(())` when the conservative payload preflight accepts the source.
    ///
    /// # Errors
    ///
    /// Returns [`ValueWireEncodeError`] when a lower-bound payload estimate
    /// exceeds `limits`. The final encoder performs the authoritative check.
    #[cfg(feature = "json")]
    pub(in crate::value_wire) fn check_encode_preflight(
        &self,
        limits: JsonEncodeLimits,
    ) -> Result<(), ValueWireEncodeError> {
        let mut checker = ValueWireEncodePreflight::new(limits);
        match self.source {
            WireSourceRef::Scalar(value) => checker.check_value(value),
            WireSourceRef::Collection(values) => checker.check_values(values),
        }
        .map_err(ValueWireEncodeError::from)
    }
}

/// Validates one scalar against V1's JSON finite-float invariant.
///
/// # Parameters
///
/// * `value` - Scalar value to validate without modifying it.
///
/// # Returns
///
/// `Ok(())` when the scalar is representable by the V1 wire contract.
///
/// # Errors
///
/// Returns [`ValueWireEncodeError::NonFiniteFloat`] for a non-finite float,
/// [`ValueWireEncodeError::BigDecimalScaleTooLarge`] for an unsupported
/// arbitrary-precision decimal scale, or
/// [`ValueWireEncodeError::InstantYearOutOfRange`] for an Instant whose UTC
/// year is outside 0 through 9999.
/// With the `json` feature, returns `JsonNumberNotRoundTrippable` if a runtime
/// JSON number, including a nested number, cannot preserve its
/// `serde_json::Number` identity under the V1 number model.
pub(in crate::value_wire) fn validate_value(value: &Value) -> Result<(), ValueWireEncodeError> {
    #[cfg(feature = "json")]
    if let ValueRepr::Json(value) = &value.repr {
        validate_numbers(value)?;
    }
    #[cfg(feature = "chrono")]
    if let ValueRepr::Instant(value) = &value.repr {
        validate_instant_year(value.year())?;
    }
    #[cfg(feature = "big-decimal")]
    if let ValueRepr::BigDecimal(value) = &value.repr {
        validate_big_decimal_scale(value.as_bigint_and_scale().1)?;
    }
    let non_finite = matches!(&value.repr, ValueRepr::Float32(value) if !value.is_finite())
        || matches!(&value.repr, ValueRepr::Float64(value) if !value.is_finite());
    if non_finite {
        return Err(ValueWireEncodeError::NonFiniteFloat {
            data_type: value.data_type(),
        });
    }
    Ok(())
}

/// Validates one collection against the V1 wire representation constraints.
///
/// # Parameters
///
/// * `values` - Collection to validate without modifying it.
///
/// # Returns
///
/// `Ok(())` when every element is representable by the V1 wire contract.
///
/// # Errors
///
/// Returns [`ValueWireEncodeError::NonFiniteFloat`] for a non-finite float
/// element, [`ValueWireEncodeError::BigDecimalScaleTooLarge`] for an
/// unsupported arbitrary-precision decimal scale, or
/// [`ValueWireEncodeError::InstantYearOutOfRange`] for an Instant whose UTC
/// year is outside 0 through 9999.
/// With the `json` feature, returns `JsonNumberNotRoundTrippable` if any
/// runtime JSON number in the collection, including a nested number, cannot
/// preserve its `serde_json::Number` identity under the V1 number model.
pub(in crate::value_wire) fn validate_values(values: &MultiValues) -> Result<(), ValueWireEncodeError> {
    #[cfg(feature = "json")]
    if let MultiValuesRepr::Json(values) = &values.repr {
        for value in values {
            validate_numbers(value)?;
        }
    }
    #[cfg(feature = "chrono")]
    if let MultiValuesRepr::Instant(values) = &values.repr {
        for value in values {
            validate_instant_year(value.year())?;
        }
    }
    #[cfg(feature = "big-decimal")]
    if let MultiValuesRepr::BigDecimal(values) = &values.repr {
        for value in values {
            validate_big_decimal_scale(value.as_bigint_and_scale().1)?;
        }
    }
    let non_finite = match &values.repr {
        MultiValuesRepr::Float32(values) => values.iter().any(|value| !value.is_finite()),
        MultiValuesRepr::Float64(values) => values.iter().any(|value| !value.is_finite()),
        _ => false,
    };
    if non_finite {
        return Err(ValueWireEncodeError::NonFiniteFloat {
            data_type: values.data_type(),
        });
    }
    Ok(())
}

/// Validates the decimal exponent accepted by V1's bounded payload format.
///
/// # Parameters
///
/// * `scale` - Decimal scale to compare with the V1 inclusive bound.
///
/// # Returns
///
/// `Ok(())` when the scale is within the supported magnitude.
///
/// # Errors
///
/// Returns [`ValueWireEncodeError::BigDecimalScaleTooLarge`] when `scale`
/// exceeds the V1 bound.
#[cfg(feature = "big-decimal")]
#[inline]
fn validate_big_decimal_scale(scale: i64) -> Result<(), ValueWireEncodeError> {
    if is_valid_big_decimal_scale(scale) {
        return Ok(());
    }
    Err(ValueWireEncodeError::BigDecimalScaleTooLarge {
        scale,
        maximum_absolute_scale: MAX_BIG_DECIMAL_ABSOLUTE_SCALE,
    })
}

impl<'a> TryFrom<&'a Value> for ValueWirePayloadRefV1<'a> {
    /// V1 representation validation failure; the borrowed input is unchanged.
    type Error = ValueWireEncodeError;

    /// Borrows and validates a scalar.
    ///
    /// # Parameters
    ///
    /// * `value` - Scalar runtime value to validate and borrow.
    ///
    /// # Returns
    ///
    /// A validated V1 payload borrowing the original input without cloning.
    ///
    /// # Errors
    ///
    /// Returns the representation validation errors documented by
    /// [`Self::from_value`].
    #[inline]
    fn try_from(value: &'a Value) -> Result<Self, Self::Error> {
        Self::from_value(value)
    }
}

impl<'a> TryFrom<&'a MultiValues> for ValueWirePayloadRefV1<'a> {
    /// V1 representation validation failure; the borrowed input is unchanged.
    type Error = ValueWireEncodeError;

    /// Borrows and validates a collection.
    ///
    /// # Parameters
    ///
    /// * `values` - Homogeneous runtime collection to validate and borrow.
    ///
    /// # Returns
    ///
    /// A validated V1 payload borrowing the original input without cloning.
    ///
    /// # Errors
    ///
    /// Returns the representation validation errors documented by
    /// [`Self::from_values`].
    #[inline]
    fn try_from(values: &'a MultiValues) -> Result<Self, Self::Error> {
        Self::from_values(values)
    }
}

impl<'a> TryFrom<&'a ValueContainer> for ValueWirePayloadRefV1<'a> {
    /// V1 representation validation failure; the borrowed input is unchanged.
    type Error = ValueWireEncodeError;

    /// Borrows and validates an explicit shape.
    ///
    /// # Parameters
    ///
    /// * `value` - Explicit scalar-or-collection value to validate and borrow.
    ///
    /// # Returns
    ///
    /// A validated V1 payload borrowing the original input without cloning.
    ///
    /// # Errors
    ///
    /// Returns the representation validation errors documented by
    /// [`Self::from_container`].
    #[inline]
    fn try_from(value: &'a ValueContainer) -> Result<Self, Self::Error> {
        Self::from_container(value)
    }
}

impl Serialize for ValueWirePayloadRefV1<'_> {
    /// Serializes the borrowed unversioned V1 shape without cloning its source.
    ///
    /// # Type Parameters
    ///
    /// * `S` - Serializer determining the output format and error type.
    ///
    /// # Parameters
    ///
    /// * `serializer` - Destination serializer consumed by this operation.
    ///
    /// # Returns
    ///
    /// The serializer's success value after emitting the scalar or collection.
    ///
    /// # Errors
    ///
    /// Returns `S::Error` if the serializer rejects the borrowed wire shape.
    #[inline]
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        self.shape().serialize(serializer)
    }
}