Skip to main content

qubit_codec/value/
value_encoder.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 encoder trait.
9
10/// Encodes 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 encoding and [`crate::Transcoder`] for batch
14/// conversion over caller-provided buffers.
15///
16/// # Examples
17///
18/// ```
19/// use qubit_codec::ValueEncoder;
20///
21/// struct TextEncoder;
22/// impl ValueEncoder<str> for TextEncoder {
23///     type Output = Vec<u8>;
24///     type Error = core::convert::Infallible;
25///
26///     fn encode(&mut self, input: &str) -> Result<Self::Output, Self::Error> {
27///         Ok(input.as_bytes().to_vec())
28///     }
29/// }
30///
31/// let mut encoder = TextEncoder;
32/// assert_eq!(encoder.encode("hello").unwrap(), b"hello");
33/// ```
34pub trait ValueEncoder<Input: ?Sized> {
35    /// Owned representation produced from one input value.
36    ///
37    /// Implementations must return a value that owns its data: `Output` may not
38    /// borrow from `Input` or from `self`, so the result outlives the borrow
39    /// passed to [`Self::encode`]. The representation is free — for example
40    /// `String` or `Vec<u8>` — and its size is the encoding's cost.
41    type Output;
42    /// Failure reported when one input value cannot be represented.
43    ///
44    /// Implementations choose the error type; anything convertible into it from
45    /// a codec or allocation failure is accepted. Callers observe it only as
46    /// the `Err` of [`Self::encode`].
47    type Error;
48
49    /// Encodes `input`.
50    ///
51    /// # Parameters
52    /// - `input`: Source value to encode.
53    ///
54    /// # Returns
55    /// Encoded output.
56    ///
57    /// # Errors
58    /// Returns an error when the codec cannot represent the supplied input.
59    fn encode(&mut self, input: &Input) -> Result<Self::Output, Self::Error>;
60}