qubit-codec 0.17.4

Core codec traits and buffer conversion primitives for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
// =============================================================================
//    Copyright (c) 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================

//! Safe type-erased bidirectional string value-codec descriptors.

use core::any::type_name;
use core::fmt::Debug;
use core::fmt::Formatter;
use core::fmt::Result as FmtResult;
use std::any::Any;
use std::any::TypeId;
use std::borrow::Borrow;
use std::error::Error;

use crate::ValueCodecExecutionError;
use crate::ValueDecoder;
use crate::ValueEncoder;

/// Checked type-erased encoding entry point returning an owned string.
type EncodeFn = fn(&dyn Any) -> Result<String, ValueCodecExecutionError>;
/// Type-erased decoding entry point returning a boxed owned value.
type DecodeFn = fn(&str) -> Result<Box<dyn Any>, ValueCodecExecutionError>;

/// An immutable, safely erased bidirectional string codec for one value type.
///
/// Each operation creates a fresh default codec; no codec state is retained
/// between calls. Type identities are process-local and names are diagnostic,
/// not stable IDs.
///
/// # Examples
///
/// ```
/// use core::convert::Infallible;
///
/// use qubit_codec::ValueDecoder;
/// use qubit_codec::ValueEncoder;
/// use qubit_codec::ValueStringCodecDescriptor;
///
/// #[derive(Default)]
/// struct Text;
/// impl ValueEncoder<u32> for Text {
///     type Output = String;
///     type Error = Infallible;
///
///     fn encode(&mut self, input: &u32) -> Result<String, Infallible> {
///         Ok(input.to_string())
///     }
/// }
/// impl ValueDecoder<str> for Text {
///     type Output = u32;
///     type Error = Infallible;
///
///     fn decode(&mut self, input: &str) -> Result<u32, Infallible> {
///         Ok(input.len() as u32)
///     }
/// }
///
/// let descriptor = ValueStringCodecDescriptor::of::<Text, u32>();
///
/// // `encode` takes an erased `&dyn Any`, so the value type must be named.
/// let value: u32 = 7;
/// assert_eq!(descriptor.encode(&value).unwrap(), "7");
///
/// let decoded = descriptor.decode("hello").unwrap();
/// assert_eq!(*decoded.downcast::<u32>().unwrap(), 5);
/// ```
#[derive(Clone, Copy)]
pub struct ValueStringCodecDescriptor {
    /// Returns the process-local identity of the concrete codec.
    codec_type_id: fn() -> TypeId,
    /// Returns the diagnostic name of the concrete codec.
    codec_type_name: fn() -> &'static str,
    /// Returns the process-local identity of the decoded value.
    value_type_id: fn() -> TypeId,
    /// Returns the diagnostic name of the decoded value.
    value_type_name: fn() -> &'static str,
    /// Checks the erased input type and invokes a fresh default encoder.
    encode: EncodeFn,
    /// Invokes a fresh default decoder and boxes its owned output.
    decode: DecodeFn,
}

impl ValueStringCodecDescriptor {
    /// Creates a descriptor for codec `C` and value type `V`.
    ///
    /// The codec error types must implement `Send + Sync` so execution errors
    /// can retain their source across thread boundaries. The codec and value
    /// types themselves need not implement these traits; `V` only needs to be
    /// `'static` because decoded values are returned through `Any`.
    /// Use [`Self::of_borrowed`] when the encoder accepts a borrowed view of
    /// `V` instead of `V` itself.
    ///
    /// # Type Parameters
    ///
    /// - `C`: Default-constructible string encoder/decoder with owned errors.
    /// - `V`: Owned value type accepted and produced by `C`.
    ///
    /// # Returns
    ///
    /// Returns immutable function metadata without constructing a codec.
    #[must_use]
    #[inline]
    pub const fn of<C, V>() -> Self
    where
        C: Default + ValueEncoder<V, Output = String> + ValueDecoder<str, Output = V> + 'static,
        <C as ValueEncoder<V>>::Error: Error + Send + Sync + 'static,
        <C as ValueDecoder<str>>::Error: Error + Send + Sync + 'static,
        V: 'static,
    {
        Self::of_borrowed::<C, V, V>()
    }

