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 #[inline]
51 fn clone(&self) -> Self {
52 *self
53 }
54}
55
56impl<T> Default for JsonStringValueEncoder<T> {
57 #[inline]
58 fn default() -> Self {
59 Self::new()
60 }
61}
62
63impl<T> JsonStringValueEncoder<T> {
64 /// Creates a JSON string encoder for values of type `T`.
65 #[inline]
66 pub const fn new() -> Self {
67 Self { _marker: PhantomData }
68 }
69}
70
71impl<T> ValueEncoder<T> for JsonStringValueEncoder<T>
72where
73 T: Serialize,
74{
75 type Error = serde_json::Error;
76 type Output = String;
77
78 /// Serializes `input` into a compact JSON string.
79 ///
80 /// # Parameters
81 /// - `input`: Value to serialize.
82 ///
83 /// # Returns
84 /// The serialized JSON text as an owned UTF-8 string.
85 ///
86 /// # Errors
87 /// Returns the `serde_json` error if serialization fails, such as when a
88 /// custom serializer reports an error or the value contains unsupported
89 /// data.
90 #[inline]
91 fn encode(&mut self, input: &T) -> Result<Self::Output, Self::Error> {
92 serde_json::to_string(input)
93 }
94}