qubit_value/value_wire/value_wire_ref_v1.rs
1// =============================================================================
2// Copyright (c) 2025 - 2026 Haixing Hu.
3//
4// SPDX-License-Identifier: Apache-2.0
5//
6// Licensed under the Apache License, Version 2.0.
7// =============================================================================
8
9//! Borrowed V1 envelope serialization.
10
11#[cfg(feature = "json")]
12use std::io::Write;
13
14#[cfg(feature = "json")]
15use qubit_budget::json::JsonEncodeLimits;
16#[cfg(feature = "json")]
17use qubit_budget::json::JsonEncodeSession;
18#[cfg(feature = "json")]
19use qubit_json::encode::JsonEncoder;
20use serde::Serialize;
21use serde::Serializer;
22
23use super::ValueWireEncodeError;
24use super::ValueWirePayloadRefV1;
25use super::serialize_wire;
26use crate::MultiValues;
27use crate::Value;
28use crate::ValueContainer;
29
30/// Borrowed standalone V1 envelope for serialization without cloning.
31///
32/// Runtime JSON numbers must round trip to the same `serde_json::Number` under
33/// the strict `qubit-json` number model. A number that would change identity
34/// returns the JSON-gated `JsonNumberNotRoundTrippable` error; the error does
35/// not expose the number text.
36///
37/// # Type Parameters
38///
39/// * `'a` - Lifetime of the runtime payload borrowed for serialization.
40///
41/// # Examples
42///
43/// ```
44/// use qubit_value::{Value, ValueWireRefV1};
45///
46/// let value = Value::from(42_i32);
47/// let wire = ValueWireRefV1::from_value(&value).unwrap();
48/// let encoded = serde_json::to_string(&wire).unwrap();
49/// assert_eq!(encoded, r#"{"version":1,"value":{"scalar":{"int32":42}}}"#);
50/// let owned = qubit_value::ValueWireV1::try_from(Value::from(42_i32)).unwrap();
51/// assert_eq!(encoded, serde_json::to_string(&owned).unwrap());
52/// ```
53#[must_use]
54pub struct ValueWireRefV1<'a> {
55 /// Borrowed V1 payload carried by this versioned envelope.
56 value: ValueWirePayloadRefV1<'a>,
57}
58
59impl<'a> ValueWireRefV1<'a> {
60 /// Borrows a scalar after validating V1's representational constraints.
61 ///
62 /// # Parameters
63 ///
64 /// * `value` - Scalar runtime value to validate and borrow.
65 ///
66 /// # Returns
67 ///
68 /// A standalone borrowed V1 envelope containing the scalar.
69 ///
70 /// # Errors
71 ///
72 /// Returns [`ValueWireEncodeError`] when the scalar violates V1 numeric
73 /// representation constraints, including the supported UTC year range
74 /// for instants.
75 #[inline(always)]
76 pub fn from_value(value: &'a Value) -> Result<Self, ValueWireEncodeError> {
77 ValueWirePayloadRefV1::from_value(value).map(Self::new)
78 }
79 /// Borrows a collection after validating V1's representational constraints.
80 ///
81 /// # Parameters
82 ///
83 /// * `values` - Homogeneous runtime collection to validate and borrow.
84 ///
85 /// # Returns
86 ///
87 /// A standalone borrowed V1 envelope containing the collection.
88 ///
89 /// # Errors
90 ///
91 /// Returns [`ValueWireEncodeError`] when an element violates V1 numeric
92 /// representation constraints, including the supported UTC year range
93 /// for instants.
94 #[inline(always)]
95 pub fn from_values(values: &'a MultiValues) -> Result<Self, ValueWireEncodeError> {
96 ValueWirePayloadRefV1::from_values(values).map(Self::new)
97 }
98 /// Borrows an explicit shape after validating V1's representational
99 /// constraints.
100 ///
101 /// # Parameters
102 ///
103 /// * `value` - Explicit scalar-or-collection value to validate and borrow.
104 ///
105 /// # Returns
106 ///
107 /// A standalone borrowed V1 envelope preserving the original shape.
108 ///
109 /// # Errors
110 ///
111 /// Returns [`ValueWireEncodeError`] when any contained value violates V1
112 /// numeric representation constraints, including the supported UTC year
113 /// range for instants.
114 #[inline(always)]
115 pub fn from_container(value: &'a ValueContainer) -> Result<Self, ValueWireEncodeError> {
116 ValueWirePayloadRefV1::from_container(value).map(Self::new)
117 }
118 /// Wraps an already validated borrowed payload.
119 ///
120 /// # Parameters
121 ///
122 /// * `value` - Validated borrowed payload to place in the V1 envelope.
123 ///
124 /// # Returns
125 ///
126 /// A standalone borrowed V1 envelope.
127 #[inline(always)]
128 pub const fn new(value: ValueWirePayloadRefV1<'a>) -> Self {
129 Self { value }
130 }
131
132 /// Encodes the borrowed V1 envelope into a compact JSON vector.
133 ///
134 /// # Returns
135 ///
136 /// Compact UTF-8 JSON bytes for the complete V1 envelope.
137 ///
138 /// # Errors
139 ///
140 /// Returns [`ValueWireEncodeError`] for resource or serialization failures.
141 #[cfg(feature = "json")]
142 #[inline(always)]
143 #[cfg_attr(docsrs, doc(cfg(feature = "json")))]
144 pub fn to_json_vec(&self) -> Result<Vec<u8>, ValueWireEncodeError> {
145 self.to_json_vec_with_limits(super::default_json_encode_limits())
146 }
147
148 /// Encodes the borrowed V1 envelope with explicit JSON resource limits.
149 ///
150 /// # Parameters
151 ///
152 /// * `limits` - Resource limits enforced during JSON encoding.
153 ///
154 /// # Returns
155 ///
156 /// Compact UTF-8 JSON bytes for the complete V1 envelope.
157 ///
158 /// Runs a conservative payload preflight before encoding, then enforces
159 /// `limits` authoritatively while encoding the full envelope. The preflight
160 /// may report a lower-bound budget error and does not bound every
161 /// preparation allocation.
162 ///
163 /// # Errors
164 ///
165 /// Returns [`ValueWireEncodeError`] when preflight or final encoding
166 /// exceeds `limits`, or Serde rejects the envelope.
167 #[cfg(feature = "json")]
168 #[inline]
169 #[cfg_attr(docsrs, doc(cfg(feature = "json")))]
170 pub fn to_json_vec_with_limits(&self, limits: JsonEncodeLimits) -> Result<Vec<u8>, ValueWireEncodeError> {
171 self.value.check_encode_preflight(limits)?;
172 let session = JsonEncodeSession::from_limits(limits);
173 JsonEncoder::new(session)
174 .to_vec(self)
175 .map_err(ValueWireEncodeError::from)
176 }
177
178 /// Encodes the borrowed V1 envelope to a writer with default limits.
179 ///
180 /// # Type Parameters
181 ///
182 /// * `W` - Destination writer type.
183 ///
184 /// # Parameters
185 ///
186 /// * `writer` - Destination receiving the complete V1 JSON envelope.
187 ///
188 /// # Returns
189 ///
190 /// `Ok(())` after the complete envelope is written.
191 ///
192 /// The complete document is buffered and admitted before this method writes
193 /// its bytes to the destination. Preflight, serialization, or budget
194 /// rejection does not write this document. An I/O error may leave an
195 /// accepted prefix in the writer; do not blindly retry a complete
196 /// document on the same destination.
197 ///
198 /// This method does not explicitly flush the writer. Success means the
199 /// writer accepted all document bytes, not that they were flushed,
200 /// persisted, or received by a remote peer. Pass `&mut writer` to
201 /// retain ownership of a buffered writer, then call `flush()` and
202 /// handle its error separately. Passing an owned writer may invoke that
203 /// writer's drop behavior; errors from an implicit drop-time flush are
204 /// not returned by this method.
205 ///
206 /// # Errors
207 ///
208 /// Returns [`ValueWireEncodeError`] for resource, serialization, or writer
209 /// failures.
210 #[cfg(feature = "json")]
211 #[inline(always)]
212 #[cfg_attr(docsrs, doc(cfg(feature = "json")))]
213 pub fn to_json_writer<W>(&self, writer: W) -> Result<(), ValueWireEncodeError>
214 where
215 W: Write,
216 {
217 self.to_json_writer_with_limits(writer, super::default_json_encode_limits())
218 }
219
220 /// Encodes the borrowed V1 envelope to a writer with explicit limits.
221 ///
222 /// # Type Parameters
223 ///
224 /// * `W` - Destination writer type.
225 ///
226 /// # Parameters
227 ///
228 /// * `writer` - Destination receiving the complete V1 JSON envelope.
229 /// * `limits` - Resource limits enforced during JSON encoding.
230 ///
231 /// # Returns
232 ///
233 /// `Ok(())` after the complete envelope is written.
234 ///
235 /// Runs a conservative payload preflight before encoding, then enforces
236 /// `limits` authoritatively while encoding the full envelope. The preflight
237 /// may report a lower-bound budget error and does not bound every
238 /// preparation allocation.
239 ///
240 /// The complete document is buffered and admitted before this method writes
241 /// its bytes to the destination. Preflight, serialization, or budget
242 /// rejection does not write this document. An I/O error may leave an
243 /// accepted prefix in the writer; do not blindly retry a complete
244 /// document on the same destination.
245 ///
246 /// This method does not explicitly flush the writer. Success means the
247 /// writer accepted all document bytes, not that they were flushed,
248 /// persisted, or received by a remote peer. Pass `&mut writer` to
249 /// retain ownership of a buffered writer, then call `flush()` and
250 /// handle its error separately. Passing an owned writer may invoke that
251 /// writer's drop behavior; errors from an implicit drop-time flush are
252 /// not returned by this method.
253 ///
254 /// # Errors
255 ///
256 /// Returns [`ValueWireEncodeError`] when preflight or final encoding
257 /// exceeds `limits`, Serde rejects the envelope, or `writer` rejects
258 /// output.
259 #[cfg(feature = "json")]
260 #[inline]
261 #[cfg_attr(docsrs, doc(cfg(feature = "json")))]
262 pub fn to_json_writer_with_limits<W>(
263 &self,
264 mut writer: W,
265 limits: JsonEncodeLimits,
266 ) -> Result<(), ValueWireEncodeError>
267 where
268 W: Write,
269 {
270 self.value.check_encode_preflight(limits)?;
271 let session = JsonEncodeSession::from_limits(limits);
272 JsonEncoder::new(session)
273 .write_buffered(&mut writer, self)
274 .map_err(ValueWireEncodeError::from)
275 }
276}
277
278impl<'a> TryFrom<&'a Value> for ValueWireRefV1<'a> {
279 /// Validation failure when the borrowed input cannot be represented in V1.
280 type Error = ValueWireEncodeError;
281
282 /// Validates and borrows the input without cloning its payload.
283 ///
284 /// # Parameters
285 ///
286 /// * `value` - Scalar runtime value to validate and borrow for `'a`.
287 ///
288 /// # Returns
289 ///
290 /// A borrowed V1 envelope preserving the input shape.
291 ///
292 /// # Errors
293 ///
294 /// Returns the same representational validation errors as
295 /// [`Self::from_value`].
296 #[inline]
297 fn try_from(value: &'a Value) -> Result<Self, Self::Error> {
298 Self::from_value(value)
299 }
300}
301
302impl<'a> TryFrom<&'a MultiValues> for ValueWireRefV1<'a> {
303 /// Validation failure when the borrowed input cannot be represented in V1.
304 type Error = ValueWireEncodeError;
305
306 /// Validates and borrows the input without cloning its payload.
307 ///
308 /// # Parameters
309 ///
310 /// * `values` - Homogeneous runtime collection to validate and borrow for
311 /// `'a`.
312 ///
313 /// # Returns
314 ///
315 /// A borrowed V1 envelope preserving the input shape.
316 ///
317 /// # Errors
318 ///
319 /// Returns the same representational validation errors as
320 /// [`Self::from_values`].
321 #[inline]
322 fn try_from(values: &'a MultiValues) -> Result<Self, Self::Error> {
323 Self::from_values(values)
324 }
325}
326
327impl<'a> TryFrom<&'a ValueContainer> for ValueWireRefV1<'a> {
328 /// Validation failure when the borrowed input cannot be represented in V1.
329 type Error = ValueWireEncodeError;
330
331 /// Validates and borrows the input without cloning its payload.
332 ///
333 /// # Parameters
334 ///
335 /// * `value` - Explicit scalar-or-collection value to validate and borrow
336 /// for `'a`.
337 ///
338 /// # Returns
339 ///
340 /// A borrowed V1 envelope preserving the input shape.
341 ///
342 /// # Errors
343 ///
344 /// Returns the same representational validation errors as
345 /// [`Self::from_container`].
346 #[inline]
347 fn try_from(value: &'a ValueContainer) -> Result<Self, Self::Error> {
348 Self::from_container(value)
349 }
350}
351
352impl Serialize for ValueWireRefV1<'_> {
353 /// Serializes the borrowed runtime shape through the V1 envelope.
354 ///
355 /// # Type Parameters
356 ///
357 /// * `S` - Serde serializer defining the output format and error type.
358 ///
359 /// # Parameters
360 ///
361 /// * `serializer` - Consumed serializer receiving the version and payload.
362 ///
363 /// # Returns
364 ///
365 /// The serializer's success value after encoding the complete V1 envelope.
366 ///
367 /// # Errors
368 ///
369 /// Returns the serializer's error if encoding the envelope or payload
370 /// fails.
371 #[inline]
372 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
373 where
374 S: Serializer,
375 {
376 serialize_wire(self.value.shape(), serializer)
377 }
378}