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