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///
20/// # Type Parameters
21///
22/// - `T`: Source value type serialized through Serde.
23///
24/// # Examples
25///
26/// ```rust
27/// use qubit_codec::JsonBytesValueEncoder;
28/// use qubit_codec::ValueEncoder;
29/// use serde::Serialize;
30///
31/// #[derive(Serialize)]
32/// struct Point {
33///     x: i32,
34///     y: i32,
35/// }
36///
37/// let mut encoder = JsonBytesValueEncoder::<Point>::new();
38/// let json = encoder.encode(&Point { x: 1, y: 2 }).unwrap();
39/// assert_eq!(json, br#"{"x":1,"y":2}"#);
40/// ```
41#[must_use]
42#[derive(Debug, Clone, Copy, Default)]
43pub struct JsonBytesValueEncoder<T> {
44    /// Associates the encoder with `T` without retaining a source value.
45    _marker: PhantomData<T>,
46}
47
48impl<T> JsonBytesValueEncoder<T> {
49    /// Creates a JSON bytes encoder for values of type `T`.
50    ///
51    /// # Returns
52    ///
53    /// Returns a stateless encoder without allocating an output buffer.
54    #[inline]
55    pub const fn new() -> Self {
56        Self { _marker: PhantomData }
57    }
58}
59
60impl<T> ValueEncoder<T> for JsonBytesValueEncoder<T>
61where
62    T: Serialize,
63{
64    /// Serialization failure reported by Serde JSON.
65    type Error = JsonError;
66    /// Newly allocated UTF-8 JSON bytes owned by the caller.
67    type Output = Vec<u8>;
68
69    /// Serializes `input` into UTF-8 JSON bytes.
70    ///
71    /// # Parameters
72    ///
73    /// - `input`: Value borrowed for the duration of serialization.
74    ///
75    /// # Returns
76    ///
77    /// Returns a newly allocated vector containing the serialized JSON.
78    ///
79    /// # Errors
80    ///
81    /// Returns a JSON error if `T` rejects serialization or contains a map key
82    /// that cannot be represented as a JSON object key.
83    #[inline]
84    fn encode(&mut self, input: &T) -> Result<Self::Output, Self::Error> {
85        to_vec(input)
86    }
87}