qubit_codec/value/json_string_value_decoder.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 decoder for one owned value.
9
10use core::marker::PhantomData;
11
12use serde::de::DeserializeOwned;
13use serde_json::Error as JsonError;
14use serde_json::from_str;
15
16use super::ValueDecoder;
17
18/// Decodes one JSON string into an owned value via `serde_json`.
19///
20/// # Type Parameters
21///
22/// - `T`: Target value type deserialized through Serde.
23///
24/// # Examples
25///
26/// ```rust
27/// use qubit_codec::JsonStringValueDecoder;
28/// use qubit_codec::ValueDecoder;
29/// use serde::Deserialize;
30///
31/// #[derive(Debug, Deserialize, PartialEq)]
32/// struct Point {
33/// x: i32,
34/// y: i32,
35/// }
36///
37/// let mut decoder = JsonStringValueDecoder::<Point>::new();
38/// let point = decoder.decode(r#"{"x":1,"y":2}"#).unwrap();
39/// assert_eq!(point, Point { x: 1, y: 2 });
40/// ```
41#[must_use]
42#[derive(Debug, Clone, Copy, Default)]
43pub struct JsonStringValueDecoder<T> {
44 /// Tracks the owned output type without storing a value between calls.
45 _marker: PhantomData<T>,
46}
47
48impl<T> JsonStringValueDecoder<T> {
49 /// Creates a JSON string decoder for values of type `T`.
50 ///
51 /// # Returns
52 ///
53 /// Returns a stateless decoder without allocating or constructing a `T`.
54 #[inline]
55 pub const fn new() -> Self {
56 Self { _marker: PhantomData }
57 }
58}
59
60impl<T> ValueDecoder<str> for JsonStringValueDecoder<T>
61where
62 T: DeserializeOwned,
63{
64 /// JSON syntax or target-value deserialization failure.
65 type Error = JsonError;
66 /// Owned value deserialized independently of the input string lifetime.
67 type Output = T;
68
69 /// Deserializes `input` from a JSON string.
70 ///
71 /// # Parameters
72 ///
73 /// - `input`: One complete JSON value, optionally surrounded by whitespace.
74 ///
75 /// # Returns
76 ///
77 /// Returns an owned `T`; decoding may allocate according to the target
78 /// type.
79 ///
80 /// # Errors
81 ///
82 /// Returns a JSON error for malformed or incomplete input, trailing
83 /// non-whitespace data, or a value incompatible with `T`.
84 #[inline]
85 fn decode(&mut self, input: &str) -> Result<Self::Output, Self::Error> {
86 from_str(input)
87 }
88}