Skip to main content

qubit_codec/value/
json_string_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 string encoder for one owned value.
9
10use core::marker::PhantomData;
11
12use serde::Serialize;
13
14use super::ValueEncoder;
15
16/// Encodes one serializable value into a UTF-8 JSON string via `serde_json`.
17/// Its stateless marker implements `Clone`, `Copy`, and `Default` without
18/// requiring those traits on `T`.
19///
20/// # Type Parameters
21///
22/// - `T`: Source value type serialized through Serde.
23///
24/// # Examples
25///
26/// ```rust
27/// use qubit_codec::{JsonStringValueEncoder, ValueEncoder};
28/// use serde::Serialize;
29///
30/// #[derive(Serialize)]
31/// struct Point {
32///     x: i32,
33///     y: i32,
34/// }
35///
36/// let mut encoder = JsonStringValueEncoder::<Point>::new();
37/// let json = encoder.encode(&Point { x: 1, y: 2 }).unwrap();
38/// assert_eq!(json, r#"{"x":1,"y":2}"#);
39/// ```
40#[must_use]
41#[derive(Debug)]
42pub struct JsonStringValueEncoder<T> {
43    /// Associates the encoder with `T` without retaining a source value.
44    _marker: PhantomData<T>,
45}
46
47impl<T> Copy for JsonStringValueEncoder<T> {}
48
49impl<T> Clone for JsonStringValueEncoder<T> {
50    /// Copies the stateless encoder marker without requiring `T: Clone`.
51    #[inline]
52    fn clone(&self) -> Self {
53        *self
54    }
55}
56
57impl<T> Default for JsonStringValueEncoder<T> {
58    /// Creates the stateless encoder through its const constructor.
59    #[inline]
60    fn default() -> Self {
61        Self::new()
62    }
63}
64
65impl<T> JsonStringValueEncoder<T> {
66    /// Creates a JSON string encoder for values of type `T`.
67    ///
68    /// # Returns
69    ///
70    /// Returns a stateless encoder without allocating an output string.
71    #[inline]
72    pub const fn new() -> Self {
73        Self { _marker: PhantomData }
74    }
75}
76
77impl<T> ValueEncoder<T> for JsonStringValueEncoder<T>
78where
79    T: Serialize,
80{
81    type Error = serde_json::Error;
82    type Output = String;
83
84    /// Serializes `input` into a compact JSON string.
85    ///
86    /// # Parameters
87    /// - `input`: Value to serialize.
88    ///
89    /// # Returns
90    /// The serialized JSON text as an owned UTF-8 string.
91    ///
92    /// # Errors
93    /// Returns the `serde_json` error if serialization fails, such as when a
94    /// custom serializer reports an error or the value contains unsupported
95    /// data.
96    #[inline]
97    fn encode(&mut self, input: &T) -> Result<Self::Output, Self::Error> {
98        serde_json::to_string(input)
99    }
100}