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///
18/// # Type Parameters
19///
20/// - `T`: Source value type serialized through Serde.
21///
22/// # Examples
23///
24/// ```rust
25/// use qubit_codec::{JsonStringValueEncoder, ValueEncoder};
26/// use serde::Serialize;
27///
28/// #[derive(Serialize)]
29/// struct Point {
30/// x: i32,
31/// y: i32,
32/// }
33///
34/// let mut encoder = JsonStringValueEncoder::<Point>::new();
35/// let json = encoder.encode(&Point { x: 1, y: 2 }).unwrap();
36/// assert_eq!(json, r#"{"x":1,"y":2}"#);
37/// ```
38#[must_use]
39#[derive(Debug, Clone, Copy, Default)]
40pub struct JsonStringValueEncoder<T> {
41 /// Associates the encoder with `T` without retaining a source value.
42 _marker: PhantomData<T>,
43}
44
45impl<T> JsonStringValueEncoder<T> {
46 /// Creates a JSON string encoder for values of type `T`.
47 #[inline]
48 pub const fn new() -> Self {
49 Self { _marker: PhantomData }
50 }
51}
52
53impl<T> ValueEncoder<T> for JsonStringValueEncoder<T>
54where
55 T: Serialize,
56{
57 type Error = serde_json::Error;
58 type Output = String;
59
60 /// Serializes `input` into a compact JSON string.
61 ///
62 /// # Parameters
63 /// - `input`: Value to serialize.
64 ///
65 /// # Returns
66 /// The serialized JSON text as an owned UTF-8 string.
67 ///
68 /// # Errors
69 /// Returns the `serde_json` error if serialization fails, such as when a
70 /// custom serializer reports an error or the value contains unsupported
71 /// data.
72 #[inline]
73 fn encode(&mut self, input: &T) -> Result<Self::Output, Self::Error> {
74 serde_json::to_string(input)
75 }
76}