Skip to main content

Decoder

Struct Decoder 

Source
pub struct Decoder<'de> { /* private fields */ }
Expand description

JSON decoder over a unified token stream.

Implementations§

Source§

impl<'de> Decoder<'de>

Source

pub fn new(input: &'de [u8]) -> Self

Create a decoder from byte input (default config).

Examples found in repository?
examples/zero_copy_reuse.rs (line 89)
36fn main() -> nextjson::Result<()> {
37    // ---- 1. 零拷贝借用 ----
38    // payload 用未转义字符串书写:JSON 解码器对未转义字符串返回 Cow::Borrowed,
39    // 从而 `Bytes` 能直接借用输入切片(若写成 `[10,20,30,40]` 数组则必然拷贝,
40    // 与 serde 的 `&[u8]` 借用语义一致)。
41    let input = br#"{"event":"market.tick","payload":"raw-bytes","seq":7}"#;
42    let header: Header = nextjson::from_slice(input)?;
43    println!(
44        "借用解码: event = {:?}, payload = {:?}, seq = {}",
45        header.event,
46        header.payload.as_bytes(),
47        header.seq
48    );
49
50    // 指针范围断言:event / payload 必须落在输入切片内(零拷贝的直接证据)。
51    let input_start = input.as_ptr() as usize;
52    let input_end = input_start + input.len();
53    let event_ptr = header.event.as_ptr() as usize;
54    let payload_ptr = header.payload.as_bytes().as_ptr() as usize;
55    assert!(
56        (input_start..input_end).contains(&event_ptr),
57        "event 必须借用输入,不能拷贝"
58    );
59    assert!(
60        (input_start..input_end).contains(&payload_ptr),
61        "payload 必须借用输入,不能拷贝"
62    );
63    println!("指针断言通过: event 与 payload 均直接指向输入切片");
64
65    // 二进制格式通过 Value 中继,无法借用——改用拥有型等价物往返,
66    // 证明同一数据模型在 CBOR 中原生字节串无损。
67    let owned = HeaderOwned {
68        event: header.event.to_owned(),
69        payload: header.payload.as_bytes().to_vec(),
70        seq: header.seq,
71    };
72    let cbor = nextjson::formats::Cbor.encode(&owned)?;
73    let back: HeaderOwned = nextjson::formats::Cbor.decode(&cbor)?;
74    assert_eq!(back, owned);
75    println!("拥有型等价物经 CBOR 原生字节串往返一致: {} B", cbor.len());
76
77    // ---- 2. 就地解码 + 槽复用 ----
78    // 持续解码场景:同一个槽反复用于下一条消息,不重新分配存储。
79    let messages = [
80        br#"{"event":"a","payload":"x","seq":1}"#.as_slice(),
81        br#"{"event":"b","payload":"yy","seq":2}"#.as_slice(),
82        br#"{"event":"c","payload":"zzz","seq":3}"#.as_slice(),
83    ];
84
85    // 复用同一个 DecodeSlot<Header>,逐条 nextdecode_into。
86    let mut slot = DecodeSlot::<Header>::new();
87    let mut decoded: Vec<Header> = Vec::new();
88    for raw in &messages {
89        let mut decoder = Decoder::new(raw);
90        Header::nextdecode_into(&mut decoder, &mut slot)?;
91        decoder.end()?;
92        // take 取出本条,槽回归空,下一条继续复用。
93        decoded.push(slot.take().expect("解码成功必须写入槽"));
94    }
95    assert_eq!(decoded[0].seq, 1);
96    assert_eq!(decoded[1].event, "b");
97    assert_eq!(decoded[2].payload.as_bytes(), b"zzz");
98    println!(
99        "槽复用: 3 条消息共用 1 个 DecodeSlot,逐条解码成功: {:?}",
100        decoded.iter().map(|h| h.seq).collect::<Vec<_>>()
101    );
102
103    // 显式证明复用:一个槽连续解两条,且第二条完成后 is_initialized 恢复。
104    let mut slot2 = DecodeSlot::<Header>::new();
105    let mut d1 = Decoder::new(messages[0]);
106    Header::nextdecode_into(&mut d1, &mut slot2)?;
107    d1.end()?;
108    let first = slot2.take().unwrap();
109    let mut d2 = Decoder::new(messages[1]);
110    Header::nextdecode_into(&mut d2, &mut slot2)?;
111    d2.end()?;
112    let second = slot2.take().unwrap();
113    assert_eq!((first.seq, second.seq), (1, 2));
114    println!(
115        "同一个槽连续承载两条消息: seq {} -> seq {}",
116        first.seq, second.seq
117    );
118
119    Ok(())
120}
Source

pub fn with_config(input: &'de [u8], config: DecodeConfig) -> Self

Create a decoder from byte input (custom config).

Source

pub fn from_tokens(tokens: Vec<Token<'de>>) -> Self

Create a decoder over an in-memory token stream.

Source

pub fn max_depth(&self) -> u32

The maximum nesting depth.

Source

pub fn save(&self) -> Mark

Save the current position (for untagged-enum backtracking).

Source

pub fn restore(&mut self, mark: Mark)

Restore a position saved with save.

Source

pub fn end(&mut self) -> Result<()>

Verify that the input contains no value or token after the decoded value.

Whitespace at the end of byte input is accepted. Top-level helpers call this automatically; direct Decoder users can call it after nextdecode.

Examples found in repository?
examples/zero_copy_reuse.rs (line 91)
36fn main() -> nextjson::Result<()> {
37    // ---- 1. 零拷贝借用 ----
38    // payload 用未转义字符串书写:JSON 解码器对未转义字符串返回 Cow::Borrowed,
39    // 从而 `Bytes` 能直接借用输入切片(若写成 `[10,20,30,40]` 数组则必然拷贝,
40    // 与 serde 的 `&[u8]` 借用语义一致)。
41    let input = br#"{"event":"market.tick","payload":"raw-bytes","seq":7}"#;
42    let header: Header = nextjson::from_slice(input)?;
43    println!(
44        "借用解码: event = {:?}, payload = {:?}, seq = {}",
45        header.event,
46        header.payload.as_bytes(),
47        header.seq
48    );
49
50    // 指针范围断言:event / payload 必须落在输入切片内(零拷贝的直接证据)。
51    let input_start = input.as_ptr() as usize;
52    let input_end = input_start + input.len();
53    let event_ptr = header.event.as_ptr() as usize;
54    let payload_ptr = header.payload.as_bytes().as_ptr() as usize;
55    assert!(
56        (input_start..input_end).contains(&event_ptr),
57        "event 必须借用输入,不能拷贝"
58    );
59    assert!(
60        (input_start..input_end).contains(&payload_ptr),
61        "payload 必须借用输入,不能拷贝"
62    );
63    println!("指针断言通过: event 与 payload 均直接指向输入切片");
64
65    // 二进制格式通过 Value 中继,无法借用——改用拥有型等价物往返,
66    // 证明同一数据模型在 CBOR 中原生字节串无损。
67    let owned = HeaderOwned {
68        event: header.event.to_owned(),
69        payload: header.payload.as_bytes().to_vec(),
70        seq: header.seq,
71    };
72    let cbor = nextjson::formats::Cbor.encode(&owned)?;
73    let back: HeaderOwned = nextjson::formats::Cbor.decode(&cbor)?;
74    assert_eq!(back, owned);
75    println!("拥有型等价物经 CBOR 原生字节串往返一致: {} B", cbor.len());
76
77    // ---- 2. 就地解码 + 槽复用 ----
78    // 持续解码场景:同一个槽反复用于下一条消息,不重新分配存储。
79    let messages = [
80        br#"{"event":"a","payload":"x","seq":1}"#.as_slice(),
81        br#"{"event":"b","payload":"yy","seq":2}"#.as_slice(),
82        br#"{"event":"c","payload":"zzz","seq":3}"#.as_slice(),
83    ];
84
85    // 复用同一个 DecodeSlot<Header>,逐条 nextdecode_into。
86    let mut slot = DecodeSlot::<Header>::new();
87    let mut decoded: Vec<Header> = Vec::new();
88    for raw in &messages {
89        let mut decoder = Decoder::new(raw);
90        Header::nextdecode_into(&mut decoder, &mut slot)?;
91        decoder.end()?;
92        // take 取出本条,槽回归空,下一条继续复用。
93        decoded.push(slot.take().expect("解码成功必须写入槽"));
94    }
95    assert_eq!(decoded[0].seq, 1);
96    assert_eq!(decoded[1].event, "b");
97    assert_eq!(decoded[2].payload.as_bytes(), b"zzz");
98    println!(
99        "槽复用: 3 条消息共用 1 个 DecodeSlot,逐条解码成功: {:?}",
100        decoded.iter().map(|h| h.seq).collect::<Vec<_>>()
101    );
102
103    // 显式证明复用:一个槽连续解两条,且第二条完成后 is_initialized 恢复。
104    let mut slot2 = DecodeSlot::<Header>::new();
105    let mut d1 = Decoder::new(messages[0]);
106    Header::nextdecode_into(&mut d1, &mut slot2)?;
107    d1.end()?;
108    let first = slot2.take().unwrap();
109    let mut d2 = Decoder::new(messages[1]);
110    Header::nextdecode_into(&mut d2, &mut slot2)?;
111    d2.end()?;
112    let second = slot2.take().unwrap();
113    assert_eq!((first.seq, second.seq), (1, 2));
114    println!(
115        "同一个槽连续承载两条消息: seq {} -> seq {}",
116        first.seq, second.seq
117    );
118
119    Ok(())
120}
Source

pub fn begin_object(&mut self) -> Result<()>

Consume { (with depth check).

Source

pub fn end_object(&mut self) -> Result<()>

Consume }.

Source

pub fn object_key(&mut self) -> Result<Option<Cow<'de, str>>>

Read the next object key; returns None on } (not consumed).

Source

pub fn object_entry_sep(&mut self) -> Result<bool>

Object entry separator: true if more entries follow ( consumed), false at object end (} left for end_object).

Source

pub fn begin_array(&mut self) -> Result<()>

Consume [.

Source

pub fn end_array(&mut self) -> Result<()>

Consume ].

Source

pub fn array_has_more(&mut self) -> Result<bool>

Whether the array has more elements (] not consumed).

