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

//! Public DTO for the stable version-one JSON wire contract.

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

#[cfg(feature = "json")]
use qubit_budget::json::JsonDecodeLimits;
#[cfg(feature = "json")]
use qubit_budget::json::JsonDecodeSession;
#[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::VALUE_WIRE_V1_VERSION;
#[cfg(feature = "json")]
use super::ValueWireDecodeError;
use super::ValueWireEncodeError;
#[cfg(feature = "json")]
use super::ValueWireEncodePreflight;
use super::ValueWirePayloadV1;
use super::serialize_wire;
use crate::MultiValues;
use crate::Value;
use crate::ValueContainer;

/// Stable version-one wire DTO for a scalar or homogeneous collection.
///
/// Canonical JSON output is byte-stable for the same value under the
/// supported `serde_json` version and configuration, with canonical field
/// and object-key order, including recursively nested JSON objects. Other
/// Serde formats may represent this DTO, but their bytes are outside this
/// stability contract. See the [crate documentation](crate).
///
/// V1 is closed: existing tags, shapes, and payload representations cannot
/// change, and future runtime data types require a new wire version instead
/// of extending V1.
///
/// Runtime JSON numbers are accepted only when V1 can reconstruct the same
/// `serde_json::Number` under the strict `qubit-json` number model. Numbers
/// that would change identity when round-tripped return the JSON-gated
/// `JsonNumberNotRoundTrippable` error. This error does not expose the number
/// text.
///
/// Deserialization is intentionally available through
/// [`crate::ValueWireV1Seed`], which lets a bounded decoder control the
/// complete input and structure.
///
/// # Examples
///
/// ```
/// use qubit_value::{Value, ValueWireV1};
///
/// let wire = ValueWireV1::try_from(Value::from(42_i32)).unwrap();
/// let encoded = serde_json::to_string(&wire).unwrap();
/// assert_eq!(encoded, r#"{"version":1,"value":{"scalar":{"int32":42}}}"#);
/// assert_eq!(wire.into_container().get_first::<i32>().unwrap(), 42);
/// ```
#[must_use]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ValueWireV1 {
    /// Explicit runtime shape and typed payload represented by this DTO.
    value: ValueWirePayloadV1,
}

impl ValueWireV1 {
    /// Numeric version emitted and accepted by this DTO.
    pub const VERSION: u8 = VALUE_WIRE_V1_VERSION;

    /// Creates a V1 DTO from an already validated V1 payload.
    ///
    /// # Parameters
    ///
    /// * `value` - Validated [`ValueWirePayloadV1`] moved into the envelope,
    ///   preserving its exact runtime type and scalar-or-collection shape.
    ///
    /// # Returns
    ///
    /// A V1 DTO containing `value`.
    #[inline(always)]
    pub const fn new(value: ValueWirePayloadV1) -> Self {
        Self { value }
    }

    /// Decodes a V1 JSON wire value using the default structural limits.
    ///
    /// The complete input length and decoded structure are checked before the
    /// value is returned. Embedded protocols should share one
    /// [`qubit_budget::json::JsonDecodeSession`] across their complete
    /// document.
    ///
    /// # Parameters
    ///
    /// * `input` - Complete UTF-8 JSON document to decode.
    ///
    /// # Returns
    ///
    /// The decoded V1 wire DTO.
    ///
    /// # Errors
    ///
    /// Returns a limit error when the input or decoded structure is too large,
    /// [`ValueWireDecodeError::UnsupportedVersion`] when the envelope declares
    /// another supported-width version, or
    /// [`ValueWireDecodeError::Syntax`] when the input is not one valid JSON
    /// document, or [`ValueWireDecodeError::InvalidJson`] when valid JSON
    /// cannot be decoded as a V1 wire value.
    #[cfg(feature = "json")]
    #[inline]
    #[cfg_attr(docsrs, doc(cfg(feature = "json")))]
    pub fn decode_json_slice(input: &[u8]) -> Result<Self, ValueWireDecodeError> {
        Self::decode_json_slice_with_limits(input, Self::default_json_decode_limits())
    }

    /// Decodes a V1 JSON wire value using explicit structural limits.
    ///
    /// The complete input length and decoded structure are checked before the
    /// value is returned. Embedded values should be checked through the outer
    /// protocol's shared [`qubit_budget::json::JsonDecodeSession`].
    ///
    /// # Parameters
    ///
    /// * `input` - Complete UTF-8 JSON document to decode.
    /// * `limits` - Shared encoded-input and structural limits.
    ///
    /// # Returns
    ///
    /// The decoded V1 wire DTO.
    ///
    /// # Errors
    ///
    /// Returns a limit error when `input` or its decoded structure exceeds
    /// `limits`, [`ValueWireDecodeError::UnsupportedVersion`] when the envelope
    /// declares another supported-width version,
    /// [`ValueWireDecodeError::Syntax`] when the input is not one valid JSON
    /// document, or [`ValueWireDecodeError::InvalidJson`] when valid JSON
    /// cannot be decoded as a V1 wire value.
    #[cfg(feature = "json")]
    #[inline]
    #[cfg_attr(docsrs, doc(cfg(feature = "json")))]
    pub fn decode_json_slice_with_limits(input: &[u8], limits: JsonDecodeLimits) -> Result<Self, ValueWireDecodeError> {
        let session = JsonDecodeSession::from_limits(limits);
        super::decode_wire_json_slice_with_session(input, session)
    }

