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    /// Encoded output type.
36    type Output;
37    /// Encoding error type.
38    type Error;
39
40    /// Encodes `input`.
41    ///
42    /// # Parameters
43    /// - `input`: Source value to encode.
44    ///
45    /// # Returns
46    /// Encoded output.
47    ///
48    /// # Errors
49    /// Returns an error when the codec cannot represent the supplied input.
50    fn encode(&mut self, input: &Input) -> Result<Self::Output, Self::Error>;
51}