Source

pub fn array_entry_sep(&mut self) -> Result<bool>

Array entry separator: true if more elements follow ( consumed), false at array end (] left for end_array).

Source

pub fn unit(&mut self) -> Result<()>

Consume null.

Source

pub fn bool(&mut self) -> Result<bool>

Read a boolean.

Source

pub fn number(&mut self) -> Result<Number>

Read a number.

Source

pub fn string(&mut self) -> Result<Cow<'de, str>>

Read a string (may borrow input).

Source

pub fn char(&mut self) -> Result<char>

Read a single character (must be a one-character string).

Source

pub fn skip_value(&mut self) -> Result<()>

Skip any one value (recursive, depth-limited).

Byte inputs dispatch on the source byte directly (no Token is materialized); replayed token streams use the token path.

Trait Implementations§

Source§

impl<'de> FormatDecoder<'de> for Decoder<'de>

Source§

type Error = Error

The error type produced by this format’s methods. Read more
Source§

fn begin_object(&mut self) -> Result<(), Self::Error>

Consume { (with depth check).
Source§

fn end_object(&mut self) -> Result<(), Self::Error>

Consume }.
Source§

fn object_key(&mut self) -> Result<Option<Cow<'de, str>>, Self::Error>

Read the next object key; returns None on } (not consumed).
Source§

