qubit_codec/value/codec_value_encoder.rs
1// =============================================================================
2// Copyright (c) 2026 Haixing Hu.
3//
4// SPDX-License-Identifier: Apache-2.0
5//
6// Licensed under the Apache License, Version 2.0.
7// =============================================================================
8//! Value encoder adapter backed by a low-level codec.
9
10use core::fmt;
11use qubit_utils::try_reserve_vec;
12
13use super::ValueEncoder;
14use crate::{
15 CapacityError,
16 Codec,
17 TranscodeEncodeErrorOf,
18 TranscodeFailure,
19 codec::assert_unit_bounds,
20 value::codec_value_lifecycle::{
21 encode_complete_value_into_reserved,
22 max_complete_encode_units,
23 },
24};
25
26/// Encodes one borrowed value into owned units by using a [`Codec`].
27///
28/// `CodecValueEncoder` is the default bridge from the low-level unchecked
29/// [`Codec`] contract to the convenience-layer [`ValueEncoder`] contract. Each
30/// call emits stream-start output through [`Codec::encode_reset`], encodes one
31/// value through [`Codec::encode`], finishes encode-side state through
32/// [`Codec::encode_finish`], and returns the owned output truncated to the
33/// units actually written.
34///
35/// # Type Parameters
36///
37/// - `C`: Low-level codec used to encode one value.
38pub struct CodecValueEncoder<C> {
39 /// Low-level codec used for one-value encoding.
40 codec: C,
41}
42
43impl<C> CodecValueEncoder<C>
44where
45 C: Codec,
46{
47 /// Creates an encoder backed by `codec`.
48 ///
49 /// # Parameters
50 ///
51 /// - `codec`: Low-level codec used to encode one value.
52 ///
53 /// # Returns
54 ///
55 /// Returns a value encoder adapter for the supplied codec.
56 ///
57 /// # Compile-Time Checks
58 ///
59 /// Fails to compile when the supplied codec declares a zero decode unit
60 /// bound or when [`Codec::MIN_UNITS_PER_VALUE`] exceeds
61 /// [`Codec::MAX_DECODE_UNITS_PER_VALUE`]. The encode bound may be zero for
62 /// a fully buffered codec.
63 #[inline]
64 #[must_use]
65 pub fn new(codec: C) -> Self {
66 assert_unit_bounds::<C>();
67 Self { codec }
68 }
69
70 /// Returns a shared reference to the wrapped codec.
71 #[inline(always)]
72 #[must_use]
73 pub const fn codec(&self) -> &C {
74 &self.codec
75 }
76
77 /// Returns a mutable reference to the wrapped codec.
78 ///
79 /// The next value operation starts a fresh codec lifecycle, so mutations
80 /// are applied to the following operation.
81 #[inline(always)]
82 #[must_use]
83 pub fn codec_mut(&mut self) -> &mut C {
84 &mut self.codec
85 }
86
87 /// Consumes the adapter and returns its wrapped codec.
88 #[inline(always)]
89 #[must_use]
90 pub fn into_codec(self) -> C {
91 self.codec
92 }
93
94 /// Encodes one borrowed value and appends the emitted units to `output`.
95 ///
96 /// This method is the reusable-buffer counterpart of
97 /// [`ValueEncoder::encode`]. It emits stream-start output through
98 /// [`Codec::encode_reset`], encodes `input` through [`Codec::encode`], and
99 /// finishes encode-side state through [`Codec::encode_finish`], appending
100 /// only the units actually written. When encoding fails, the vector length
101 /// is restored to its original value.
102 ///
103 /// # Parameters
104 ///
105 /// - `input`: Value to encode.
106 /// - `output`: Destination vector receiving appended encoded units.
107 ///
108 /// # Returns
109 ///
110 /// Returns the number of units appended to `output`.
111 ///
112 /// # Errors
113 ///
114 /// Returns the wrapped codec's encode error when reset output, `input`, or
115 /// finish output cannot be represented. Returns a framework error when
116 /// output length arithmetic overflows.
117 ///
118 /// # Panics
119 ///
120 /// Panics when the wrapped codec reports more reset or finish output than
121 /// its declared bounds, when [`Codec::encode_len`] exceeds
122 /// [`Codec::MAX_ENCODE_UNITS_PER_VALUE`], or when encoding writes a
123 /// different value width than [`Codec::encode_len`].
124 pub fn encode_into(
125 &mut self,
126 input: &C::Value,
127 output: &mut Vec<C::Unit>,
128 ) -> Result<usize, TranscodeEncodeErrorOf<C>>
129 where
130 C::Unit: Default,
131 {
132 let units = max_complete_encode_units::<C>()?;
133 let original_len = output.len();
134 let target_len = original_len
135 .checked_add(units)
136 .ok_or(CapacityError::OutputLengthOverflow)?;
137 try_reserve_vec(output, units)
138 .map_err(|_| TranscodeFailure::allocation_failed())?;
139 output.resize_with(target_len, C::Unit::default);
140
141 match encode_complete_value_into_reserved(
142 &mut self.codec,
143 input,
144 output,
145 original_len,
146 units,
147 ) {
148 Ok(written) => {
149 output.truncate(original_len + written);
150 Ok(written)
151 }
152 Err(error) => {
153 output.truncate(original_len);
154 Err(error)
155 }
156 }
157 }
158}
159
160impl<C> ValueEncoder<C::Value> for CodecValueEncoder<C>
161where
162 C: Codec,
163 C::Unit: Default,
164{
165 type Output = Vec<C::Unit>;
166 type Error = TranscodeEncodeErrorOf<C>;
167
168 /// Encodes one borrowed value into owned units.
169 ///
170 /// # Parameters
171 ///
172 /// - `input`: Value to encode.
173 ///
174 /// # Returns
175 ///
176 /// Returns stream-start output followed by the units written for `input`
177 /// and any encode-finish output.
178 ///
179 /// # Errors
180 ///
181 /// Returns the wrapped codec's encode error when reset output, `input`, or
182 /// finish output cannot be represented.
183 ///
184 /// # Panics
185 ///
186 /// Panics when the wrapped codec reports more reset or finish output than
187 /// its declared bounds, or a value width different from
188 /// [`Codec::encode_len`].
189 fn encode(
190 &mut self,
191 input: &C::Value,
192 ) -> Result<Self::Output, Self::Error> {
193 let mut output = Vec::new();
194 self.encode_into(input, &mut output)?;
195 Ok(output)
196 }
197}
198
199impl<C> fmt::Debug for CodecValueEncoder<C>
200where
201 C: Codec + fmt::Debug,
202{
203 /// Formats the encoder without requiring finished values to be printable.
204 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
205 formatter
206 .debug_struct("CodecValueEncoder")
207 .field("codec", &self.codec)
208 .finish()
209 }
210}
211
212impl<C> Default for CodecValueEncoder<C>
213where
214 C: Codec + Default,
215{
216 /// Creates an encoder from the default codec.
217 #[inline(always)]
218 fn default() -> Self {
219 Self::new(C::default())
220 }
221}