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 type is not tied to the temporary borrow of `input` passed to
46 /// [`decode`](Self::decode). It may still borrow data carried by `Input`,
47 /// such as an `&'a str` input whose output also has lifetime `'a`.
48 type Output;
49
50 /// Error reported when `Input` cannot be decoded.
51 ///
52 /// Implementations report malformed or unsupported input here; callers
53 /// cannot observe partial results because a failed call yields no value.
54 type Error;
55
56 /// Decodes `input`.
57 ///
58 /// # Parameters
59 /// - `input`: Source value to decode.
60 ///
61 /// # Returns
62 /// Returns the owned value decoded from `input`.
63 ///
64 /// # Errors
65 /// Returns an error when the input is malformed or unsupported by the
66 /// codec.
67 fn decode(&mut self, input: &Input) -> Result<Self::Output, Self::Error>;
68}