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