    /// Creates a descriptor that encodes an owned value through a borrowed
    /// view.
    ///
    /// The descriptor continues to accept and return the owned type `V`.
    /// During each encode call it checks the erased value is exactly `V`, then
    /// borrows an `I` view with [`Borrow`] for that call only. The view is
    /// never stored. Each operation constructs a fresh `C::default()`
    /// codec. Encoder and decoder errors must implement `Error + Send +
    /// Sync + 'static`; `C` and `V` themselves need not be `Send` or
    /// `Sync`.
    ///
    /// # Type Parameters
    ///
    /// - `C`: Default-constructible codec encoding `I` and decoding into `V`.
    /// - `V`: Owned value type erased by this descriptor and produced by
    ///   decode.
    /// - `I`: Borrowed input view accepted by the encoder; it may be unsized.
    ///
    /// # Returns
    ///
    /// Returns immutable function metadata without constructing a codec.
    ///
    /// # Errors
    ///
    /// Encoding returns a type mismatch if the erased value is not `V`, or
    /// retains the codec's source error. Decoding retains the decoder's source
    /// error.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::io::Error;
    /// use qubit_codec::{ValueDecoder, ValueEncoder, ValueStringCodecDescriptor};
    ///
    /// #[derive(Default)]
    /// struct Utf8;
    /// impl ValueEncoder<[u8]> for Utf8 {
    ///     type Output = String;
    ///     type Error = Error;
    ///     fn encode(&mut self, input: &[u8]) -> Result<String, Error> {
    ///         String::from_utf8(input.to_vec()).map_err(Error::other)
    ///     }
    /// }
    /// impl ValueDecoder<str> for Utf8 {
    ///     type Output = Vec<u8>;
    ///     type Error = Error;
    ///     fn decode(&mut self, input: &str) -> Result<Vec<u8>, Error> {
    ///         Ok(input.as_bytes().to_vec())
    ///     }
    /// }
    ///
    /// let descriptor = ValueStringCodecDescriptor::of_borrowed::<Utf8, Vec<u8>, [u8]>();
    /// let value = b"hello".to_vec();
    /// assert_eq!(descriptor.encode(&value).unwrap(), "hello");
    /// let decoded = descriptor.decode("hello").unwrap().downcast::<Vec<u8>>().unwrap();
    /// assert_eq!(*decoded, value);
    /// ```
    ///
    /// The owned type must implement [`Borrow`] for the selected input view,
    /// and the decoder output must be exactly `V`:
    ///
    /// ```compile_fail
    /// use std::io::Error;
    /// use qubit_codec::{ValueDecoder, ValueEncoder, ValueStringCodecDescriptor};
    ///
    /// #[derive(Default)] struct Codec;
    /// impl ValueEncoder<[u8]> for Codec {
    ///     type Output = String; type Error = Error;
    ///     fn encode(&mut self, input: &[u8]) -> Result<String, Error> {
    ///         String::from_utf8(input.to_vec()).map_err(Error::other)
    ///     }
    /// }
    /// impl ValueDecoder<str> for Codec {
    ///     type Output = String; type Error = Error;
    ///     fn decode(&mut self, input: &str) -> Result<String, Error> { Ok(input.to_owned()) }
    /// }
    /// let _ = ValueStringCodecDescriptor::of_borrowed::<Codec, String, [u8]>();
    /// ```
    ///
    /// ```compile_fail
    /// use std::io::Error;
    /// use qubit_codec::{ValueDecoder, ValueEncoder, ValueStringCodecDescriptor};
    ///
    /// #[derive(Default)] struct Codec;
    /// impl ValueEncoder<[u8]> for Codec {
    ///     type Output = String; type Error = Error;
    ///     fn encode(&mut self, input: &[u8]) -> Result<String, Error> {
    ///         String::from_utf8(input.to_vec()).map_err(Error::other)
    ///     }
    /// }
    /// impl ValueDecoder<str> for Codec {
    ///     type Output = String; type Error = Error;
    ///     fn decode(&mut self, input: &str) -> Result<String, Error> { Ok(input.to_owned()) }
    /// }
    /// let _ = ValueStringCodecDescriptor::of_borrowed::<Codec, Vec<u8>, [u8]>();
    /// ```
    #[must_use]
    #[inline]
    pub const fn of_borrowed<C, V, I>() -> Self
    where
        C: Default + ValueEncoder<I, Output = String> + ValueDecoder<str, Output = V> + 'static,
        <C as ValueEncoder<I>>::Error: Error + Send + Sync + 'static,
        <C as ValueDecoder<str>>::Error: Error + Send + Sync + 'static,
        V: Borrow<I> + 'static,
        I: ?Sized,
    {
        Self {
            codec_type_id: TypeId::of::<C>,
            codec_type_name: type_name::<C>,
            value_type_id: TypeId::of::<V>,
            value_type_name: type_name::<V>,
            encode: encode::<C, V, I>,
            decode: decode::<C, V>,
        }
    }

    /// Returns the process-local identity of the concrete codec.
    ///
    /// # Returns
    ///
    /// Returns the `TypeId` of the codec this descriptor was built for.
    #[must_use]
    #[inline]
    pub fn codec_type_id(&self) -> TypeId {
        (self.codec_type_id)()
    }