fn object_entry_sep(&mut self) -> Result<bool, Self::Error>

Object entry separator: true if more entries follow, false at end.
Source§

fn begin_array(&mut self) -> Result<(), Self::Error>

Consume [ (with depth check).
Source§

fn end_array(&mut self) -> Result<(), Self::Error>

Consume ].
Source§

fn array_has_more(&mut self) -> Result<bool, Self::Error>

Whether the array has more elements (] not consumed).
Source§

fn array_entry_sep(&mut self) -> Result<bool, Self::Error>

Array entry separator: true if more elements follow, false at end.
Source§

fn unit(&mut self) -> Result<(), Self::Error>

Consume null.
Source§

fn bool(&mut self) -> Result<bool, Self::Error>

Read a boolean.
Source§

fn number(&mut self) -> Result<Number, Self::Error>

Read a number.
Source§

fn string(&mut self) -> Result<Cow<'de, str>, Self::Error>

Read a string (may borrow the source).
Source§

fn char(&mut self) -> Result<char, Self::Error>

Read a single character (a one-scalar string).
Source§

fn skip_value(&mut self) -> Result<(), Self::Error>

Skip any one value.
Source§

fn option_tag(&mut self) -> Result<OptionTag, Self::Error>

Report whether the next value is Option::None or Option::Some. Read more
Source§