    /// Returns the default JSON resource profile for complete V1 documents.
    ///
    /// # Returns
    ///
    /// Decode limits suitable for one standalone V1 envelope.
    #[cfg(feature = "json")]
    #[must_use = "the V1 JSON profile should be applied to a budget"]
    #[inline]
    #[cfg_attr(docsrs, doc(cfg(feature = "json")))]
    pub fn default_json_decode_limits() -> JsonDecodeLimits {
        super::default_json_decode_limits()
    }

    /// Returns the default JSON resource profile for encoding V1 documents.
    ///
    /// # Returns
    ///
    /// Encode limits suitable for one standalone V1 envelope.
    #[cfg(feature = "json")]
    #[must_use = "the V1 JSON profile should be applied to an encode session"]
    #[inline(always)]
    #[cfg_attr(docsrs, doc(cfg(feature = "json")))]
    pub fn default_json_encode_limits() -> JsonEncodeLimits {
        super::default_json_encode_limits()
    }

    /// Returns the runtime container represented by this DTO.
    ///
    /// # Returns
    ///
    /// A shared reference to the preserved runtime container.
    #[must_use = "the borrowed value container should be used"]
    #[inline]
    pub const fn container(&self) -> &ValueContainer {
        self.value.container()
    }

    /// Encodes this V1 document into a compact JSON vector with default limits.
    ///
    /// # Returns
    ///
    /// The encoded complete V1 document.
    ///
    /// # Errors
    ///
    /// Returns [`ValueWireEncodeError::Budget`] when the document exceeds the
    /// default JSON resource profile.
    #[cfg(feature = "json")]
    #[inline]
    #[cfg_attr(docsrs, doc(cfg(feature = "json")))]
    pub fn to_json_vec(&self) -> Result<Vec<u8>, ValueWireEncodeError> {
        self.to_json_vec_with_limits(Self::default_json_encode_limits())
    }

    /// Encodes this V1 document into a bounded compact JSON vector.
    ///
    /// # Parameters
    ///
    /// * `limits` - Resource limits enforced during encoding.
    ///
    /// # Returns
    ///
    /// Compact UTF-8 JSON bytes for the complete V1 document.
    ///
    /// Runs a conservative payload preflight before encoding, then enforces
    /// `limits` authoritatively while encoding the full envelope. The preflight
    /// may report a lower-bound budget error and does not bound every
    /// preparation allocation.
    ///
    /// # Errors
    ///
    /// Returns [`ValueWireEncodeError`] when preflight or final encoding
    /// exceeds `limits`, or the document cannot be serialized.
    #[cfg(feature = "json")]
    #[cfg_attr(docsrs, doc(cfg(feature = "json")))]
    pub fn to_json_vec_with_limits(&self, limits: JsonEncodeLimits) -> Result<Vec<u8>, ValueWireEncodeError> {
        ValueWireEncodePreflight::new(limits)
            .check_container(self.container())
            .map_err(ValueWireEncodeError::from)?;
        let session = JsonEncodeSession::from_limits(limits);
        JsonEncoder::new(session)
            .to_vec(self)
            .map_err(ValueWireEncodeError::from)
    }

    /// Encodes this V1 document to a writer with default limits.
    ///
    /// # Type Parameters
    ///
    /// * `W` - Destination writer type.
    ///
    /// # Parameters
    ///
    /// * `writer` - Destination receiving the complete JSON document.
    ///
    /// # Returns
    ///
    /// `Ok(())` after the complete document is written.
    ///
    /// The complete document is buffered and admitted before this method writes
    /// its bytes to the destination. Preflight, serialization, or budget
    /// rejection does not write this document. An I/O error may leave an
    /// accepted prefix in the writer; do not blindly retry a complete
    /// document on the same destination.
    ///
    /// This method does not explicitly flush the writer. Success means the
    /// writer accepted all document 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::Budget`] for resource-limit failures or
    /// [`ValueWireEncodeError::Io`] when `writer` rejects output.
    #[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, Self::default_json_encode_limits())
    }

    /// Encodes this V1 document to a writer after enforcing JSON budgets.
    ///
    /// # Type Parameters
    ///
    /// * `W` - Destination writer type.
    ///
    /// # Parameters
    ///
    /// * `writer` - Destination receiving the complete JSON document.
    /// * `limits` - Resource limits enforced during encoding.
    ///
    /// # Returns
    ///
    /// `Ok(())` after the complete document is written.
    ///
    /// Runs a conservative payload preflight before encoding, then enforces
    /// `limits` authoritatively while encoding the full envelope. The preflight
    /// may report a lower-bound budget error and does not bound every
    /// preparation allocation.
    ///
    /// The complete document is buffered and admitted before this method writes
    /// its bytes to the destination. Preflight, serialization, or budget
    /// rejection does not write this document. An I/O error may leave an
    /// accepted prefix in the writer; do not blindly retry a complete
    /// document on the same destination.
    ///
    /// This method does not explicitly flush the writer. Success means the
    /// writer accepted all document 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 preflight or final encoding
    /// exceeds `limits`, the document cannot be serialized, or `writer`
    /// rejects output.
    #[cfg(feature = "json")]
    #[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,
    {
        ValueWireEncodePreflight::new(limits)
            .check_container(self.container())
            .map_err(ValueWireEncodeError::from)?;
        let session = JsonEncodeSession::from_limits(limits);
        JsonEncoder::new(session)
            .write_buffered(&mut writer, self)
            .map_err(ValueWireEncodeError::from)
    }

    /// Consumes the DTO and returns its runtime container.
    ///
    /// # Returns
    ///
    /// The preserved runtime container.
    #[inline(always)]
    pub fn into_container(self) -> ValueContainer {
        self.value.into_container()
    }
}

