Skip to main content

qubit_codec/value/
json_bytes_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//! Serde JSON bytes encoder for one owned value.
9
10use core::marker::PhantomData;
11
12use serde::Serialize;
13use serde_json::Error as JsonError;
14use serde_json::to_vec;
15
16use super::ValueEncoder;
17
18/// Encodes one serializable value into UTF-8 JSON bytes via `serde_json`.
19/// Its stateless marker implements `Clone`, `Copy`, and `Default` without
20/// requiring those traits on `T`.
21///
22/// # Type Parameters
23///
24/// - `T`: Source value type serialized through Serde.
25///
26/// # Examples
27///
28/// ```rust
29/// use qubit_codec::JsonBytesValueEncoder;
30/// use qubit_codec::ValueEncoder;
31/// use serde::Serialize;
32///
33/// #[derive(Serialize)]
34/// struct Point {
35///     x: i32,
36///     y: i32,
37/// }
38///
39/// let mut encoder = JsonBytesValueEncoder::<Point>::new();
40/// let json = encoder.encode(&Point { x: 1, y: 2 }).unwrap();
41/// assert_eq!(json, br#"{"x":1,"y":2}"#);
42/// ```
43#[must_use]
44#[derive(Debug)]
45pub struct JsonBytesValueEncoder<T> {
46    /// Associates the encoder with `T` without retaining a source value.
47    _marker: PhantomData<T>,
48}
49
50impl<T> Copy for JsonBytesValueEncoder<T> {}
51
52impl<T> Clone for JsonBytesValueEncoder<T> {
53    /// Returns the same stateless encoder marker without constructing or
54    /// cloning a value of type `T`.
55    ///
56    /// This implementation does not require `T: Clone`.
57    ///
58    /// # Returns
59    ///
60    /// Returns a copy of this encoder.
61    #[inline]
62    fn clone(&self) -> Self {
63        *self
64    }
65}
66
67impl<T> Default for JsonBytesValueEncoder<T> {
68    /// Creates the default encoder by calling [`Self::new`].
69    ///
70    /// This implementation does not require `T: Default` and performs no
71    /// allocation.
72    ///
73    /// # Returns
74    ///
75    /// Returns a stateless encoder for values of type `T`.
76    #[inline]
77    fn default() -> Self {
78        Self::new()
79    }
80}
81
82impl<T> JsonBytesValueEncoder<T> {
83    /// Creates a JSON bytes encoder for values of type `T`.
84    ///
85    /// # Returns
86    ///
87    /// Returns a stateless encoder without allocating an output buffer.
88    #[inline]
89    pub const fn new() -> Self {
90        Self { _marker: PhantomData }
91    }
92}
93
94impl<T> ValueEncoder<T> for JsonBytesValueEncoder<T>
95where
96    T: Serialize,
97{
98    /// Serialization failure reported by Serde JSON.
99    type Error = JsonError;
100    /// Newly allocated UTF-8 JSON bytes owned by the caller.
101    type Output = Vec<u8>;
102
103    /// Serializes `input` into UTF-8 JSON bytes.
104    ///
105    /// # Parameters
106    ///
107    /// - `input`: Value borrowed for the duration of serialization.
108    ///
109    /// # Returns
110    ///
111    /// Returns a newly allocated vector containing the serialized JSON.
112    ///
113    /// # Errors
114    ///
115    /// Returns a JSON error if `T` rejects serialization or contains a map key
116    /// that cannot be represented as a JSON object key.
117    #[inline]
118    fn encode(&mut self, input: &T) -> Result<Self::Output, Self::Error> {
119        to_vec(input)
120    }
121}