Skip to main content

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
11use serde::{
12    Serialize,
13    Serializer,
14};
15
16use crate::{
17    MultiValues,
18    Value,
19    ValueContainer,
20};
21
22use super::{
23    ValueWireEncodeError,
24    ValueWirePayloadRefV1,
25    serialize_wire,
26};
27
28/// Borrowed standalone V1 envelope for serialization without cloning.
29#[must_use]
30pub struct ValueWireRefV1<'a> {
31    value: ValueWirePayloadRefV1<'a>,
32}
33
34impl<'a> ValueWireRefV1<'a> {
35    /// Borrows a scalar after validating V1's finite-float invariant.
36    pub fn from_value(value: &'a Value) -> Result<Self, ValueWireEncodeError> {
37        ValueWirePayloadRefV1::from_value(value).map(Self::new)
38    }
39    /// Borrows a collection after validating V1's finite-float invariant.
40    pub fn from_values(
41        values: &'a MultiValues,
42    ) -> Result<Self, ValueWireEncodeError> {
43        ValueWirePayloadRefV1::from_values(values).map(Self::new)
44    }
45    /// Borrows an explicit shape after validating V1's finite-float invariant.
46    pub fn from_container(
47        value: &'a ValueContainer,
48    ) -> Result<Self, ValueWireEncodeError> {
49        ValueWirePayloadRefV1::from_container(value).map(Self::new)
50    }
51    /// Wraps an already validated borrowed payload.
52    pub const fn new(value: ValueWirePayloadRefV1<'a>) -> Self {
53        Self { value }
54    }
55}
56
57impl<'a> TryFrom<&'a Value> for ValueWireRefV1<'a> {
58    type Error = ValueWireEncodeError;
59    /// Borrows and validates a scalar.
60    fn try_from(value: &'a Value) -> Result<Self, Self::Error> {
61        Self::from_value(value)
62    }
63}
64
65impl<'a> TryFrom<&'a MultiValues> for ValueWireRefV1<'a> {
66    type Error = ValueWireEncodeError;
67    /// Borrows and validates a collection.
68    fn try_from(values: &'a MultiValues) -> Result<Self, Self::Error> {
69        Self::from_values(values)
70    }
71}
72
73impl<'a> TryFrom<&'a ValueContainer> for ValueWireRefV1<'a> {
74    type Error = ValueWireEncodeError;
75    /// Borrows and validates an explicit shape.
76    fn try_from(value: &'a ValueContainer) -> Result<Self, Self::Error> {
77        Self::from_container(value)
78    }
79}
80
81impl Serialize for ValueWireRefV1<'_> {
82    /// Serializes the borrowed runtime shape through the V1 envelope.
83    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
84    where
85        S: Serializer,
86    {
87        serialize_wire(self.value.shape(), serializer)
88    }
89}