    /// Returns the diagnostic name of the concrete codec.
    ///
    /// # Returns
    ///
    /// Returns the `type_name` of the codec, for diagnostics only.
    #[must_use]
    #[inline]
    pub fn codec_type_name(&self) -> &'static str {
        (self.codec_type_name)()
    }

    /// Returns the process-local identity of the decoded value.
    ///
    /// # Returns
    ///
    /// Returns the `TypeId` of the value this descriptor accepts and produces.
    #[must_use]
    #[inline]
    pub fn value_type_id(&self) -> TypeId {
        (self.value_type_id)()
    }

    /// Returns the diagnostic name of the decoded value.
    ///
    /// # Returns
    ///
    /// Returns the `type_name` of the value, for diagnostics only.
    #[must_use]
    #[inline]
    pub fn value_type_name(&self) -> &'static str {
        (self.value_type_name)()
    }

    /// Encodes one erased value after checking its concrete type.
    ///
    /// # Parameters
    ///
    /// - `value`: Borrowed value whose concrete type must match the descriptor.
    ///
    /// # Returns
    ///
    /// Returns an owned string produced by a fresh default codec.
    ///
    /// # Errors
    ///
    /// Returns a type mismatch or the typed encoder source error.
    #[inline]
    pub fn encode(&self, value: &dyn Any) -> Result<String, ValueCodecExecutionError> {
        (self.encode)(value)
    }

    /// Decodes one string into a safely erased value of the declared type.
    ///
    /// # Parameters
    ///
    /// - `input`: String borrowed for one decoding operation.
    ///
    /// # Returns
    ///
    /// Returns a boxed owned value that can be downcast to the declared type.
    ///
    /// # Errors
    ///
    /// Returns the typed decoder source error.
    #[inline]
    pub fn decode(&self, input: &str) -> Result<Box<dyn Any>, ValueCodecExecutionError> {
        (self.decode)(input)
    }
}

impl Debug for ValueStringCodecDescriptor {
    /// Formats descriptor metadata without invoking either codec function.
    ///
    /// # Parameters
    ///
    /// - `formatter`: Destination receiving the diagnostic type names.
    ///
    /// # Returns
    ///
    /// Returns success after both names have been formatted.
    ///
    /// # Errors
    ///
    /// Returns the underlying formatting failure.
    fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
        formatter
            .debug_struct("ValueStringCodecDescriptor")
            .field("codec_type_name", &self.codec_type_name())
            .field("value_type_name", &self.value_type_name())
            .finish_non_exhaustive()
    }
}

/// Downcasts an erased value and encodes it with a fresh default codec.
///
/// # Type Parameters
///
/// - `C`: Default codec encoding the selected borrowed view.
/// - `V`: Concrete owned value type required by the descriptor.
/// - `I`: Borrowed input view accepted by the encoder.
///
/// # Parameters
///
/// - `value`: Erased input borrowed until serialization completes.
///
/// # Returns
///
/// Returns the owned string produced by the codec.
///
/// # Errors
///
/// Returns `TypeMismatch` when the input has a different concrete type, or
/// `EncodeFailed` with the codec source error when encoding fails.
fn encode<C, V, I>(value: &dyn Any) -> Result<String, ValueCodecExecutionError>
where
    C: Default + ValueEncoder<I, Output = String>,
    <C as ValueEncoder<I>>::Error: Error + Send + Sync + 'static,
    V: Borrow<I> + 'static,
    I: ?Sized,
{
    let value = value
        .downcast_ref::<V>()
        .ok_or_else(|| ValueCodecExecutionError::TypeMismatch {
            expected_type: type_name::<V>(),
            actual_type: value.type_id(),
        })?;
    <C as ValueEncoder<I>>::encode(&mut C::default(), <V as Borrow<I>>::borrow(value)).map_err(|source| {
        ValueCodecExecutionError::EncodeFailed {
            codec_type: type_name::<C>(),
            source: Box::new(source),
        }
    })
}

/// Decodes one string with a fresh default codec and erases its typed output.
///
/// # Type Parameters
///
/// - `C`: Default codec with matching string encode/decode contracts.
/// - `V`: Concrete owned value type produced by the descriptor.
///
/// # Parameters
///
/// - `input`: String slice borrowed until decoding completes.
///
/// # Returns
///
/// Returns the decoded value in a box that can be downcast to `V`.
///
/// # Errors
///
/// Returns `DecodeFailed` with the codec source error when decoding fails.
fn decode<C, V>(input: &str) -> Result<Box<dyn Any>, ValueCodecExecutionError>
where
    C: Default + ValueDecoder<str, Output = V>,
    <C as ValueDecoder<str>>::Error: Error + Send + Sync + 'static,
    V: 'static,
{
    C::default()
        .decode(input)
        .map(|value| Box::new(value) as Box<dyn Any>)
        .map_err(|source| ValueCodecExecutionError::DecodeFailed {
            codec_type: type_name::<C>(),
            source: Box::new(source),
        })
}