qubit_codec/value/json_bytes_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 bytes 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_slice;
15
16use super::ValueDecoder;
17
18/// Decodes UTF-8 JSON bytes into one 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::{JsonBytesValueDecoder, ValueDecoder};
28/// use serde::Deserialize;
29///
30/// #[derive(Debug, Deserialize, PartialEq)]
31/// struct Point {
32/// x: i32,
33/// y: i32,
34/// }
35///
36/// let mut decoder = JsonBytesValueDecoder::<Point>::new();
37/// let point = decoder.decode(br#"{"x":1,"y":2}"#).unwrap();
38/// assert_eq!(point, Point { x: 1, y: 2 });
39/// ```
40#[must_use]
41#[derive(Debug, Clone, Copy, Default)]
42pub struct JsonBytesValueDecoder<T> {
43 /// Associates the decoder with `T` without retaining a value.
44 _marker: PhantomData<T>,
45}
46
47impl<T> JsonBytesValueDecoder<T> {
48 /// Creates a JSON bytes decoder for values of type `T`.
49 ///
50 /// # Returns
51 ///
52 /// Returns a stateless decoder without allocating or constructing a `T`.
53 #[inline]
54 pub const fn new() -> Self {
55 Self { _marker: PhantomData }
56 }
57}
58
59impl<T> ValueDecoder<[u8]> for JsonBytesValueDecoder<T>
60where
61 T: DeserializeOwned,
62{
63 /// JSON syntax, UTF-8, or target-value deserialization failure.
64 type Error = JsonError;
65 /// Owned value deserialized independently of the input byte slice.
66 type Output = T;
67
68 /// Deserializes `input` from UTF-8 JSON bytes.
69 ///
70 /// # Parameters
71 ///
72 /// - `input`: One complete UTF-8 JSON value, optionally surrounded by
73 /// 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 invalid UTF-8, malformed or incomplete input,
83 /// trailing non-whitespace data, or a value incompatible with `T`.
84 #[inline]
85 fn decode(&mut self, input: &[u8]) -> Result<Self::Output, Self::Error> {
86 from_slice(input)
87 }
88}