Skip to main content

qubit_codec/value/
value_bytes_codec_descriptor.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
9//! Safe type-erased bidirectional bytes value-codec descriptors.
10
11use core::any::type_name;
12use core::fmt::Debug;
13use core::fmt::Formatter;
14use core::fmt::Result as FmtResult;
15use std::any::Any;
16use std::any::TypeId;
17use std::error::Error;
18
19use crate::ValueCodecExecutionError;
20use crate::ValueDecoder;
21use crate::ValueEncoder;
22
23/// Checked type-erased encoding entry point returning caller-owned bytes.
24type EncodeFn = fn(&dyn Any) -> Result<Vec<u8>, ValueCodecExecutionError>;
25/// Type-erased decoding entry point returning a boxed owned value.
26type DecodeFn = fn(&[u8]) -> Result<Box<dyn Any>, ValueCodecExecutionError>;
27
28/// An immutable, safely erased bidirectional bytes codec for one value type.
29///
30/// Each operation creates a fresh default codec; no codec state is retained.
31/// Type identities are process-local and names are diagnostic, not stable IDs.
32///
33/// # Examples
34///
35/// ```
36/// use core::convert::Infallible;
37///
38/// use qubit_codec::ValueBytesCodecDescriptor;
39/// use qubit_codec::ValueDecoder;
40/// use qubit_codec::ValueEncoder;
41///
42/// #[derive(Default)]
43/// struct Bytes;
44/// impl ValueEncoder<Vec<u8>> for Bytes {
45///     type Error = Infallible;
46///     type Output = Vec<u8>;
47///     fn encode(&mut self, value: &Vec<u8>) -> Result<Vec<u8>, Infallible> {
48///         Ok(value.clone())
49///     }
50/// }
51/// impl ValueDecoder<[u8]> for Bytes {
52///     type Error = Infallible;
53///     type Output = Vec<u8>;
54///     fn decode(&mut self, input: &[u8]) -> Result<Vec<u8>, Infallible> {
55///         Ok(input.to_vec())
56///     }
57/// }
58/// let descriptor = ValueBytesCodecDescriptor::of::<Bytes, Vec<u8>>();
59/// let bytes = descriptor.encode(&vec![1_u8, 2]).unwrap();
60/// let decoded = descriptor.decode(&bytes).unwrap();
61/// assert_eq!(*decoded.downcast::<Vec<u8>>().unwrap(), vec![1, 2]);
62/// ```
63#[derive(Clone, Copy)]
64pub struct ValueBytesCodecDescriptor {
65    /// Returns the process-local identity of the concrete codec.
66    codec_type_id: fn() -> TypeId,
67    /// Returns the diagnostic name of the concrete codec.
68    codec_type_name: fn() -> &'static str,
69    /// Returns the process-local identity of the decoded value.
70    value_type_id: fn() -> TypeId,
71    /// Returns the diagnostic name of the decoded value.
72    value_type_name: fn() -> &'static str,
73    /// Checks the erased input type and invokes a fresh default encoder.
74    encode: EncodeFn,
75    /// Invokes a fresh default decoder and boxes its owned output.
76    decode: DecodeFn,
77}
78
79impl ValueBytesCodecDescriptor {
80    /// Creates a descriptor for codec `C` and value type `V`.
81    ///
82    /// # Type Parameters
83    ///
84    /// - `C`: Default-constructible bytes encoder/decoder with owned errors.
85    /// - `V`: Owned value type accepted and produced by `C`.
86    ///
87    /// # Returns
88    ///
89    /// Returns immutable function metadata without constructing a codec.
90    #[must_use]
91    #[inline]
92    pub const fn of<C, V>() -> Self
93    where
94        C: Default + ValueEncoder<V, Output = Vec<u8>> + ValueDecoder<[u8], Output = V> + 'static,
95        <C as ValueEncoder<V>>::Error: Error + 'static,
96        <C as ValueDecoder<[u8]>>::Error: Error + 'static,
97        V: 'static,
98    {
99        Self {
100            codec_type_id: TypeId::of::<C>,
101            codec_type_name: type_name::<C>,
102            value_type_id: TypeId::of::<V>,
103            value_type_name: type_name::<V>,
104            encode: encode::<C, V>,
105            decode: decode::<C, V>,
106        }
107    }
108
109    /// Returns the process-local codec type identity.
110    ///
111    /// # Returns
112    ///
113    /// Returns metadata for the type selected by [`Self::of`], without
114    /// allocation.
115    #[must_use]
116    #[inline]
117    pub fn codec_type_id(&self) -> TypeId {
118        (self.codec_type_id)()
119    }
120
121    /// Returns the diagnostic codec type name.
122    ///
123    /// # Returns
124    ///
125    /// Returns metadata for the type selected by [`Self::of`], without
126    /// allocation.
127    #[must_use]
128    #[inline]
129    pub fn codec_type_name(&self) -> &'static str {
130        (self.codec_type_name)()
131    }
132
133    /// Returns the process-local value type identity.
134    ///
135    /// # Returns
136    ///
137    /// Returns metadata for the type selected by [`Self::of`], without
138    /// allocation.
139    #[must_use]
140    #[inline]
141    pub fn value_type_id(&self) -> TypeId {
142        (self.value_type_id)()
143    }
144
145    /// Returns the diagnostic value type name.
146    ///
147    /// # Returns
148    ///
149    /// Returns metadata for the type selected by [`Self::of`], without
150    /// allocation.
151    #[must_use]
152    #[inline]
153    pub fn value_type_name(&self) -> &'static str {
154        (self.value_type_name)()
155    }
156
157    /// Encodes one erased value after checking its concrete type.
158    ///
159    /// # Parameters
160    ///
161    /// - `value`: Borrowed value whose concrete type must match the descriptor.
162    ///
163    /// # Returns
164    ///
165    /// Returns owned bytes produced by a fresh default codec.
166    ///
167    /// # Errors
168    ///
169    /// Returns a type mismatch or the typed encoder source error.
170    pub fn encode(&self, value: &dyn Any) -> Result<Vec<u8>, ValueCodecExecutionError> {
171        (self.encode)(value)
172    }
173
174    /// Decodes one byte slice into a safely erased value of the declared type.
175    ///
176    /// # Parameters
177    ///
178    /// - `input`: Bytes borrowed for one decoding operation.
179    ///
180    /// # Returns
181    ///
182    /// Returns a boxed owned value that can be downcast to the declared type.
183    ///
184    /// # Errors
185    ///
186    /// Returns the typed decoder source error.
187    pub fn decode(&self, input: &[u8]) -> Result<Box<dyn Any>, ValueCodecExecutionError> {
188        (self.decode)(input)
189    }
190}
191
192impl Debug for ValueBytesCodecDescriptor {
193    /// Formats descriptor metadata without invoking either codec function.
194    ///
195    /// # Parameters
196    ///
197    /// - `formatter`: Destination receiving the diagnostic type names.
198    ///
199    /// # Returns
200    ///
201    /// Returns success after both names have been formatted.
202    ///
203    /// # Errors
204    ///
205    /// Returns the formatting error if the destination rejects output.
206    fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
207        formatter
208            .debug_struct("ValueBytesCodecDescriptor")
209            .field("codec_type_name", &self.codec_type_name())
210            .field("value_type_name", &self.value_type_name())
211            .finish_non_exhaustive()
212    }
213}
214
215/// Downcasts and encodes one typed value using a fresh default codec.
216///
217/// # Type Parameters
218///
219/// - `C`: Default codec with matching bytes encode/decode contracts.
220/// - `V`: Concrete owned value type required by the descriptor.
221///
222/// # Parameters
223///
224/// - `value`: Erased input borrowed until serialization completes.
225///
226/// # Returns
227///
228/// Returns caller-owned encoded bytes.
229///
230/// # Errors
231///
232/// Returns `TypeMismatch` for a different concrete type, or `EncodeFailed`
233/// retaining the codec source error if encoding fails.
234fn encode<C, V>(value: &dyn Any) -> Result<Vec<u8>, ValueCodecExecutionError>
235where
236    C: Default + ValueEncoder<V, Output = Vec<u8>> + ValueDecoder<[u8], Output = V> + 'static,
237    <C as ValueEncoder<V>>::Error: Error + 'static,
238    <C as ValueDecoder<[u8]>>::Error: Error + 'static,
239    V: 'static,
240{
241    let value = value
242        .downcast_ref::<V>()
243        .ok_or_else(|| ValueCodecExecutionError::TypeMismatch {
244            expected_type: type_name::<V>(),
245            actual_type: value.type_id(),
246        })?;
247    C::default()
248        .encode(value)
249        .map_err(|source| ValueCodecExecutionError::EncodeFailed {
250            codec_type: type_name::<C>(),
251            source: Box::new(source),
252        })
253}
254
255/// Decodes one byte slice and erases the typed output safely.
256///
257/// # Type Parameters
258///
259/// - `C`: Default codec with matching bytes encode/decode contracts.
260/// - `V`: Concrete owned output type placed in the returned box.
261///
262/// # Parameters
263///
264/// - `input`: Borrowed bytes passed to a fresh default decoder.
265///
266/// # Returns
267///
268/// Returns a newly boxed decoded value with no borrow of the input.
269///
270/// # Errors
271///
272/// Returns `DecodeFailed` retaining the codec source error on decode failure.
273fn decode<C, V>(input: &[u8]) -> Result<Box<dyn Any>, ValueCodecExecutionError>
274where
275    C: Default + ValueEncoder<V, Output = Vec<u8>> + ValueDecoder<[u8], Output = V> + 'static,
276    <C as ValueEncoder<V>>::Error: Error + 'static,
277    <C as ValueDecoder<[u8]>>::Error: Error + 'static,
278    V: 'static,
279{
280    C::default()
281        .decode(input)
282        .map(|value| Box::new(value) as Box<dyn Any>)
283        .map_err(|source| ValueCodecExecutionError::DecodeFailed {
284            codec_type: type_name::<C>(),
285            source: Box::new(source),
286        })
287}