pub struct Decoder<'de> { /* private fields */ }Expand description
JSON decoder over a unified token stream.
Implementations§
Source§impl<'de> Decoder<'de>
impl<'de> Decoder<'de>
Sourcepub fn new(input: &'de [u8]) -> Self
pub fn new(input: &'de [u8]) -> Self
Create a decoder from byte input (default config).
Examples found in repository?
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}Sourcepub fn with_config(input: &'de [u8], config: DecodeConfig) -> Self
pub fn with_config(input: &'de [u8], config: DecodeConfig) -> Self
Create a decoder from byte input (custom config).
Sourcepub fn from_tokens(tokens: Vec<Token<'de>>) -> Self
pub fn from_tokens(tokens: Vec<Token<'de>>) -> Self
Create a decoder over an in-memory token stream.
Sourcepub fn end(&mut self) -> Result<()>
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?
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}Sourcepub fn begin_object(&mut self) -> Result<()>
pub fn begin_object(&mut self) -> Result<()>
Consume { (with depth check).
Sourcepub fn end_object(&mut self) -> Result<()>
pub fn end_object(&mut self) -> Result<()>
Consume }.
Sourcepub fn object_key(&mut self) -> Result<Option<Cow<'de, str>>>
pub fn object_key(&mut self) -> Result<Option<Cow<'de, str>>>
Read the next object key; returns None on } (not consumed).
Sourcepub fn object_entry_sep(&mut self) -> Result<bool>
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).
Sourcepub fn begin_array(&mut self) -> Result<()>
pub fn begin_array(&mut self) -> Result<()>
Consume [.
Sourcepub fn array_has_more(&mut self) -> Result<bool>
pub fn array_has_more(&mut self) -> Result<bool>
Whether the array has more elements (] not consumed).
Sourcepub fn array_entry_sep(&mut self) -> Result<bool>
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).
Sourcepub fn char(&mut self) -> Result<char>
pub fn char(&mut self) -> Result<char>
Read a single character (must be a one-character string).
Sourcepub fn skip_value(&mut self) -> Result<()>
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>
impl<'de> FormatDecoder<'de> for Decoder<'de>
Source§fn object_key(&mut self) -> Result<Option<Cow<'de, str>>, Self::Error>
fn object_key(&mut self) -> Result<Option<Cow<'de, str>>, Self::Error>
None on } (not consumed).Source§fn object_entry_sep(&mut self) -> Result<bool, Self::Error>
fn object_entry_sep(&mut self) -> Result<bool, Self::Error>
true if more entries follow, false at end.Source§fn array_has_more(&mut self) -> Result<bool, Self::Error>
fn array_has_more(&mut self) -> Result<bool, Self::Error>
] not consumed).Source§fn array_entry_sep(&mut self) -> Result<bool, Self::Error>
fn array_entry_sep(&mut self) -> Result<bool, Self::Error>
true if more elements follow, false at end.Source§fn string(&mut self) -> Result<Cow<'de, str>, Self::Error>
fn string(&mut self) -> Result<Cow<'de, str>, Self::Error>
Source§fn char(&mut self) -> Result<char, Self::Error>
fn char(&mut self) -> Result<char, Self::Error>
Source§fn peek_token(&mut self) -> Result<Token<'de>, Self::Error>
fn peek_token(&mut self) -> Result<Token<'de>, Self::Error>
Source§fn next_token(&mut self) -> Result<Token<'de>, Self::Error>
fn next_token(&mut self) -> Result<Token<'de>, Self::Error>
Source§fn set_expecting(&mut self, expecting: &'static str) -> Option<&'static str>
fn set_expecting(&mut self, expecting: &'static str) -> Option<&'static str>
begin_object /
begin_array hitting the wrong token) can name the expected type
instead of a bare structural token like '{'. Read moreSource§fn array_len_hint(&self) -> Option<usize>
fn array_len_hint(&self) -> Option<usize>
Source§fn object_len_hint(&self) -> Option<usize>
fn object_len_hint(&self) -> Option<usize>
array_len_hint.Source§fn i8(&mut self) -> Result<i8, Self::Error>
fn i8(&mut self) -> Result<i8, Self::Error>
$t (default: read a number and convert). Read moreSource§fn i16(&mut self) -> Result<i16, Self::Error>
fn i16(&mut self) -> Result<i16, Self::Error>
$t (default: read a number and convert). Read moreSource§fn i32(&mut self) -> Result<i32, Self::Error>
fn i32(&mut self) -> Result<i32, Self::Error>
$t (default: read a number and convert). Read moreSource§fn i64(&mut self) -> Result<i64, Self::Error>
fn i64(&mut self) -> Result<i64, Self::Error>
$t (default: read a number and convert). Read moreSource§fn i128(&mut self) -> Result<i128, Self::Error>
fn i128(&mut self) -> Result<i128, Self::Error>
$t (default: read a number and convert). Read moreSource§fn isize(&mut self) -> Result<isize, Self::Error>
fn isize(&mut self) -> Result<isize, Self::Error>
$t (default: read a number and convert). Read moreSource§fn u8(&mut self) -> Result<u8, Self::Error>
fn u8(&mut self) -> Result<u8, Self::Error>
$t (default: read a number and convert). Read moreSource§fn u16(&mut self) -> Result<u16, Self::Error>
fn u16(&mut self) -> Result<u16, Self::Error>
$t (default: read a number and convert). Read moreSource§fn u32(&mut self) -> Result<u32, Self::Error>
fn u32(&mut self) -> Result<u32, Self::Error>
$t (default: read a number and convert). Read moreSource§fn u64(&mut self) -> Result<u64, Self::Error>
fn u64(&mut self) -> Result<u64, Self::Error>
$t (default: read a number and convert). Read moreSource§fn u128(&mut self) -> Result<u128, Self::Error>
fn u128(&mut self) -> Result<u128, Self::Error>
$t (default: read a number and convert). Read moreSource§fn usize(&mut self) -> Result<usize, Self::Error>
fn usize(&mut self) -> Result<usize, Self::Error>
$t (default: read a number and convert). Read more