qubit_codec/value/value_string_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 string 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 an owned string.
24type EncodeFn = fn(&dyn Any) -> Result<String, ValueCodecExecutionError>;
25/// Type-erased decoding entry point returning a boxed owned value.
26type DecodeFn = fn(&str) -> Result<Box<dyn Any>, ValueCodecExecutionError>;
27
28/// An immutable, safely erased bidirectional string codec for one value type.
29///
30/// Each operation creates a fresh default codec; no codec state is retained
31/// between calls. Type identities are process-local and names are diagnostic,
32/// not stable IDs.
33///
34/// # Examples
35///
36/// ```
37/// use core::convert::Infallible;
38///
39/// use qubit_codec::ValueDecoder;
40/// use qubit_codec::ValueEncoder;
41/// use qubit_codec::ValueStringCodecDescriptor;
42///
43/// #[derive(Default)]
44/// struct Text;
45/// impl ValueEncoder<u32> for Text {
46/// type Output = String;
47/// type Error = Infallible;
48///
49/// fn encode(&mut self, input: &u32) -> Result<String, Infallible> {
50/// Ok(input.to_string())
51/// }
52/// }
53/// impl ValueDecoder<str> for Text {
54/// type Output = u32;
55/// type Error = Infallible;
56///
57/// fn decode(&mut self, input: &str) -> Result<u32, Infallible> {
58/// Ok(input.len() as u32)
59/// }
60/// }
61///
62/// let descriptor = ValueStringCodecDescriptor::of::<Text, u32>();
63///
64/// // `encode` takes an erased `&dyn Any`, so the value type must be named.
65/// let value: u32 = 7;
66/// assert_eq!(descriptor.encode(&value).unwrap(), "7");
67///
68/// let decoded = descriptor.decode("hello").unwrap();
69/// assert_eq!(*decoded.downcast::<u32>().unwrap(), 5);
70/// ```
71#[derive(Clone, Copy)]
72pub struct ValueStringCodecDescriptor {
73 /// Returns the process-local identity of the concrete codec.
74 codec_type_id: fn() -> TypeId,
75 /// Returns the diagnostic name of the concrete codec.
76 codec_type_name: fn() -> &'static str,
77 /// Returns the process-local identity of the decoded value.
78 value_type_id: fn() -> TypeId,
79 /// Returns the diagnostic name of the decoded value.
80 value_type_name: fn() -> &'static str,
81 /// Checks the erased input type and invokes a fresh default encoder.
82 encode: EncodeFn,
83 /// Invokes a fresh default decoder and boxes its owned output.
84 decode: DecodeFn,
85}
86
87impl ValueStringCodecDescriptor {
88 /// Creates a descriptor for codec `C` and value type `V`.
89 ///
90 /// # Type Parameters
91 ///
92 /// - `C`: Default-constructible string encoder/decoder with owned errors.
93 /// - `V`: Owned value type accepted and produced by `C`.
94 ///
95 /// # Returns
96 ///
97 /// Returns immutable function metadata without constructing a codec.
98 #[must_use]
99 #[inline]
100 pub const fn of<C, V>() -> Self
101 where
102 C: Default + ValueEncoder<V, Output = String> + ValueDecoder<str, Output = V> + 'static,
103 <C as ValueEncoder<V>>::Error: Error + 'static,
104 <C as ValueDecoder<str>>::Error: Error + 'static,
105 V: 'static,
106 {
107 Self {
108 codec_type_id: TypeId::of::<C>,
109 codec_type_name: type_name::<C>,
110 value_type_id: TypeId::of::<V>,
111 value_type_name: type_name::<V>,
112 encode: encode::<C, V>,
113 decode: decode::<C, V>,
114 }
115 }
116
117 /// Returns the process-local identity of the concrete codec.
118 ///
119 /// # Returns
120 ///
121 /// Returns the `TypeId` of the codec this descriptor was built for.
122 #[must_use]
123 #[inline]
124 pub fn codec_type_id(&self) -> TypeId {
125 (self.codec_type_id)()
126 }
127
128 /// Returns the diagnostic name of the concrete codec.
129 ///
130 /// # Returns
131 ///
132 /// Returns the `type_name` of the codec, for diagnostics only.
133 #[must_use]
134 #[inline]
135 pub fn codec_type_name(&self) -> &'static str {
136 (self.codec_type_name)()
137 }
138
139 /// Returns the process-local identity of the decoded value.
140 ///
141 /// # Returns
142 ///
143 /// Returns the `TypeId` of the value this descriptor accepts and produces.
144 #[must_use]
145 #[inline]
146 pub fn value_type_id(&self) -> TypeId {
147 (self.value_type_id)()
148 }
149
150 /// Returns the diagnostic name of the decoded value.
151 ///
152 /// # Returns
153 ///
154 /// Returns the `type_name` of the value, for diagnostics only.
155 #[must_use]
156 #[inline]
157 pub fn value_type_name(&self) -> &'static str {
158 (self.value_type_name)()
159 }
160
161 /// Encodes one erased value after checking its concrete type.
162 ///
163 /// # Parameters
164 ///
165 /// - `value`: Borrowed value whose concrete type must match the descriptor.
166 ///
167 /// # Returns
168 ///
169 /// Returns an owned string produced by a fresh default codec.
170 ///
171 /// # Errors
172 ///
173 /// Returns a type mismatch or the typed encoder source error.
174 pub fn encode(&self, value: &dyn Any) -> Result<String, ValueCodecExecutionError> {
175 (self.encode)(value)
176 }
177
178 /// Decodes one string into a safely erased value of the declared type.
179 ///
180 /// # Parameters
181 ///
182 /// - `input`: String borrowed for one decoding operation.
183 ///
184 /// # Returns
185 ///
186 /// Returns a boxed owned value that can be downcast to the declared type.
187 ///
188 /// # Errors
189 ///
190 /// Returns the typed decoder source error.
191 pub fn decode(&self, input: &str) -> Result<Box<dyn Any>, ValueCodecExecutionError> {
192 (self.decode)(input)
193 }
194}
195
196impl Debug for ValueStringCodecDescriptor {
197 /// Formats descriptor metadata without invoking either codec function.
198 ///
199 /// # Parameters
200 ///
201 /// - `formatter`: Destination receiving the diagnostic type names.
202 ///
203 /// # Returns
204 ///
205 /// Returns success after both names have been formatted.
206 ///
207 /// # Errors
208 ///
209 /// Returns the underlying formatting failure.
210 fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
211 formatter
212 .debug_struct("ValueStringCodecDescriptor")
213 .field("codec_type_name", &self.codec_type_name())
214 .field("value_type_name", &self.value_type_name())
215 .finish_non_exhaustive()
216 }
217}
218
219/// Downcasts and encodes one typed value.
220fn encode<C, V>(value: &dyn Any) -> Result<String, ValueCodecExecutionError>
221where
222 C: Default + ValueEncoder<V, Output = String> + ValueDecoder<str, Output = V> + 'static,
223 <C as ValueEncoder<V>>::Error: Error + 'static,
224 <C as ValueDecoder<str>>::Error: Error + 'static,
225 V: 'static,
226{
227 let value = value
228 .downcast_ref::<V>()
229 .ok_or_else(|| ValueCodecExecutionError::TypeMismatch {
230 expected_type: type_name::<V>(),
231 actual_type: value.type_id(),
232 })?;
233 C::default()
234 .encode(value)
235 .map_err(|source| ValueCodecExecutionError::EncodeFailed {
236 codec_type: type_name::<C>(),
237 source: Box::new(source),
238 })
239}
240
241/// Decodes one string and erases the typed output safely.
242fn decode<C, V>(input: &str) -> Result<Box<dyn Any>, ValueCodecExecutionError>
243where
244 C: Default + ValueEncoder<V, Output = String> + ValueDecoder<str, Output = V> + 'static,
245 <C as ValueEncoder<V>>::Error: Error + 'static,
246 <C as ValueDecoder<str>>::Error: Error + 'static,
247 V: 'static,
248{
249 C::default()
250 .decode(input)
251 .map(|value| Box::new(value) as Box<dyn Any>)
252 .map_err(|source| ValueCodecExecutionError::DecodeFailed {
253 codec_type: type_name::<C>(),
254 source: Box::new(source),
255 })
256}