Skip to main content

qubit_codec/value/
value_decoder.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//! Owned-value decoder trait.
9
10/// Decodes a borrowed input value into an owned representation.
11///
12/// This trait is a convenience-layer API. Use [`crate::Codec`] for low-level
13/// single-value buffer decoding and [`crate::Transcoder`] for batch
14/// conversion over caller-provided buffers.
15///
16/// # Type Parameters
17///
18/// - `Input`: Borrowed source type accepted by [`decode`](Self::decode). It may
19///   be unsized, so implementations can accept slices and string types without
20///   an extra reference layer.
21///
22/// # Examples
23///
24/// ```
25/// use core::convert::Infallible;
26///
27/// use qubit_codec::ValueDecoder;
28///
29/// struct Identity;
30/// impl ValueDecoder<str> for Identity {
31///     type Output = String;
32///     type Error = Infallible;
33///
34///     fn decode(&mut self, input: &str) -> Result<Self::Output, Self::Error> {
35///         Ok(input.to_owned())
36///     }
37/// }
38///
39/// let mut decoder = Identity;
40/// assert_eq!(decoder.decode("hello").unwrap(), "hello");
41/// ```
42pub trait ValueDecoder<Input: ?Sized> {
43    /// Owned value produced from one successfully decoded `Input`.
44    ///
45    /// The output is returned by value, so an implementation that borrows from
46    /// `Input` cannot satisfy this associated type and must allocate or copy.
47    type Output;
48
49    /// Error reported when `Input` cannot be decoded.
50    ///
51    /// Implementations report malformed or unsupported input here; callers
52    /// cannot observe partial results because a failed call yields no value.
53    type Error;
54
55    /// Decodes `input`.
56    ///
57    /// # Parameters
58    /// - `input`: Source value to decode.
59    ///
60    /// # Returns
61    /// Returns the owned value decoded from `input`.
62    ///
63    /// # Errors
64    /// Returns an error when the input is malformed or unsupported by the
65    /// codec.
66    fn decode(&mut self, input: &Input) -> Result<Self::Output, Self::Error>;
67}