fn peek_token(&mut self) -> Result<Token<'de>, Self::Error>

Peek the next token without consuming it (container-flatten support).
Source§

fn next_token(&mut self) -> Result<Token<'de>, Self::Error>

Consume and return the next token.
Source§

fn save(&self) -> Mark

Save the current position (for untagged-enum backtracking).
Source§

fn restore(&mut self, mark: Mark)

Restore a position saved with save.
Source§

fn set_expecting(&mut self, expecting: &'static str) -> Option<&'static str>

Set the human-readable description of the type currently being decoded, so container-level type-mismatch errors (begin_object / begin_array hitting the wrong token) can name the expected type instead of a bare structural token like '{'. Read more
Source§

fn array_len_hint(&self) -> Option<usize>

A conservative upper bound for the remaining elements in the current array, when the wire format carries a length prefix. Read more
Source§

fn object_len_hint(&self) -> Option<usize>

A conservative upper bound for the remaining entries in the current object, subject to the same resource-safety rule as array_len_hint.
Source§

fn i8(&mut self) -> Result<i8, Self::Error>

Read a $t (default: read a number and convert). Read more
Source§

fn i16(&mut self) -> Result<i16, Self::Error>

Read a $t (default: read a number and convert). Read more
Source§

fn i32(&mut self) -> Result<i32, Self::Error>

Read a $t (default: read a number and convert). Read more
Source§

fn i64(&mut self) -> Result<i64, Self::Error>

Read a $t (default: read a number and convert). Read more
Source§

fn i128(&mut self) -> Result<i128, Self::Error>

Read a $t (default: read a number and convert). Read more
Source§

fn isize(&mut self) -> Result<isize, Self::Error>

Read a $t (default: read a number and convert). Read more
Source§

fn u8(&mut self) -> Result<u8, Self::Error>

Read a $t (default: read a number and convert). Read more
Source§

fn u16(&mut self) -> Result<u16, Self::Error>

Read a $t (default: read a number and convert). Read more
Source§

fn u32(&mut self) -> Result<u32, Self::Error>

Read a $t (default: read a number and convert). Read more
Source§

fn u64(&mut self) -> Result<u64, Self::Error>

Read a $t (default: read a number and convert). Read more
Source§

fn u128(&mut self) -> Result<u128, Self::Error>

Read a $t (default: read a number and convert). Read more
Source§

fn usize(&mut self) -> Result<usize, Self::Error>

Read a $t (default: read a number and convert). Read more
Source§

fn bytes(&mut self) -> Result<Cow<'de, [u8]>, Self::Error>

Read a byte sequence (may borrow the source). Read more
Source§

fn map_key<K: for<'a> NsonDeserialize<'a>>( &mut self, ) -> Result<Option<K>, Self::Error>

Read the next map key. Read more
Source§

fn is_human_readable(&self) -> bool

Whether this format produces human-readable output. Read more

Auto Trait Implementations§

§

impl<'de> Freeze for Decoder<'de>

§

impl<'de> RefUnwindSafe for Decoder<'de>

§

impl<'de> Send for Decoder<'de>

§

impl<'de> Sync for Decoder<'de>

§

impl<'de> Unpin for Decoder<'de>

§

impl<'de> UnsafeUnpin for Decoder<'de>

§

impl<'de> UnwindSafe for Decoder<'de>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.