1 //! Deserialization.
2
3 use core::f32;
4 use core::marker::PhantomData;
5 use core::result;
6 use core::str;
7 use half::f16;
8 use serde::de;
9 #[cfg(feature = "std")]
10 use std::io;
11
12 use crate::error::{Error, ErrorCode, Result};
13 #[cfg(not(feature = "unsealed_read_write"))]
14 use crate::read::EitherLifetime;
15 #[cfg(feature = "unsealed_read_write")]
16 pub use crate::read::EitherLifetime;
17 #[cfg(feature = "std")]
18 pub use crate::read::IoRead;
19 use crate::read::Offset;
20 #[cfg(any(feature = "std", feature = "alloc"))]
21 pub use crate::read::SliceRead;
22 pub use crate::read::{MutSliceRead, Read, SliceReadFixed};
23 #[cfg(feature = "tags")]
24 use crate::tags::set_tag;
25 /// Decodes a value from CBOR data in a slice.
26 ///
27 /// # Examples
28 ///
29 /// Deserialize a `String`
30 ///
31 /// ```
32 /// # use serde_cbor::de;
33 /// let v: Vec<u8> = vec![0x66, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72];
34 /// let value: String = de::from_slice(&v[..]).unwrap();
35 /// assert_eq!(value, "foobar");
36 /// ```
37 ///
38 /// Deserialize a borrowed string with zero copies.
39 ///
40 /// ```
41 /// # use serde_cbor::de;
42 /// let v: Vec<u8> = vec![0x66, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72];
43 /// let value: &str = de::from_slice(&v[..]).unwrap();
44 /// assert_eq!(value, "foobar");
45 /// ```
46 #[cfg(any(feature = "std", feature = "alloc"))]
from_slice<'a, T>(slice: &'a [u8]) -> Result<T> where T: de::Deserialize<'a>,47 pub fn from_slice<'a, T>(slice: &'a [u8]) -> Result<T>
48 where
49 T: de::Deserialize<'a>,
50 {
51 let mut deserializer = Deserializer::from_slice(slice);
52 let value = de::Deserialize::deserialize(&mut deserializer)?;
53 deserializer.end()?;
54 Ok(value)
55 }
56
57 // When the "std" feature is enabled there should be little to no need to ever use this function,
58 // as `from_slice` covers all use cases (at the expense of being less efficient).
59 /// Decode a value from CBOR data in a mutable slice.
60 ///
61 /// This can be used in analogy to `from_slice`. Unlike `from_slice`, this will use the slice's
62 /// mutability to rearrange data in it in order to resolve indefinite byte or text strings without
63 /// resorting to allocations.
from_mut_slice<'a, T>(slice: &'a mut [u8]) -> Result<T> where T: de::Deserialize<'a>,64 pub fn from_mut_slice<'a, T>(slice: &'a mut [u8]) -> Result<T>
65 where
66 T: de::Deserialize<'a>,
67 {
68 let mut deserializer = Deserializer::from_mut_slice(slice);
69 let value = de::Deserialize::deserialize(&mut deserializer)?;
70 deserializer.end()?;
71 Ok(value)
72 }
73
74 // When the "std" feature is enabled there should be little to no need to ever use this function,
75 // as `from_slice` covers all use cases and is much more reliable (at the expense of being less
76 // efficient).
77 /// Decode a value from CBOR data using a scratch buffer.
78 ///
79 /// Users should generally prefer to use `from_slice` or `from_mut_slice` over this function,
80 /// as decoding may fail when the scratch buffer turns out to be too small.
81 ///
82 /// A realistic use case for this method would be decoding in a `no_std` environment from an
83 /// immutable slice that is too large to copy.
from_slice_with_scratch<'a, 'b, T>(slice: &'a [u8], scratch: &'b mut [u8]) -> Result<T> where T: de::Deserialize<'a>,84 pub fn from_slice_with_scratch<'a, 'b, T>(slice: &'a [u8], scratch: &'b mut [u8]) -> Result<T>
85 where
86 T: de::Deserialize<'a>,
87 {
88 let mut deserializer = Deserializer::from_slice_with_scratch(slice, scratch);
89 let value = de::Deserialize::deserialize(&mut deserializer)?;
90 deserializer.end()?;
91 Ok(value)
92 }
93
94 /// Decodes a value from CBOR data in a reader.
95 ///
96 /// # Examples
97 ///
98 /// Deserialize a `String`
99 ///
100 /// ```
101 /// # use serde_cbor::de;
102 /// let v: Vec<u8> = vec![0x66, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72];
103 /// let value: String = de::from_reader(&v[..]).unwrap();
104 /// assert_eq!(value, "foobar");
105 /// ```
106 ///
107 /// Note that `from_reader` cannot borrow data:
108 ///
109 /// ```compile_fail
110 /// # use serde_cbor::de;
111 /// let v: Vec<u8> = vec![0x66, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72];
112 /// let value: &str = de::from_reader(&v[..]).unwrap();
113 /// assert_eq!(value, "foobar");
114 /// ```
115 #[cfg(feature = "std")]
from_reader<T, R>(reader: R) -> Result<T> where T: de::DeserializeOwned, R: io::Read,116 pub fn from_reader<T, R>(reader: R) -> Result<T>
117 where
118 T: de::DeserializeOwned,
119 R: io::Read,
120 {
121 let mut deserializer = Deserializer::from_reader(reader);
122 let value = de::Deserialize::deserialize(&mut deserializer)?;
123 deserializer.end()?;
124 Ok(value)
125 }
126
127 /// A Serde `Deserialize`r of CBOR data.
128 #[derive(Debug)]
129 pub struct Deserializer<R> {
130 read: R,
131 remaining_depth: u8,
132 accept_named: bool,
133 accept_packed: bool,
134 accept_standard_enums: bool,
135 accept_legacy_enums: bool,
136 }
137
138 #[cfg(feature = "std")]
139 impl<R> Deserializer<IoRead<R>>
140 where
141 R: io::Read,
142 {
143 /// Constructs a `Deserializer` which reads from a `Read`er.
from_reader(reader: R) -> Deserializer<IoRead<R>>144 pub fn from_reader(reader: R) -> Deserializer<IoRead<R>> {
145 Deserializer::new(IoRead::new(reader))
146 }
147 }
148
149 #[cfg(any(feature = "std", feature = "alloc"))]
150 impl<'a> Deserializer<SliceRead<'a>> {
151 /// Constructs a `Deserializer` which reads from a slice.
152 ///
153 /// Borrowed strings and byte slices will be provided when possible.
from_slice(bytes: &'a [u8]) -> Deserializer<SliceRead<'a>>154 pub fn from_slice(bytes: &'a [u8]) -> Deserializer<SliceRead<'a>> {
155 Deserializer::new(SliceRead::new(bytes))
156 }
157 }
158
159 impl<'a> Deserializer<MutSliceRead<'a>> {
160 /// Constructs a `Deserializer` which reads from a mutable slice that doubles as its own
161 /// scratch buffer.
162 ///
163 /// Borrowed strings and byte slices will be provided even for indefinite strings.
from_mut_slice(bytes: &'a mut [u8]) -> Deserializer<MutSliceRead<'a>>164 pub fn from_mut_slice(bytes: &'a mut [u8]) -> Deserializer<MutSliceRead<'a>> {
165 Deserializer::new(MutSliceRead::new(bytes))
166 }
167 }
168
169 impl<'a, 'b> Deserializer<SliceReadFixed<'a, 'b>> {
170 #[doc(hidden)]
from_slice_with_scratch( bytes: &'a [u8], scratch: &'b mut [u8], ) -> Deserializer<SliceReadFixed<'a, 'b>>171 pub fn from_slice_with_scratch(
172 bytes: &'a [u8],
173 scratch: &'b mut [u8],
174 ) -> Deserializer<SliceReadFixed<'a, 'b>> {
175 Deserializer::new(SliceReadFixed::new(bytes, scratch))
176 }
177 }
178
179 impl<'de, R> Deserializer<R>
180 where
181 R: Read<'de>,
182 {
183 /// Constructs a `Deserializer` from one of the possible serde_cbor input sources.
184 ///
185 /// `from_slice` and `from_reader` should normally be used instead of this method.
new(read: R) -> Self186 pub fn new(read: R) -> Self {
187 Deserializer {
188 read,
189 remaining_depth: 128,
190 accept_named: true,
191 accept_packed: true,
192 accept_standard_enums: true,
193 accept_legacy_enums: true,
194 }
195 }
196
197 /// Don't accept named variants and fields.
disable_named_format(mut self) -> Self198 pub fn disable_named_format(mut self) -> Self {
199 self.accept_named = false;
200 self
201 }
202
203 /// Don't accept numbered variants and fields.
disable_packed_format(mut self) -> Self204 pub fn disable_packed_format(mut self) -> Self {
205 self.accept_packed = false;
206 self
207 }
208
209 /// Don't accept the new enum format used by `serde_cbor` versions >= v0.10.
disable_standard_enums(mut self) -> Self210 pub fn disable_standard_enums(mut self) -> Self {
211 self.accept_standard_enums = false;
212 self
213 }
214
215 /// Don't accept the old enum format used by `serde_cbor` versions <= v0.9.
disable_legacy_enums(mut self) -> Self216 pub fn disable_legacy_enums(mut self) -> Self {
217 self.accept_legacy_enums = false;
218 self
219 }
220
221 /// This method should be called after a value has been deserialized to ensure there is no
222 /// trailing data in the input source.
end(&mut self) -> Result<()>223 pub fn end(&mut self) -> Result<()> {
224 match self.next()? {
225 Some(_) => Err(self.error(ErrorCode::TrailingData)),
226 None => Ok(()),
227 }
228 }
229
230 /// Turn a CBOR deserializer into an iterator over values of type T.
231 #[allow(clippy::should_implement_trait)] // Trait doesn't allow unconstrained T.
into_iter<T>(self) -> StreamDeserializer<'de, R, T> where T: de::Deserialize<'de>,232 pub fn into_iter<T>(self) -> StreamDeserializer<'de, R, T>
233 where
234 T: de::Deserialize<'de>,
235 {
236 StreamDeserializer {
237 de: self,
238 output: PhantomData,
239 lifetime: PhantomData,
240 }
241 }
242
next(&mut self) -> Result<Option<u8>>243 fn next(&mut self) -> Result<Option<u8>> {
244 self.read.next()
245 }
246
peek(&mut self) -> Result<Option<u8>>247 fn peek(&mut self) -> Result<Option<u8>> {
248 self.read.peek()
249 }
250
consume(&mut self)251 fn consume(&mut self) {
252 self.read.discard();
253 }
254
error(&self, reason: ErrorCode) -> Error255 fn error(&self, reason: ErrorCode) -> Error {
256 let offset = self.read.offset();
257 Error::syntax(reason, offset)
258 }
259
parse_u8(&mut self) -> Result<u8>260 fn parse_u8(&mut self) -> Result<u8> {
261 match self.next()? {
262 Some(byte) => Ok(byte),
263 None => Err(self.error(ErrorCode::EofWhileParsingValue)),
264 }
265 }
266
parse_u16(&mut self) -> Result<u16>267 fn parse_u16(&mut self) -> Result<u16> {
268 let mut buf = [0; 2];
269 self.read
270 .read_into(&mut buf)
271 .map(|()| u16::from_be_bytes(buf))
272 }
273
parse_u32(&mut self) -> Result<u32>274 fn parse_u32(&mut self) -> Result<u32> {
275 let mut buf = [0; 4];
276 self.read
277 .read_into(&mut buf)
278 .map(|()| u32::from_be_bytes(buf))
279 }
280
parse_u64(&mut self) -> Result<u64>281 fn parse_u64(&mut self) -> Result<u64> {
282 let mut buf = [0; 8];
283 self.read
284 .read_into(&mut buf)
285 .map(|()| u64::from_be_bytes(buf))
286 }
287
parse_bytes<V>(&mut self, len: usize, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>,288 fn parse_bytes<V>(&mut self, len: usize, visitor: V) -> Result<V::Value>
289 where
290 V: de::Visitor<'de>,
291 {
292 match self.read.read(len)? {
293 EitherLifetime::Long(buf) => visitor.visit_borrowed_bytes(buf),
294 EitherLifetime::Short(buf) => visitor.visit_bytes(buf),
295 }
296 }
297
parse_indefinite_bytes<V>(&mut self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>,298 fn parse_indefinite_bytes<V>(&mut self, visitor: V) -> Result<V::Value>
299 where
300 V: de::Visitor<'de>,
301 {
302 self.read.clear_buffer();
303 loop {
304 let byte = self.parse_u8()?;
305 let len = match byte {
306 0x40..=0x57 => byte as usize - 0x40,
307 0x58 => self.parse_u8()? as usize,
308 0x59 => self.parse_u16()? as usize,
309 0x5a => self.parse_u32()? as usize,
310 0x5b => {
311 let len = self.parse_u64()?;
312 if len > usize::max_value() as u64 {
313 return Err(self.error(ErrorCode::LengthOutOfRange));
314 }
315 len as usize
316 }
317 0xff => break,
318 _ => return Err(self.error(ErrorCode::UnexpectedCode)),
319 };
320
321 self.read.read_to_buffer(len)?;
322 }
323
324 match self.read.take_buffer() {
325 EitherLifetime::Long(buf) => visitor.visit_borrowed_bytes(buf),
326 EitherLifetime::Short(buf) => visitor.visit_bytes(buf),
327 }
328 }
329
convert_str<'a>(buf: &'a [u8], buf_end_offset: u64) -> Result<&'a str>330 fn convert_str<'a>(buf: &'a [u8], buf_end_offset: u64) -> Result<&'a str> {
331 match str::from_utf8(buf) {
332 Ok(s) => Ok(s),
333 Err(e) => {
334 let shift = buf.len() - e.valid_up_to();
335 let offset = buf_end_offset - shift as u64;
336 Err(Error::syntax(ErrorCode::InvalidUtf8, offset))
337 }
338 }
339 }
340
parse_str<V>(&mut self, len: usize, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>,341 fn parse_str<V>(&mut self, len: usize, visitor: V) -> Result<V::Value>
342 where
343 V: de::Visitor<'de>,
344 {
345 if let Some(offset) = self.read.offset().checked_add(len as u64) {
346 match self.read.read(len)? {
347 EitherLifetime::Long(buf) => {
348 let s = Self::convert_str(buf, offset)?;
349 visitor.visit_borrowed_str(s)
350 }
351 EitherLifetime::Short(buf) => {
352 let s = Self::convert_str(buf, offset)?;
353 visitor.visit_str(s)
354 }
355 }
356 } else {
357 // An overflow would have occured.
358 Err(Error::syntax(
359 ErrorCode::LengthOutOfRange,
360 self.read.offset(),
361 ))
362 }
363 }
364
parse_indefinite_str<V>(&mut self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>,365 fn parse_indefinite_str<V>(&mut self, visitor: V) -> Result<V::Value>
366 where
367 V: de::Visitor<'de>,
368 {
369 self.read.clear_buffer();
370 loop {
371 let byte = self.parse_u8()?;
372 let len = match byte {
373 0x60..=0x77 => byte as usize - 0x60,
374 0x78 => self.parse_u8()? as usize,
375 0x79 => self.parse_u16()? as usize,
376 0x7a => self.parse_u32()? as usize,
377 0x7b => {
378 let len = self.parse_u64()?;
379 if len > usize::max_value() as u64 {
380 return Err(self.error(ErrorCode::LengthOutOfRange));
381 }
382 len as usize
383 }
384 0xff => break,
385 _ => return Err(self.error(ErrorCode::UnexpectedCode)),
386 };
387
388 self.read.read_to_buffer(len)?;
389 }
390
391 let offset = self.read.offset();
392 match self.read.take_buffer() {
393 EitherLifetime::Long(buf) => {
394 let s = Self::convert_str(buf, offset)?;
395 visitor.visit_borrowed_str(s)
396 }
397 EitherLifetime::Short(buf) => {
398 let s = Self::convert_str(buf, offset)?;
399 visitor.visit_str(s)
400 }
401 }
402 }
403
404 #[cfg(feature = "tags")]
handle_tagged_value<V>(&mut self, tag: u64, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>,405 fn handle_tagged_value<V>(&mut self, tag: u64, visitor: V) -> Result<V::Value>
406 where
407 V: de::Visitor<'de>,
408 {
409 self.recursion_checked(|d| {
410 set_tag(Some(tag));
411 let r = visitor.visit_newtype_struct(d);
412 set_tag(None);
413 r
414 })
415 }
416
417 #[cfg(not(feature = "tags"))]
handle_tagged_value<V>(&mut self, _tag: u64, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>,418 fn handle_tagged_value<V>(&mut self, _tag: u64, visitor: V) -> Result<V::Value>
419 where
420 V: de::Visitor<'de>,
421 {
422 self.recursion_checked(|de| de.parse_value(visitor))
423 }
424
recursion_checked<F, T>(&mut self, f: F) -> Result<T> where F: FnOnce(&mut Deserializer<R>) -> Result<T>,425 fn recursion_checked<F, T>(&mut self, f: F) -> Result<T>
426 where
427 F: FnOnce(&mut Deserializer<R>) -> Result<T>,
428 {
429 self.remaining_depth -= 1;
430 if self.remaining_depth == 0 {
431 return Err(self.error(ErrorCode::RecursionLimitExceeded));
432 }
433 let r = f(self);
434 self.remaining_depth += 1;
435 r
436 }
437
parse_array<V>(&mut self, mut len: usize, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>,438 fn parse_array<V>(&mut self, mut len: usize, visitor: V) -> Result<V::Value>
439 where
440 V: de::Visitor<'de>,
441 {
442 self.recursion_checked(|de| {
443 let value = visitor.visit_seq(SeqAccess { de, len: &mut len })?;
444
445 if len != 0 {
446 Err(de.error(ErrorCode::TrailingData))
447 } else {
448 Ok(value)
449 }
450 })
451 }
452
parse_indefinite_array<V>(&mut self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>,453 fn parse_indefinite_array<V>(&mut self, visitor: V) -> Result<V::Value>
454 where
455 V: de::Visitor<'de>,
456 {
457 self.recursion_checked(|de| {
458 let value = visitor.visit_seq(IndefiniteSeqAccess { de })?;
459 match de.next()? {
460 Some(0xff) => Ok(value),
461 Some(_) => Err(de.error(ErrorCode::TrailingData)),
462 None => Err(de.error(ErrorCode::EofWhileParsingArray)),
463 }
464 })
465 }
466
parse_map<V>(&mut self, mut len: usize, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>,467 fn parse_map<V>(&mut self, mut len: usize, visitor: V) -> Result<V::Value>
468 where
469 V: de::Visitor<'de>,
470 {
471 let accept_packed = self.accept_packed;
472 let accept_named = self.accept_named;
473 self.recursion_checked(|de| {
474 let value = visitor.visit_map(MapAccess {
475 de,
476 len: &mut len,
477 accept_named,
478 accept_packed,
479 })?;
480
481 if len != 0 {
482 Err(de.error(ErrorCode::TrailingData))
483 } else {
484 Ok(value)
485 }
486 })
487 }
488
parse_indefinite_map<V>(&mut self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>,489 fn parse_indefinite_map<V>(&mut self, visitor: V) -> Result<V::Value>
490 where
491 V: de::Visitor<'de>,
492 {
493 let accept_named = self.accept_named;
494 let accept_packed = self.accept_packed;
495 self.recursion_checked(|de| {
496 let value = visitor.visit_map(IndefiniteMapAccess {
497 de,
498 accept_packed,
499 accept_named,
500 })?;
501 match de.next()? {
502 Some(0xff) => Ok(value),
503 Some(_) => Err(de.error(ErrorCode::TrailingData)),
504 None => Err(de.error(ErrorCode::EofWhileParsingMap)),
505 }
506 })
507 }
508
parse_enum<V>(&mut self, mut len: usize, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>,509 fn parse_enum<V>(&mut self, mut len: usize, visitor: V) -> Result<V::Value>
510 where
511 V: de::Visitor<'de>,
512 {
513 self.recursion_checked(|de| {
514 let value = visitor.visit_enum(VariantAccess {
515 seq: SeqAccess { de, len: &mut len },
516 })?;
517
518 if len != 0 {
519 Err(de.error(ErrorCode::TrailingData))
520 } else {
521 Ok(value)
522 }
523 })
524 }
525
parse_enum_map<V>(&mut self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>,526 fn parse_enum_map<V>(&mut self, visitor: V) -> Result<V::Value>
527 where
528 V: de::Visitor<'de>,
529 {
530 let accept_named = self.accept_named;
531 let accept_packed = self.accept_packed;
532 self.recursion_checked(|de| {
533 let mut len = 1;
534 let value = visitor.visit_enum(VariantAccessMap {
535 map: MapAccess {
536 de,
537 len: &mut len,
538 accept_packed,
539 accept_named,
540 },
541 })?;
542
543 if len != 0 {
544 Err(de.error(ErrorCode::TrailingData))
545 } else {
546 Ok(value)
547 }
548 })
549 }
550
parse_indefinite_enum<V>(&mut self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>,551 fn parse_indefinite_enum<V>(&mut self, visitor: V) -> Result<V::Value>
552 where
553 V: de::Visitor<'de>,
554 {
555 self.recursion_checked(|de| {
556 let value = visitor.visit_enum(VariantAccess {
557 seq: IndefiniteSeqAccess { de },
558 })?;
559 match de.next()? {
560 Some(0xff) => Ok(value),
561 Some(_) => Err(de.error(ErrorCode::TrailingData)),
562 None => Err(de.error(ErrorCode::EofWhileParsingArray)),
563 }
564 })
565 }
566
parse_f16(&mut self) -> Result<f32>567 fn parse_f16(&mut self) -> Result<f32> {
568 Ok(f32::from(f16::from_bits(self.parse_u16()?)))
569 }
570
parse_f32(&mut self) -> Result<f32>571 fn parse_f32(&mut self) -> Result<f32> {
572 self.parse_u32().map(|i| f32::from_bits(i))
573 }
574
parse_f64(&mut self) -> Result<f64>575 fn parse_f64(&mut self) -> Result<f64> {
576 self.parse_u64().map(|i| f64::from_bits(i))
577 }
578
579 // Don't warn about the `unreachable!` in case
580 // exhaustive integer pattern matching is enabled.
581 #[allow(unreachable_patterns)]
parse_value<V>(&mut self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>,582 fn parse_value<V>(&mut self, visitor: V) -> Result<V::Value>
583 where
584 V: de::Visitor<'de>,
585 {
586 let byte = self.parse_u8()?;
587 match byte {
588 // Major type 0: an unsigned integer
589 0x00..=0x17 => visitor.visit_u8(byte),
590 0x18 => {
591 let value = self.parse_u8()?;
592 visitor.visit_u8(value)
593 }
594 0x19 => {
595 let value = self.parse_u16()?;
596 visitor.visit_u16(value)
597 }
598 0x1a => {
599 let value = self.parse_u32()?;
600 visitor.visit_u32(value)
601 }
602 0x1b => {
603 let value = self.parse_u64()?;
604 visitor.visit_u64(value)
605 }
606 0x1c..=0x1f => Err(self.error(ErrorCode::UnassignedCode)),
607
608 // Major type 1: a negative integer
609 0x20..=0x37 => visitor.visit_i8(-1 - (byte - 0x20) as i8),
610 0x38 => {
611 let value = self.parse_u8()?;
612 visitor.visit_i16(-1 - i16::from(value))
613 }
614 0x39 => {
615 let value = self.parse_u16()?;
616 visitor.visit_i32(-1 - i32::from(value))
617 }
618 0x3a => {
619 let value = self.parse_u32()?;
620 visitor.visit_i64(-1 - i64::from(value))
621 }
622 0x3b => {
623 let value = self.parse_u64()?;
624 if value > i64::max_value() as u64 {
625 return visitor.visit_i128(-1 - i128::from(value));
626 }
627 visitor.visit_i64(-1 - value as i64)
628 }
629 0x3c..=0x3f => Err(self.error(ErrorCode::UnassignedCode)),
630
631 // Major type 2: a byte string
632 0x40..=0x57 => self.parse_bytes(byte as usize - 0x40, visitor),
633 0x58 => {
634 let len = self.parse_u8()?;
635 self.parse_bytes(len as usize, visitor)
636 }
637 0x59 => {
638 let len = self.parse_u16()?;
639 self.parse_bytes(len as usize, visitor)
640 }
641 0x5a => {
642 let len = self.parse_u32()?;
643 self.parse_bytes(len as usize, visitor)
644 }
645 0x5b => {
646 let len = self.parse_u64()?;
647 if len > usize::max_value() as u64 {
648 return Err(self.error(ErrorCode::LengthOutOfRange));
649 }
650 self.parse_bytes(len as usize, visitor)
651 }
652 0x5c..=0x5e => Err(self.error(ErrorCode::UnassignedCode)),
653 0x5f => self.parse_indefinite_bytes(visitor),
654
655 // Major type 3: a text string
656 0x60..=0x77 => self.parse_str(byte as usize - 0x60, visitor),
657 0x78 => {
658 let len = self.parse_u8()?;
659 self.parse_str(len as usize, visitor)
660 }
661 0x79 => {
662 let len = self.parse_u16()?;
663 self.parse_str(len as usize, visitor)
664 }
665 0x7a => {
666 let len = self.parse_u32()?;
667 self.parse_str(len as usize, visitor)
668 }
669 0x7b => {
670 let len = self.parse_u64()?;
671 if len > usize::max_value() as u64 {
672 return Err(self.error(ErrorCode::LengthOutOfRange));
673 }
674 self.parse_str(len as usize, visitor)
675 }
676 0x7c..=0x7e => Err(self.error(ErrorCode::UnassignedCode)),
677 0x7f => self.parse_indefinite_str(visitor),
678
679 // Major type 4: an array of data items
680 0x80..=0x97 => self.parse_array(byte as usize - 0x80, visitor),
681 0x98 => {
682 let len = self.parse_u8()?;
683 self.parse_array(len as usize, visitor)
684 }
685 0x99 => {
686 let len = self.parse_u16()?;
687 self.parse_array(len as usize, visitor)
688 }
689 0x9a => {
690 let len = self.parse_u32()?;
691 self.parse_array(len as usize, visitor)
692 }
693 0x9b => {
694 let len = self.parse_u64()?;
695 if len > usize::max_value() as u64 {
696 return Err(self.error(ErrorCode::LengthOutOfRange));
697 }
698 self.parse_array(len as usize, visitor)
699 }
700 0x9c..=0x9e => Err(self.error(ErrorCode::UnassignedCode)),
701 0x9f => self.parse_indefinite_array(visitor),
702
703 // Major type 5: a map of pairs of data items
704 0xa0..=0xb7 => self.parse_map(byte as usize - 0xa0, visitor),
705 0xb8 => {
706 let len = self.parse_u8()?;
707 self.parse_map(len as usize, visitor)
708 }
709 0xb9 => {
710 let len = self.parse_u16()?;
711 self.parse_map(len as usize, visitor)
712 }
713 0xba => {
714 let len = self.parse_u32()?;
715 self.parse_map(len as usize, visitor)
716 }
717 0xbb => {
718 let len = self.parse_u64()?;
719 if len > usize::max_value() as u64 {
720 return Err(self.error(ErrorCode::LengthOutOfRange));
721 }
722 self.parse_map(len as usize, visitor)
723 }
724 0xbc..=0xbe => Err(self.error(ErrorCode::UnassignedCode)),
725 0xbf => self.parse_indefinite_map(visitor),
726
727 // Major type 6: optional semantic tagging of other major types
728 0xc0..=0xd7 => {
729 let tag = u64::from(byte) - 0xc0;
730 self.handle_tagged_value(tag, visitor)
731 }
732 0xd8 => {
733 let tag = self.parse_u8()?;
734 self.handle_tagged_value(tag.into(), visitor)
735 }
736 0xd9 => {
737 let tag = self.parse_u16()?;
738 self.handle_tagged_value(tag.into(), visitor)
739 }
740 0xda => {
741 let tag = self.parse_u32()?;
742 self.handle_tagged_value(tag.into(), visitor)
743 }
744 0xdb => {
745 let tag = self.parse_u64()?;
746 self.handle_tagged_value(tag, visitor)
747 }
748 0xdc..=0xdf => Err(self.error(ErrorCode::UnassignedCode)),
749
750 // Major type 7: floating-point numbers and other simple data types that need no content
751 0xe0..=0xf3 => Err(self.error(ErrorCode::UnassignedCode)),
752 0xf4 => visitor.visit_bool(false),
753 0xf5 => visitor.visit_bool(true),
754 0xf6 => visitor.visit_unit(),
755 0xf7 => visitor.visit_unit(),
756 0xf8 => Err(self.error(ErrorCode::UnassignedCode)),
757 0xf9 => {
758 let value = self.parse_f16()?;
759 visitor.visit_f32(value)
760 }
761 0xfa => {
762 let value = self.parse_f32()?;
763 visitor.visit_f32(value)
764 }
765 0xfb => {
766 let value = self.parse_f64()?;
767 visitor.visit_f64(value)
768 }
769 0xfc..=0xfe => Err(self.error(ErrorCode::UnassignedCode)),
770 0xff => Err(self.error(ErrorCode::UnexpectedCode)),
771
772 _ => unreachable!(),
773 }
774 }
775 }
776
777 impl<'de, 'a, R> de::Deserializer<'de> for &'a mut Deserializer<R>
778 where
779 R: Read<'de>,
780 {
781 type Error = Error;
782
783 #[inline]
deserialize_any<V>(self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>,784 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value>
785 where
786 V: de::Visitor<'de>,
787 {
788 self.parse_value(visitor)
789 }
790
791 #[inline]
deserialize_option<V>(self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>,792 fn deserialize_option<V>(self, visitor: V) -> Result<V::Value>
793 where
794 V: de::Visitor<'de>,
795 {
796 match self.peek()? {
797 Some(0xf6) => {
798 self.consume();
799 visitor.visit_none()
800 }
801 _ => visitor.visit_some(self),
802 }
803 }
804
805 #[inline]
deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>,806 fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value>
807 where
808 V: de::Visitor<'de>,
809 {
810 visitor.visit_newtype_struct(self)
811 }
812
813 // Unit variants are encoded as just the variant identifier.
814 // Tuple variants are encoded as an array of the variant identifier followed by the fields.
815 // Struct variants are encoded as an array of the variant identifier followed by the struct.
816 #[inline]
deserialize_enum<V>( self, _name: &str, _variants: &'static [&'static str], visitor: V, ) -> Result<V::Value> where V: de::Visitor<'de>,817 fn deserialize_enum<V>(
818 self,
819 _name: &str,
820 _variants: &'static [&'static str],
821 visitor: V,
822 ) -> Result<V::Value>
823 where
824 V: de::Visitor<'de>,
825 {
826 match self.peek()? {
827 Some(byte @ 0x80..=0x9f) => {
828 if !self.accept_legacy_enums {
829 return Err(self.error(ErrorCode::WrongEnumFormat));
830 }
831 self.consume();
832 match byte {
833 0x80..=0x97 => self.parse_enum(byte as usize - 0x80, visitor),
834 0x98 => {
835 let len = self.parse_u8()?;
836 self.parse_enum(len as usize, visitor)
837 }
838 0x99 => {
839 let len = self.parse_u16()?;
840 self.parse_enum(len as usize, visitor)
841 }
842 0x9a => {
843 let len = self.parse_u32()?;
844 self.parse_enum(len as usize, visitor)
845 }
846 0x9b => {
847 let len = self.parse_u64()?;
848 if len > usize::max_value() as u64 {
849 return Err(self.error(ErrorCode::LengthOutOfRange));
850 }
851 self.parse_enum(len as usize, visitor)
852 }
853 0x9c..=0x9e => Err(self.error(ErrorCode::UnassignedCode)),
854 0x9f => self.parse_indefinite_enum(visitor),
855
856 _ => unreachable!(),
857 }
858 }
859 Some(0xa1) => {
860 if !self.accept_standard_enums {
861 return Err(self.error(ErrorCode::WrongEnumFormat));
862 }
863 self.consume();
864 self.parse_enum_map(visitor)
865 }
866 None => Err(self.error(ErrorCode::EofWhileParsingValue)),
867 _ => {
868 if !self.accept_standard_enums && !self.accept_legacy_enums {
869 return Err(self.error(ErrorCode::WrongEnumFormat));
870 }
871 visitor.visit_enum(UnitVariantAccess { de: self })
872 }
873 }
874 }
875
876 #[inline]
is_human_readable(&self) -> bool877 fn is_human_readable(&self) -> bool {
878 false
879 }
880
881 serde::forward_to_deserialize_any! {
882 bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string unit
883 unit_struct seq tuple tuple_struct map struct identifier ignored_any
884 bytes byte_buf
885 }
886 }
887
888 impl<R> Deserializer<R>
889 where
890 R: Offset,
891 {
892 /// Return the current offset in the reader
893 #[inline]
byte_offset(&self) -> usize894 pub fn byte_offset(&self) -> usize {
895 self.read.byte_offset()
896 }
897 }
898
899 trait MakeError {
error(&self, code: ErrorCode) -> Error900 fn error(&self, code: ErrorCode) -> Error;
901 }
902
903 struct SeqAccess<'a, R> {
904 de: &'a mut Deserializer<R>,
905 len: &'a mut usize,
906 }
907
908 impl<'de, 'a, R> de::SeqAccess<'de> for SeqAccess<'a, R>
909 where
910 R: Read<'de>,
911 {
912 type Error = Error;
913
next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>> where T: de::DeserializeSeed<'de>,914 fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
915 where
916 T: de::DeserializeSeed<'de>,
917 {
918 if *self.len == 0 {
919 return Ok(None);
920 }
921 *self.len -= 1;
922
923 let value = seed.deserialize(&mut *self.de)?;
924 Ok(Some(value))
925 }
926
size_hint(&self) -> Option<usize>927 fn size_hint(&self) -> Option<usize> {
928 Some(*self.len)
929 }
930 }
931
932 impl<'de, 'a, R> MakeError for SeqAccess<'a, R>
933 where
934 R: Read<'de>,
935 {
error(&self, code: ErrorCode) -> Error936 fn error(&self, code: ErrorCode) -> Error {
937 self.de.error(code)
938 }
939 }
940
941 struct IndefiniteSeqAccess<'a, R> {
942 de: &'a mut Deserializer<R>,
943 }
944
945 impl<'de, 'a, R> de::SeqAccess<'de> for IndefiniteSeqAccess<'a, R>
946 where
947 R: Read<'de>,
948 {
949 type Error = Error;
950
next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>> where T: de::DeserializeSeed<'de>,951 fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
952 where
953 T: de::DeserializeSeed<'de>,
954 {
955 match self.de.peek()? {
956 Some(0xff) => return Ok(None),
957 Some(_) => {}
958 None => return Err(self.de.error(ErrorCode::EofWhileParsingArray)),
959 }
960
961 let value = seed.deserialize(&mut *self.de)?;
962 Ok(Some(value))
963 }
964 }
965
966 impl<'de, 'a, R> MakeError for IndefiniteSeqAccess<'a, R>
967 where
968 R: Read<'de>,
969 {
error(&self, code: ErrorCode) -> Error970 fn error(&self, code: ErrorCode) -> Error {
971 self.de.error(code)
972 }
973 }
974
975 struct MapAccess<'a, R> {
976 de: &'a mut Deserializer<R>,
977 len: &'a mut usize,
978 accept_named: bool,
979 accept_packed: bool,
980 }
981
982 impl<'de, 'a, R> de::MapAccess<'de> for MapAccess<'a, R>
983 where
984 R: Read<'de>,
985 {
986 type Error = Error;
987
next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>> where K: de::DeserializeSeed<'de>,988 fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
989 where
990 K: de::DeserializeSeed<'de>,
991 {
992 if *self.len == 0 {
993 return Ok(None);
994 }
995 *self.len -= 1;
996
997 match self.de.peek()? {
998 Some(_byte @ 0x00..=0x1b) if !self.accept_packed => {
999 return Err(self.de.error(ErrorCode::WrongStructFormat));
1000 }
1001 Some(_byte @ 0x60..=0x7f) if !self.accept_named => {
1002 return Err(self.de.error(ErrorCode::WrongStructFormat));
1003 }
1004 _ => {}
1005 };
1006
1007 let value = seed.deserialize(&mut *self.de)?;
1008 Ok(Some(value))
1009 }
1010
next_value_seed<V>(&mut self, seed: V) -> Result<V::Value> where V: de::DeserializeSeed<'de>,1011 fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value>
1012 where
1013 V: de::DeserializeSeed<'de>,
1014 {
1015 seed.deserialize(&mut *self.de)
1016 }
1017
size_hint(&self) -> Option<usize>1018 fn size_hint(&self) -> Option<usize> {
1019 Some(*self.len)
1020 }
1021 }
1022
1023 impl<'de, 'a, R> MakeError for MapAccess<'a, R>
1024 where
1025 R: Read<'de>,
1026 {
error(&self, code: ErrorCode) -> Error1027 fn error(&self, code: ErrorCode) -> Error {
1028 self.de.error(code)
1029 }
1030 }
1031
1032 struct IndefiniteMapAccess<'a, R> {
1033 de: &'a mut Deserializer<R>,
1034 accept_packed: bool,
1035 accept_named: bool,
1036 }
1037
1038 impl<'de, 'a, R> de::MapAccess<'de> for IndefiniteMapAccess<'a, R>
1039 where
1040 R: Read<'de>,
1041 {
1042 type Error = Error;
1043
next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>> where K: de::DeserializeSeed<'de>,1044 fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
1045 where
1046 K: de::DeserializeSeed<'de>,
1047 {
1048 match self.de.peek()? {
1049 Some(_byte @ 0x00..=0x1b) if !self.accept_packed => {
1050 return Err(self.de.error(ErrorCode::WrongStructFormat))
1051 }
1052 Some(_byte @ 0x60..=0x7f) if !self.accept_named => {
1053 return Err(self.de.error(ErrorCode::WrongStructFormat))
1054 }
1055 Some(0xff) => return Ok(None),
1056 Some(_) => {}
1057 None => return Err(self.de.error(ErrorCode::EofWhileParsingMap)),
1058 }
1059
1060 let value = seed.deserialize(&mut *self.de)?;
1061 Ok(Some(value))
1062 }
1063
next_value_seed<V>(&mut self, seed: V) -> Result<V::Value> where V: de::DeserializeSeed<'de>,1064 fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value>
1065 where
1066 V: de::DeserializeSeed<'de>,
1067 {
1068 seed.deserialize(&mut *self.de)
1069 }
1070 }
1071
1072 struct UnitVariantAccess<'a, R> {
1073 de: &'a mut Deserializer<R>,
1074 }
1075
1076 impl<'de, 'a, R> de::EnumAccess<'de> for UnitVariantAccess<'a, R>
1077 where
1078 R: Read<'de>,
1079 {
1080 type Error = Error;
1081 type Variant = UnitVariantAccess<'a, R>;
1082
variant_seed<V>(self, seed: V) -> Result<(V::Value, UnitVariantAccess<'a, R>)> where V: de::DeserializeSeed<'de>,1083 fn variant_seed<V>(self, seed: V) -> Result<(V::Value, UnitVariantAccess<'a, R>)>
1084 where
1085 V: de::DeserializeSeed<'de>,
1086 {
1087 let variant = seed.deserialize(&mut *self.de)?;
1088 Ok((variant, self))
1089 }
1090 }
1091
1092 impl<'de, 'a, R> de::VariantAccess<'de> for UnitVariantAccess<'a, R>
1093 where
1094 R: Read<'de>,
1095 {
1096 type Error = Error;
1097
unit_variant(self) -> Result<()>1098 fn unit_variant(self) -> Result<()> {
1099 Ok(())
1100 }
1101
newtype_variant_seed<T>(self, _seed: T) -> Result<T::Value> where T: de::DeserializeSeed<'de>,1102 fn newtype_variant_seed<T>(self, _seed: T) -> Result<T::Value>
1103 where
1104 T: de::DeserializeSeed<'de>,
1105 {
1106 Err(de::Error::invalid_type(
1107 de::Unexpected::UnitVariant,
1108 &"newtype variant",
1109 ))
1110 }
1111
tuple_variant<V>(self, _len: usize, _visitor: V) -> Result<V::Value> where V: de::Visitor<'de>,1112 fn tuple_variant<V>(self, _len: usize, _visitor: V) -> Result<V::Value>
1113 where
1114 V: de::Visitor<'de>,
1115 {
1116 Err(de::Error::invalid_type(
1117 de::Unexpected::UnitVariant,
1118 &"tuple variant",
1119 ))
1120 }
1121
struct_variant<V>(self, _fields: &'static [&'static str], _visitor: V) -> Result<V::Value> where V: de::Visitor<'de>,1122 fn struct_variant<V>(self, _fields: &'static [&'static str], _visitor: V) -> Result<V::Value>
1123 where
1124 V: de::Visitor<'de>,
1125 {
1126 Err(de::Error::invalid_type(
1127 de::Unexpected::UnitVariant,
1128 &"struct variant",
1129 ))
1130 }
1131 }
1132
1133 struct VariantAccess<T> {
1134 seq: T,
1135 }
1136
1137 impl<'de, T> de::EnumAccess<'de> for VariantAccess<T>
1138 where
1139 T: de::SeqAccess<'de, Error = Error> + MakeError,
1140 {
1141 type Error = Error;
1142 type Variant = VariantAccess<T>;
1143
variant_seed<V>(mut self, seed: V) -> Result<(V::Value, VariantAccess<T>)> where V: de::DeserializeSeed<'de>,1144 fn variant_seed<V>(mut self, seed: V) -> Result<(V::Value, VariantAccess<T>)>
1145 where
1146 V: de::DeserializeSeed<'de>,
1147 {
1148 let variant = match self.seq.next_element_seed(seed) {
1149 Ok(Some(variant)) => variant,
1150 Ok(None) => return Err(self.seq.error(ErrorCode::ArrayTooShort)),
1151 Err(e) => return Err(e),
1152 };
1153 Ok((variant, self))
1154 }
1155 }
1156
1157 impl<'de, T> de::VariantAccess<'de> for VariantAccess<T>
1158 where
1159 T: de::SeqAccess<'de, Error = Error> + MakeError,
1160 {
1161 type Error = Error;
1162
unit_variant(mut self) -> Result<()>1163 fn unit_variant(mut self) -> Result<()> {
1164 match self.seq.next_element() {
1165 Ok(Some(())) => Ok(()),
1166 Ok(None) => Err(self.seq.error(ErrorCode::ArrayTooLong)),
1167 Err(e) => Err(e),
1168 }
1169 }
1170
newtype_variant_seed<S>(mut self, seed: S) -> Result<S::Value> where S: de::DeserializeSeed<'de>,1171 fn newtype_variant_seed<S>(mut self, seed: S) -> Result<S::Value>
1172 where
1173 S: de::DeserializeSeed<'de>,
1174 {
1175 match self.seq.next_element_seed(seed) {
1176 Ok(Some(variant)) => Ok(variant),
1177 Ok(None) => Err(self.seq.error(ErrorCode::ArrayTooShort)),
1178 Err(e) => Err(e),
1179 }
1180 }
1181
tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>,1182 fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value>
1183 where
1184 V: de::Visitor<'de>,
1185 {
1186 visitor.visit_seq(self.seq)
1187 }
1188
struct_variant<V>(mut self, _fields: &'static [&'static str], visitor: V) -> Result<V::Value> where V: de::Visitor<'de>,1189 fn struct_variant<V>(mut self, _fields: &'static [&'static str], visitor: V) -> Result<V::Value>
1190 where
1191 V: de::Visitor<'de>,
1192 {
1193 let seed = StructVariantSeed { visitor };
1194 match self.seq.next_element_seed(seed) {
1195 Ok(Some(variant)) => Ok(variant),
1196 Ok(None) => Err(self.seq.error(ErrorCode::ArrayTooShort)),
1197 Err(e) => Err(e),
1198 }
1199 }
1200 }
1201
1202 struct StructVariantSeed<V> {
1203 visitor: V,
1204 }
1205
1206 impl<'de, V> de::DeserializeSeed<'de> for StructVariantSeed<V>
1207 where
1208 V: de::Visitor<'de>,
1209 {
1210 type Value = V::Value;
1211
deserialize<D>(self, de: D) -> result::Result<V::Value, D::Error> where D: de::Deserializer<'de>,1212 fn deserialize<D>(self, de: D) -> result::Result<V::Value, D::Error>
1213 where
1214 D: de::Deserializer<'de>,
1215 {
1216 de.deserialize_any(self.visitor)
1217 }
1218 }
1219
1220 /// Iterator that deserializes a stream into multiple CBOR values.
1221 ///
1222 /// A stream deserializer can be created from any CBOR deserializer using the
1223 /// `Deserializer::into_iter` method.
1224 ///
1225 /// ```
1226 /// # extern crate serde_cbor;
1227 /// use serde_cbor::de::Deserializer;
1228 /// use serde_cbor::value::Value;
1229 ///
1230 /// # fn main() {
1231 /// let data: Vec<u8> = vec![
1232 /// 0x01, 0x66, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72,
1233 /// ];
1234 /// let mut it = Deserializer::from_slice(&data[..]).into_iter::<Value>();
1235 /// assert_eq!(
1236 /// Value::Integer(1),
1237 /// it.next().unwrap().unwrap()
1238 /// );
1239 /// assert_eq!(
1240 /// Value::Text("foobar".to_string()),
1241 /// it.next().unwrap().unwrap()
1242 /// );
1243 /// # }
1244 /// ```
1245 #[derive(Debug)]
1246 pub struct StreamDeserializer<'de, R, T> {
1247 de: Deserializer<R>,
1248 output: PhantomData<T>,
1249 lifetime: PhantomData<&'de ()>,
1250 }
1251
1252 impl<'de, R, T> StreamDeserializer<'de, R, T>
1253 where
1254 R: Read<'de>,
1255 T: de::Deserialize<'de>,
1256 {
1257 /// Create a new CBOR stream deserializer from one of the possible
1258 /// serde_cbor input sources.
1259 ///
1260 /// Typically it is more convenient to use one of these methods instead:
1261 ///
1262 /// * `Deserializer::from_slice(...).into_iter()`
1263 /// * `Deserializer::from_reader(...).into_iter()`
new(read: R) -> StreamDeserializer<'de, R, T>1264 pub fn new(read: R) -> StreamDeserializer<'de, R, T> {
1265 StreamDeserializer {
1266 de: Deserializer::new(read),
1267 output: PhantomData,
1268 lifetime: PhantomData,
1269 }
1270 }
1271 }
1272
1273 impl<'de, R, T> StreamDeserializer<'de, R, T>
1274 where
1275 R: Offset,
1276 T: de::Deserialize<'de>,
1277 {
1278 /// Return the current offset in the reader
1279 #[inline]
byte_offset(&self) -> usize1280 pub fn byte_offset(&self) -> usize {
1281 self.de.byte_offset()
1282 }
1283 }
1284
1285 impl<'de, R, T> Iterator for StreamDeserializer<'de, R, T>
1286 where
1287 R: Read<'de>,
1288 T: de::Deserialize<'de>,
1289 {
1290 type Item = Result<T>;
1291
next(&mut self) -> Option<Result<T>>1292 fn next(&mut self) -> Option<Result<T>> {
1293 match self.de.peek() {
1294 Ok(Some(_)) => Some(T::deserialize(&mut self.de)),
1295 Ok(None) => None,
1296 Err(e) => Some(Err(e)),
1297 }
1298 }
1299 }
1300
1301 struct VariantAccessMap<T> {
1302 map: T,
1303 }
1304
1305 impl<'de, T> de::EnumAccess<'de> for VariantAccessMap<T>
1306 where
1307 T: de::MapAccess<'de, Error = Error> + MakeError,
1308 {
1309 type Error = Error;
1310 type Variant = VariantAccessMap<T>;
1311
variant_seed<V>(mut self, seed: V) -> Result<(V::Value, VariantAccessMap<T>)> where V: de::DeserializeSeed<'de>,1312 fn variant_seed<V>(mut self, seed: V) -> Result<(V::Value, VariantAccessMap<T>)>
1313 where
1314 V: de::DeserializeSeed<'de>,
1315 {
1316 let variant = match self.map.next_key_seed(seed) {
1317 Ok(Some(variant)) => variant,
1318 Ok(None) => return Err(self.map.error(ErrorCode::ArrayTooShort)),
1319 Err(e) => return Err(e),
1320 };
1321 Ok((variant, self))
1322 }
1323 }
1324
1325 impl<'de, T> de::VariantAccess<'de> for VariantAccessMap<T>
1326 where
1327 T: de::MapAccess<'de, Error = Error> + MakeError,
1328 {
1329 type Error = Error;
1330
unit_variant(mut self) -> Result<()>1331 fn unit_variant(mut self) -> Result<()> {
1332 match self.map.next_value() {
1333 Ok(()) => Ok(()),
1334 Err(e) => Err(e),
1335 }
1336 }
1337
newtype_variant_seed<S>(mut self, seed: S) -> Result<S::Value> where S: de::DeserializeSeed<'de>,1338 fn newtype_variant_seed<S>(mut self, seed: S) -> Result<S::Value>
1339 where
1340 S: de::DeserializeSeed<'de>,
1341 {
1342 self.map.next_value_seed(seed)
1343 }
1344
tuple_variant<V>(mut self, _len: usize, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>,1345 fn tuple_variant<V>(mut self, _len: usize, visitor: V) -> Result<V::Value>
1346 where
1347 V: de::Visitor<'de>,
1348 {
1349 let seed = StructVariantSeed { visitor };
1350 self.map.next_value_seed(seed)
1351 }
1352
struct_variant<V>(mut self, _fields: &'static [&'static str], visitor: V) -> Result<V::Value> where V: de::Visitor<'de>,1353 fn struct_variant<V>(mut self, _fields: &'static [&'static str], visitor: V) -> Result<V::Value>
1354 where
1355 V: de::Visitor<'de>,
1356 {
1357 let seed = StructVariantSeed { visitor };
1358 self.map.next_value_seed(seed)
1359 }
1360 }
1361