impl TryFrom<Value> for ValueWireV1 {
    /// Failure to represent the consumed runtime value under the V1 contract.
    type Error = ValueWireEncodeError;

    /// Wraps a runtime scalar in a V1 DTO.
    ///
    /// # Parameters
    ///
    /// * `value` - Runtime scalar to validate and consume.
    ///
    /// # Returns
    ///
    /// A V1 DTO preserving the input type and shape.
    ///
    /// # Errors
    ///
    /// Returns [`ValueWireEncodeError::NonFiniteFloat`] for a non-finite
    /// float, [`ValueWireEncodeError::BigDecimalScaleTooLarge`] for a decimal
    /// whose exponent is outside V1's supported range, or
    /// [`ValueWireEncodeError::InstantYearOutOfRange`] for an instant outside
    /// the supported UTC year range.
    /// 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.
    #[inline(always)]
    fn try_from(value: Value) -> Result<Self, Self::Error> {
        ValueWirePayloadV1::try_from(value).map(Self::new)
    }
}

impl TryFrom<MultiValues> for ValueWireV1 {
    /// Failure to represent the consumed runtime value under the V1 contract.
    type Error = ValueWireEncodeError;

    /// Wraps a runtime collection in a V1 DTO.
    ///
    /// # Parameters
    ///
    /// * `values` - Homogeneous collection to validate and consume.
    ///
    /// # Returns
    ///
    /// A V1 DTO preserving the input type and shape.
    ///
    /// # Errors
    ///
    /// Returns [`ValueWireEncodeError::NonFiniteFloat`] for a non-finite
    /// float element, [`ValueWireEncodeError::BigDecimalScaleTooLarge`] for
    /// an element whose decimal exponent is outside V1's supported range, or
    /// [`ValueWireEncodeError::InstantYearOutOfRange`] for an instant outside
    /// the supported UTC year range.
    /// 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.
    #[inline(always)]
    fn try_from(values: MultiValues) -> Result<Self, Self::Error> {
        ValueWirePayloadV1::try_from(values).map(Self::new)
    }
}

impl TryFrom<ValueContainer> for ValueWireV1 {
    /// Failure to represent the consumed runtime value under the V1 contract.
    type Error = ValueWireEncodeError;

    /// Wraps an explicit runtime shape in a V1 DTO.
    ///
    /// # Parameters
    ///
    /// * `value` - Scalar-or-collection container to validate and consume.
    ///
    /// # Returns
    ///
    /// A V1 DTO preserving the input type and shape.
    ///
    /// # Errors
    ///
    /// Returns [`ValueWireEncodeError::NonFiniteFloat`] for a non-finite
    /// float, [`ValueWireEncodeError::BigDecimalScaleTooLarge`] for a decimal
    /// whose exponent is outside V1's supported range, or
    /// [`ValueWireEncodeError::InstantYearOutOfRange`] for an instant outside
    /// the supported UTC year range.
    /// 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]
    fn try_from(value: ValueContainer) -> Result<Self, Self::Error> {
        ValueWirePayloadV1::try_from(value).map(Self::new)
    }
}

impl From<ValueWireV1> for ValueContainer {
    /// Unwraps the runtime container from a V1 DTO.
    ///
    /// # Parameters
    ///
    /// * `value` - Owned DTO whose container is moved into the result.
    ///
    /// # Returns
    ///
    /// The preserved runtime container without cloning its payload.
    #[inline(always)]
    fn from(value: ValueWireV1) -> Self {
        value.into_container()
    }
}

impl Serialize for ValueWireV1 {
    /// Serializes the contained runtime shape through the V1 contract.
    ///
    /// # Type Parameters
    ///
    /// * `S` - Serde serializer defining the output format and error type.
    ///
    /// # Parameters
    ///
    /// * `serializer` - Serializer consumed to emit the versioned envelope.
    ///
    /// # Returns
    ///
    /// The serializer's completed output on success.
    ///
    /// # Errors
    ///
    /// Returns the serializer's error if it cannot encode the envelope or
    /// payload.
    #[inline(always)]
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serialize_wire(self.value.container().into(), serializer)
    }
}