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/// # Type Parameters
17///
18/// - `Input`: Borrowed source type accepted by [`encode`](Self::encode). 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 qubit_codec::ValueEncoder;
26///
27/// struct TextEncoder;
28/// impl ValueEncoder<str> for TextEncoder {
29/// type Output = Vec<u8>;
30/// type Error = core::convert::Infallible;
31///
32/// fn encode(&mut self, input: &str) -> Result<Self::Output, Self::Error> {
33/// Ok(input.as_bytes().to_vec())
34/// }
35/// }
36///
37/// let mut encoder = TextEncoder;
38/// assert_eq!(encoder.encode("hello").unwrap(), b"hello");
39/// ```
40pub trait ValueEncoder<Input: ?Sized> {
41 /// Owned representation produced from one input value.
42 ///
43 /// Implementations must return a value that owns its data: `Output` may not
44 /// borrow from `Input` or from `self`, so the result outlives the borrow
45 /// passed to [`Self::encode`]. The representation is free — for example
46 /// `String` or `Vec<u8>` — and its size is the encoding's cost.
47 type Output;
48 /// Failure reported when one input value cannot be represented.
49 ///
50 /// Implementations choose the error type and determine which encoding
51 /// failures it represents. Callers observe it as the `Err` of
52 /// [`Self::encode`].
53 type Error;
54
55 /// Encodes `input`.
56 ///
57 /// # Parameters
58 /// - `input`: Source value to encode.
59 ///
60 /// # Returns
61 /// Encoded output.
62 ///
63 /// # Errors
64 /// Returns an error when the codec cannot represent the supplied input.
65 fn encode(&mut self, input: &Input) -> Result<Self::Output, Self::Error>;
66}