1 //! Parsing BER encoded values.
2 //!
3 //! This is an internal module. Its public types are re-exported by the
4 //! parent.
5 
6 use bytes::Bytes;
7 use smallvec::SmallVec;
8 use crate::captured::Captured;
9 use crate::int::{Integer, Unsigned};
10 use crate::length::Length;
11 use crate::mode::Mode;
12 use crate::tag::Tag;
13 use super::error::Error;
14 use super::source::{CaptureSource, LimitedSource, Source};
15 
16 
17 //------------ Content -------------------------------------------------------
18 
19 /// The content octets of a BER-encoded value.
20 ///
21 /// A value is either primitive, containing actual octets of an actual value,
22 /// or constructed, in which case its content contains additional BER encoded
23 /// values. This enum is useful for cases where a certain type may be encoded
24 /// as either a primitive value or a complex constructed value.
25 ///
26 /// Note that this type represents the content octets only, i.e., it does not
27 /// contain the tag of the value.
28 pub enum Content<'a, S: 'a> {
29     /// The value is a primitive value.
30     Primitive(Primitive<'a, S>),
31 
32     /// The value is a constructed value.
33     Constructed(Constructed<'a, S>)
34 }
35 
36 impl<'a, S: Source + 'a> Content<'a, S> {
37     /// Checkes that the content has been parsed completely.
38     ///
39     /// Returns a malformed error if not.
exhausted(self) -> Result<(), S::Err>40     fn exhausted(self) -> Result<(), S::Err> {
41         match self {
42             Content::Primitive(inner) => inner.exhausted(),
43             Content::Constructed(mut inner) => inner.exhausted()
44         }
45     }
46 
47     /// Returns the encoding mode used by the value.
mode(&self) -> Mode48     pub fn mode(&self) -> Mode {
49         match *self {
50             Content::Primitive(ref inner) => inner.mode(),
51             Content::Constructed(ref inner) => inner.mode()
52         }
53     }
54 
55     /// Returns whether this value is a primitive value.
is_primitive(&self) -> bool56     pub fn is_primitive(&self) -> bool {
57         match *self {
58             Content::Primitive(_) => true,
59             Content::Constructed(_) => false,
60         }
61     }
62 
63     /// Returns whether this value is a constructed value.
is_constructed(&self) -> bool64     pub fn is_constructed(&self) -> bool {
65         match *self {
66             Content::Primitive(_) => false,
67             Content::Constructed(_) => true,
68         }
69     }
70 
71     /// Converts a reference into into one to a primitive value or errors out.
as_primitive(&mut self) -> Result<&mut Primitive<'a, S>, S::Err>72     pub fn as_primitive(&mut self) -> Result<&mut Primitive<'a, S>, S::Err> {
73         match *self {
74             Content::Primitive(ref mut inner) => Ok(inner),
75             Content::Constructed(_) => {
76                 xerr!(Err(Error::Malformed.into()))
77             }
78         }
79     }
80 
81     /// Converts a reference into on to a constructed value or errors out.
as_constructed( &mut self ) -> Result<&mut Constructed<'a, S>, S::Err>82     pub fn as_constructed(
83         &mut self
84     ) -> Result<&mut Constructed<'a, S>, S::Err> {
85         match *self {
86             Content::Primitive(_) => {
87                 xerr!(Err(Error::Malformed.into()))
88             }
89             Content::Constructed(ref mut inner) => Ok(inner),
90         }
91     }
92 }
93 
94 #[allow(clippy::wrong_self_convention)]
95 impl<'a, S: Source + 'a> Content<'a, S> {
96     /// Converts content into a `u8`.
97     ///
98     /// If the content is not primitive or does not contain a single BER
99     /// encoded INTEGER value between 0 and 256, returns a malformed error.
to_u8(&mut self) -> Result<u8, S::Err>100     pub fn to_u8(&mut self) -> Result<u8, S::Err> {
101         if let Content::Primitive(ref mut prim) = *self {
102             prim.to_u8()
103         }
104         else {
105             xerr!(Err(Error::Malformed.into()))
106         }
107     }
108 
109     /// Skips over the content if it contains an INTEGER of value `expected`.
110     ///
111     /// The content needs to be primitive and contain a validly encoded
112     /// integer of value `expected` or else a malformed error will be
113     /// returned.
skip_u8_if(&mut self, expected: u8) -> Result<(), S::Err>114     pub fn skip_u8_if(&mut self, expected: u8) -> Result<(), S::Err> {
115         let res = self.to_u8()?;
116         if res == expected {
117             Ok(())
118         }
119         else {
120             xerr!(Err(Error::Malformed.into()))
121         }
122     }
123 
124     /// Converts content into a `u16`.
125     ///
126     /// If the content is not primitive or does not contain a single BER
127     /// encoded INTEGER value between 0 and 2^16-1, returns a malformed error.
to_u16(&mut self) -> Result<u16, S::Err>128     pub fn to_u16(&mut self) -> Result<u16, S::Err> {
129         if let Content::Primitive(ref mut prim) = *self {
130             prim.to_u16()
131         }
132         else {
133             xerr!(Err(Error::Malformed.into()))
134         }
135     }
136 
137     /// Converts content into a `u32`.
138     ///
139     /// If the content is not primitive or does not contain a single BER
140     /// encoded INTEGER value between 0 and 2^32-1, returns a malformed error.
to_u32(&mut self) -> Result<u32, S::Err>141     pub fn to_u32(&mut self) -> Result<u32, S::Err> {
142         if let Content::Primitive(ref mut prim) = *self {
143             prim.to_u32()
144         }
145         else {
146             xerr!(Err(Error::Malformed.into()))
147         }
148     }
149 
150     /// Converts content into a `u64`.
151     ///
152     /// If the content is not primitive or does not contain a single BER
153     /// encoded INTEGER value between 0 and 2^64-1, returns a malformed error.
to_u64(&mut self) -> Result<u64, S::Err>154     pub fn to_u64(&mut self) -> Result<u64, S::Err> {
155         if let Content::Primitive(ref mut prim) = *self {
156             prim.to_u64()
157         }
158         else {
159             xerr!(Err(Error::Malformed.into()))
160         }
161     }
162 
163     /// Converts the content into a NULL value.
164     ///
165     /// If the content isn’t primitive and contains a single BER encoded
166     /// NULL value (i.e., nothing), returns a malformed error.
to_null(&mut self) -> Result<(), S::Err>167     pub fn to_null(&mut self) -> Result<(), S::Err> {
168         if let Content::Primitive(ref mut prim) = *self {
169             prim.to_null()
170         }
171         else {
172             xerr!(Err(Error::Malformed.into()))
173         }
174     }
175 }
176 
177 
178 //------------ Primitive -----------------------------------------------------
179 
180 /// The content octets of a primitive value.
181 ///
182 /// You will receive a reference to a value of this type through a closure,
183 /// possibly wrapped in a `Content` value. Your task will be to read out all
184 /// the octets of the value before returning from the closure or produce an
185 /// error if the value isn’t correctly encoded. If you read less octets than
186 /// are available, whoever called the closure will produce an error after
187 /// you returned. Thus, you can read as many octets as you expect and not
188 /// bother to check whether that was all available octets.
189 ///
190 /// The most basic way to do this is through the primitive’s implementation
191 /// of the `Source` trait. Thus, you can gain access to some or all of the
192 /// octets and mark them read by advancing over them. You can safely attempt
193 /// to read more octets than available as that will reliably result in a
194 /// malformed error.
195 ///
196 /// A number of methods are available to deal with the encodings defined for
197 /// various types. These are prefixed by `to_` to indicate that they are
198 /// intended to convert the content to a certain type. They all read exactly
199 /// one encoded value.
200 ///
201 /// The value provides access to the decoding mode via the `mode` method.
202 /// All methodes that decode data will honour the decoding mode and enforce
203 /// that data is encoded according to the mode.
204 pub struct Primitive<'a, S: 'a> {
205     /// The underlying source limited to the length of the value.
206     source: &'a mut LimitedSource<S>,
207 
208     /// The decoding mode to operate in.
209     mode: Mode,
210 }
211 
212 /// # Value Management
213 ///
214 impl<'a, S: 'a> Primitive<'a, S> {
215     /// Creates a new primitive from the given source and mode.
new(source: &'a mut LimitedSource<S>, mode: Mode) -> Self216     fn new(source: &'a mut LimitedSource<S>, mode: Mode) -> Self {
217         Primitive { source, mode }
218     }
219 
220     /// Returns the current decoding mode.
221     ///
222     /// The higher-level `to_` methods will use this mode to enforce that
223     /// data is encoded correctly.
mode(&self) -> Mode224     pub fn mode(&self) -> Mode {
225         self.mode
226     }
227 
228     /// Sets the current decoding mode.
set_mode(&mut self, mode: Mode)229     pub fn set_mode(&mut self, mode: Mode) {
230         self.mode = mode
231     }
232 }
233 
234 
235 /// # High-level Decoding
236 ///
237 #[allow(clippy::wrong_self_convention)]
238 impl<'a, S: Source + 'a> Primitive<'a, S> {
239     /// Parses the primitive value as a BOOLEAN value.
to_bool(&mut self) -> Result<bool, S::Err>240     pub fn to_bool(&mut self) -> Result<bool, S::Err> {
241         let res = self.take_u8()?;
242         if self.mode != Mode::Ber {
243             match res {
244                 0 => Ok(false),
245                 0xFF => Ok(true),
246                 _ => {
247                     xerr!(Err(Error::Malformed.into()))
248                 }
249             }
250         }
251         else {
252             Ok(res != 0)
253         }
254     }
255 
256     /// Parses the primitive value as an INTEGER limited to a `i8`.
to_i8(&mut self) -> Result<i8, S::Err>257     pub fn to_i8(&mut self) -> Result<i8, S::Err> {
258         Integer::i8_from_primitive(self)
259     }
260 
261     /// Parses the primitive value as an INTEGER limited to a `i8`.
to_i16(&mut self) -> Result<i16, S::Err>262     pub fn to_i16(&mut self) -> Result<i16, S::Err> {
263         Integer::i16_from_primitive(self)
264     }
265 
266     /// Parses the primitive value as an INTEGER limited to a `i8`.
to_i32(&mut self) -> Result<i32, S::Err>267     pub fn to_i32(&mut self) -> Result<i32, S::Err> {
268         Integer::i32_from_primitive(self)
269     }
270 
271     /// Parses the primitive value as an INTEGER limited to a `i8`.
to_i64(&mut self) -> Result<i64, S::Err>272     pub fn to_i64(&mut self) -> Result<i64, S::Err> {
273         Integer::i64_from_primitive(self)
274     }
275 
276     /// Parses the primitive value as an INTEGER limited to a `i8`.
to_i128(&mut self) -> Result<i128, S::Err>277     pub fn to_i128(&mut self) -> Result<i128, S::Err> {
278         Integer::i128_from_primitive(self)
279     }
280 
281     /// Parses the primitive value as an INTEGER limited to a `u8`.
to_u8(&mut self) -> Result<u8, S::Err>282     pub fn to_u8(&mut self) -> Result<u8, S::Err> {
283         Unsigned::u8_from_primitive(self)
284     }
285 
286     /// Parses the primitive value as an INTEGER limited to a `u16`.
to_u16(&mut self) -> Result<u16, S::Err>287     pub fn to_u16(&mut self) -> Result<u16, S::Err> {
288         Unsigned::u16_from_primitive(self)
289     }
290 
291     /// Parses the primitive value as an INTEGER limited to a `u32`.
to_u32(&mut self) -> Result<u32, S::Err>292     pub fn to_u32(&mut self) -> Result<u32, S::Err> {
293         Unsigned::u32_from_primitive(self)
294     }
295 
296     /// Parses the primitive value as a INTEGER value limited to a `u64`.
to_u64(&mut self) -> Result<u64, S::Err>297     pub fn to_u64(&mut self) -> Result<u64, S::Err> {
298         Unsigned::u64_from_primitive(self)
299     }
300 
301     /// Parses the primitive value as a INTEGER value limited to a `u128`.
to_u128(&mut self) -> Result<u64, S::Err>302     pub fn to_u128(&mut self) -> Result<u64, S::Err> {
303         Unsigned::u64_from_primitive(self)
304     }
305 
306     /// Converts the content octets to a NULL value.
307     ///
308     /// Since such a value is empty, this doesn’t really do anything.
to_null(&mut self) -> Result<(), S::Err>309     pub fn to_null(&mut self) -> Result<(), S::Err> {
310         // The rest is taken care of by the exhausted check later ...
311         Ok(())
312     }
313 }
314 
315 /// # Low-level Access
316 ///
317 /// For basic low-level access, `Primitive` implements the `Source` trait.
318 /// Because the length of the content is guaranteed to be known, it can
319 /// provide a few additional methods. Note that these may still fail because
320 /// the underlying source doesn’t guarantee that as many octets are actually
321 /// available.
322 impl<'a, S: Source + 'a> Primitive<'a, S> {
323     /// Returns the number of remaining octets.
324     ///
325     /// The returned value reflects what is left of the content and therefore
326     /// decreases when the primitive is advanced.
remaining(&self) -> usize327     pub fn remaining(&self) -> usize {
328         self.source.limit().unwrap()
329     }
330 
331     /// Skips the rest of the content.
skip_all(&mut self) -> Result<(), S::Err>332     pub fn skip_all(&mut self) -> Result<(), S::Err> {
333         self.source.skip_all()
334     }
335 
336     /// Returns the remainder of the content as a `Bytes` value.
take_all(&mut self) -> Result<Bytes, S::Err>337     pub fn take_all(&mut self) -> Result<Bytes, S::Err> {
338         self.source.take_all()
339     }
340 
341     /// Returns a bytes slice of the remainder of the content.
slice_all(&mut self) -> Result<&[u8], S::Err>342     pub fn slice_all(&mut self) -> Result<&[u8], S::Err> {
343         let remaining = self.remaining();
344         self.source.request(remaining)?;
345         Ok(&self.source.slice()[..remaining])
346     }
347 
348     /// Checkes whether all content has been advanced over.
exhausted(self) -> Result<(), S::Err>349     fn exhausted(self) -> Result<(), S::Err> {
350         self.source.exhausted()
351     }
352 }
353 
354 
355 /// # Support for Testing
356 ///
357 impl<'a> Primitive<'a, &'a [u8]> {
358     /// Decode a bytes slice via a closure.
359     ///
360     /// This method can be used in testing code for decoding primitive
361     /// values by providing a bytes slice with the content. For instance,
362     /// decoding the `to_bool` method could be tested like this:
363     ///
364     /// ```
365     /// use bcder::Mode;
366     /// use bcder::decode::Primitive;
367     ///
368     /// assert_eq!(
369     ///     Primitive::decode_slice(
370     ///         b"\x00".as_ref(), Mode::Der,
371     ///         |prim| prim.to_bool()
372     ///     ).unwrap(),
373     ///     false
374     /// )
375     /// ```
decode_slice<F, T>( source: &'a [u8], mode: Mode, op: F ) -> Result<T, Error> where F: FnOnce(&mut Primitive<&[u8]>) -> Result<T, Error>376     pub fn decode_slice<F, T>(
377         source: &'a [u8],
378         mode: Mode,
379         op: F
380     ) -> Result<T, Error>
381     where F: FnOnce(&mut Primitive<&[u8]>) -> Result<T, Error> {
382         let mut lim = LimitedSource::new(source);
383         lim.set_limit(Some(source.len()));
384         let mut prim = Primitive::new(&mut lim, mode);
385         let res = op(&mut prim)?;
386         prim.exhausted()?;
387         Ok(res)
388     }
389 }
390 
391 
392 //--- Source
393 
394 impl<'a, S: Source + 'a> Source for Primitive<'a, S> {
395     type Err = S::Err;
396 
request(&mut self, len: usize) -> Result<usize, Self::Err>397     fn request(&mut self, len: usize) -> Result<usize, Self::Err> {
398         self.source.request(len)
399     }
400 
advance(&mut self, len: usize) -> Result<(), Self::Err>401     fn advance(&mut self, len: usize) -> Result<(), Self::Err> {
402         self.source.advance(len)
403     }
404 
slice(&self) -> &[u8]405     fn slice(&self) -> &[u8] {
406         self.source.slice()
407     }
408 
bytes(&self, start: usize, end: usize) -> Bytes409     fn bytes(&self, start: usize, end: usize) -> Bytes {
410         self.source.bytes(start, end)
411     }
412 }
413 
414 
415 //------------ Constructed ---------------------------------------------------
416 
417 /// The content octets of a constructed value.
418 ///
419 /// You will only ever receive a mutable reference to a value of this type
420 /// as an argument to a closure provided to some function. The closure will
421 /// have to process all content of the constructed value.
422 ///
423 /// Since constructed values consist of a sequence of values, the methods
424 /// allow you to process these values one by one. The most basic of these
425 /// are [`take_value`] and [`take_opt_value`] which process exactly one
426 /// value or up to one value. A number of convenience functions exists on
427 /// top of them for commonly encountered types and cases.
428 ///
429 /// Because the caller of your closure checks whether all content has been
430 /// advanced over and raising an error of not, you only need to read as many
431 /// values as you expected to be present and can simply return when you think
432 /// you are done.
433 ///
434 /// [`take_value`]: #method.take_value
435 /// [`take_opt_value`]: #method.take_opt_value
436 #[derive(Debug)]
437 pub struct Constructed<'a, S: 'a> {
438     /// The underlying source.
439     source: &'a mut LimitedSource<S>,
440 
441     /// The state we are in so we can determine the end of the content.
442     state: State,
443 
444     /// The encoding mode to use.
445     mode: Mode,
446 }
447 
448 /// # General Management
449 ///
450 impl<'a, S: Source + 'a> Constructed<'a, S> {
451     /// Creates a new source from the given components.
new( source: &'a mut LimitedSource<S>, state: State, mode: Mode ) -> Self452     fn new(
453         source: &'a mut LimitedSource<S>,
454         state: State,
455         mode: Mode
456     ) -> Self {
457         Constructed { source, state, mode }
458     }
459 
460     /// Decode a source as a constructed content.
461     ///
462     /// The function will start decoding of `source` in the given mode. It
463     /// will pass a constructed content value to the closure `op` which
464     /// has to process all the content and return a result or error.
465     ///
466     /// This function is identical to calling [`Mode::decode`].
467     ///
468     /// [`Mode::decode`]: ../enum.Mode.html#method.decode
decode<F, T>(source: S, mode: Mode, op: F) -> Result<T, S::Err> where F: FnOnce(&mut Constructed<S>) -> Result<T, S::Err>469     pub fn decode<F, T>(source: S, mode: Mode, op: F) -> Result<T, S::Err>
470     where F: FnOnce(&mut Constructed<S>) -> Result<T, S::Err> {
471         let mut source = LimitedSource::new(source);
472         let mut cons = Constructed::new(&mut source, State::Unbounded, mode);
473         let res = op(&mut cons)?;
474         cons.exhausted()?;
475         Ok(res)
476     }
477 
478     /// Returns the encoding mode used by the value.
mode(&self) -> Mode479     pub fn mode(&self) -> Mode {
480         self.mode
481     }
482 
483     /// Sets the encoding mode to be used for the value.
set_mode(&mut self, mode: Mode)484     pub fn set_mode(&mut self, mode: Mode) {
485         self.mode = mode
486     }
487 }
488 
489 /// # Fundamental Reading
490 ///
491 impl<'a, S: Source + 'a> Constructed<'a, S> {
492     /// Checks whether all content has been advanced over.
493     ///
494     /// For a value of definite length, this is the case when the limit of the
495     /// source has been reached. For indefinite values, we need to have either
496     /// already read or can now read the end-of-value marker.
exhausted(&mut self) -> Result<(), S::Err>497     fn exhausted(&mut self) -> Result<(), S::Err> {
498         match self.state {
499             State::Done => Ok(()),
500             State::Definite => {
501                 self.source.exhausted()
502             }
503             State::Indefinite => {
504                 let (tag, constructed) = Tag::take_from(self.source)?;
505                 if tag != Tag::END_OF_VALUE || constructed
506                     || !Length::take_from(self.source, self.mode)?.is_zero()
507                 {
508                     xerr!(Err(Error::Malformed.into()))
509                 }
510                 else {
511                     Ok(())
512                 }
513             }
514             State::Unbounded => Ok(())
515         }
516     }
517 
518     /// Returns whether we have already reached the end.
519     ///
520     /// For indefinite values, we may be at the end right now but don’t
521     /// know it yet.
is_exhausted(&self) -> bool522     fn is_exhausted(&self) -> bool {
523         match self.state {
524             State::Definite => {
525                 self.source.limit().unwrap() == 0
526             }
527             State::Indefinite => false,
528             State::Done => true,
529             State::Unbounded => false,
530         }
531     }
532 
533     /// Processes the next value.
534     ///
535     /// If `expected` is not `None`, the method will only process a value
536     /// with the given tag and return `Ok(None)` if there isn’t another value
537     /// or if the next value has a different tag.
538     ///
539     /// If `expected` is `None`, the method will process a value with any
540     /// tag and only return `Ok(None)` if it reached the end of the value.
541     ///
542     /// The closure `op` receives both the tag and content for the next
543     /// value. It must process the value, advancing the source to its end
544     /// or return an error.
process_next_value<F, T>( &mut self, expected: Option<Tag>, op: F ) -> Result<Option<T>, S::Err> where F: FnOnce(Tag, &mut Content<S>) -> Result<T, S::Err>545     fn process_next_value<F, T>(
546         &mut self,
547         expected: Option<Tag>,
548         op: F
549     ) -> Result<Option<T>, S::Err>
550     where F: FnOnce(Tag, &mut Content<S>) -> Result<T, S::Err> {
551         if self.is_exhausted() {
552             return Ok(None)
553         }
554         let (tag, constructed) = if let Some(expected) = expected {
555             (
556                 expected,
557                 match expected.take_from_if(self.source)? {
558                     Some(compressed) => compressed,
559                     None => return Ok(None)
560                 }
561             )
562         }
563         else {
564             Tag::take_from(self.source)?
565         };
566         let length = Length::take_from(self.source, self.mode)?;
567 
568         if tag == Tag::END_OF_VALUE {
569             if let State::Indefinite = self.state {
570                 if constructed {
571                     xerr!(return Err(Error::Malformed.into()))
572                 }
573                 if !length.is_zero() {
574                     xerr!(return Err(Error::Malformed.into()))
575                 }
576                 self.state = State::Done;
577                 return Ok(None)
578             }
579             else {
580                 xerr!(return Err(Error::Malformed.into()))
581             }
582         }
583 
584         match length {
585             Length::Definite(len) => {
586                 let old_limit = self.source.limit_further(Some(len));
587                 let res = {
588                     let mut content = if constructed {
589                         // Definite length constructed values are not allowed
590                         // in CER.
591                         if self.mode == Mode::Cer {
592                             xerr!(return Err(Error::Malformed.into()))
593                         }
594                         Content::Constructed(
595                             Constructed::new(
596                                 self.source, State::Definite, self.mode
597                             )
598                         )
599                     }
600                     else {
601                         Content::Primitive(
602                             Primitive::new(self.source, self.mode)
603                         )
604                     };
605                     let res = op(tag, &mut content)?;
606                     content.exhausted()?;
607                     res
608                 };
609                 self.source.set_limit(old_limit.map(|x| x - len));
610                 Ok(Some(res))
611             }
612             Length::Indefinite => {
613                 if !constructed || self.mode == Mode::Der {
614                     xerr!(return Err(Error::Malformed.into()))
615                 }
616                 let mut content = Content::Constructed(
617                     Constructed::new(self.source, State::Indefinite, self.mode)
618                 );
619                 let res = op(tag, &mut content)?;
620                 content.exhausted()?;
621                 Ok(Some(res))
622             }
623         }
624     }
625 }
626 
627 /// # Processing Contained Values
628 ///
629 /// The methods in this section each process one value of the constructed
630 /// value’s content.
631 impl<'a, S: Source + 'a> Constructed<'a, S> {
632     /// Process one value of content.
633     ///
634     /// The closure `op` receives the tag and content of the next value
635     /// and must process it completely, advancing to the content’s end.
636     ///
637     /// Upon success, the method returns the closure’s return value. The
638     /// method returns a malformed error if there isn’t at least one more
639     /// value available. It also returns an error if the closure returns one
640     /// or if reading from the source fails.
take_value<F, T>(&mut self, op: F) -> Result<T, S::Err> where F: FnOnce(Tag, &mut Content<S>) -> Result<T, S::Err>641     pub fn take_value<F, T>(&mut self, op: F) -> Result<T, S::Err>
642     where F: FnOnce(Tag, &mut Content<S>) -> Result<T, S::Err> {
643         match self.process_next_value(None, op)? {
644             Some(res) => Ok(res),
645             None => {
646                 xerr!(Err(Error::Malformed.into()))
647             }
648         }
649     }
650 
651     /// Processes an optional value.
652     ///
653     /// If there is at least one more value available, the closure `op` is
654     /// given the tag and content of that value and must process it
655     /// completely, advancing to the end of its content. If the closure
656     /// succeeds, its return value is returned as ‘some’ result.
657     ///
658     /// If there are no more values available, the method returns `Ok(None)`.
659     /// It returns an error if the closure returns one or if reading from
660     /// the source fails.
take_opt_value<F, T>(&mut self, op: F) -> Result<Option<T>, S::Err> where F: FnOnce(Tag, &mut Content<S>) -> Result<T, S::Err>661     pub fn take_opt_value<F, T>(&mut self, op: F) -> Result<Option<T>, S::Err>
662     where F: FnOnce(Tag, &mut Content<S>) -> Result<T, S::Err> {
663         self.process_next_value(None, op)
664     }
665 
666     /// Processes a value with the given tag.
667     ///
668     /// If the next value has the tag `expected`, its content is being given
669     /// to the closure which has to process it completely and return whatever
670     /// is being returned upon success.
671     ///
672     /// The method will return a malformed error if it encounters any other
673     /// tag or the end of the value. It will also return an error if the
674     /// closure returns an error or doesn’t process the complete values, or
675     /// if accessing the underlying source fails.
take_value_if<F, T>( &mut self, expected: Tag, op: F ) -> Result<T, S::Err> where F: FnOnce(&mut Content<S>) -> Result<T, S::Err>676     pub fn take_value_if<F, T>(
677         &mut self,
678         expected: Tag,
679         op: F
680     ) -> Result<T, S::Err>
681     where F: FnOnce(&mut Content<S>) -> Result<T, S::Err> {
682         let res = self.process_next_value(Some(expected), |_, content| {
683             op(content)
684         })?;
685         match res {
686             Some(res) => Ok(res),
687             None => {
688                 xerr!(Err(Error::Malformed.into()))
689             }
690         }
691     }
692 
693     /// Processes an optional value with the given tag.
694     ///
695     /// If the next value has the tag `expected`, its content is being given
696     /// to the closure which has to process it completely and return whatever
697     /// is to be returned as some value.
698     ///
699     /// If the next value has a different tag or if the end of the value has
700     /// been reached, the method returns `Ok(None)`. It will return an error
701     /// if the closure fails or doesn’t process the complete value, or if
702     /// accessing the underlying source fails.
take_opt_value_if<F, T>( &mut self, expected: Tag, op: F ) -> Result<Option<T>, S::Err> where F: FnOnce(&mut Content<S>) -> Result<T, S::Err>703     pub fn take_opt_value_if<F, T>(
704         &mut self,
705         expected: Tag,
706         op: F
707     ) -> Result<Option<T>, S::Err>
708     where F: FnOnce(&mut Content<S>) -> Result<T, S::Err> {
709         self.process_next_value(Some(expected), |_, content| op(content))
710     }
711 
712     /// Process a constructed value.
713     ///
714     /// If the next value is a constructed value, its tag and content are
715     /// being given to the closure `op` which has to process it completely.
716     /// If it succeeds, its return value is returned.
717     ///
718     /// If the next value is not a constructed value or there is no next
719     /// value or if the closure doesn’t process the next value completely,
720     /// a malformed error is returned. An error is also returned if the
721     /// closure returns one or if accessing the underlying source fails.
take_constructed<F, T>(&mut self, op: F) -> Result<T, S::Err> where F: FnOnce(Tag, &mut Constructed<S>) -> Result<T, S::Err>722     pub fn take_constructed<F, T>(&mut self, op: F) -> Result<T, S::Err>
723     where F: FnOnce(Tag, &mut Constructed<S>) -> Result<T, S::Err> {
724         match self.take_opt_constructed(op)? {
725             Some(res) => Ok(res),
726             None => {
727                 xerr!(Err(Error::Malformed.into()))
728             }
729         }
730     }
731 
732     /// Processes an optional constructed value.
733     ///
734     /// If the next value is a constructed value, its tag and content are
735     /// being given to the closure `op` which has to process it completely.
736     /// If it succeeds, its return value is returned as some value.
737     ///
738     /// If the end of the value has been reached, the method returns
739     /// `Ok(None)`.
740     ///
741     /// If the next value is not a constructed value or if the closure
742     /// doesn’t process the next value completely, a malformed error is
743     /// returned. An error is also returned if the closure returns one or
744     /// if accessing the underlying source fails.
take_opt_constructed<F, T>( &mut self, op: F ) -> Result<Option<T>, S::Err> where F: FnOnce(Tag, &mut Constructed<S>) -> Result<T, S::Err>745     pub fn take_opt_constructed<F, T>(
746         &mut self,
747         op: F
748     ) -> Result<Option<T>, S::Err>
749     where F: FnOnce(Tag, &mut Constructed<S>) -> Result<T, S::Err> {
750         self.process_next_value(None, |tag, content| {
751             op(tag, content.as_constructed()?)
752         })
753     }
754 
755     /// Processes a constructed value with a required tag.
756     ///
757     /// If the next value is a constructed value with a tag equal to
758     /// `expected`, its content is given to the closure `op` which has to
759     /// process it completely. If the closure succeeds, its return value
760     /// is returned.
761     ///
762     /// If the next value is not constructed or has a different tag, if
763     /// the end of the value has been reached, or if the closure does not
764     /// process the contained value’s content completely, a malformed error
765     /// is returned. An error is also returned if the closure returns one or
766     /// if accessing the underlying source fails.
take_constructed_if<F, T>( &mut self, expected: Tag, op: F ) -> Result<T, S::Err> where F: FnOnce(&mut Constructed<S>) -> Result<T, S::Err>767     pub fn take_constructed_if<F, T>(
768         &mut self,
769         expected: Tag,
770         op: F
771     ) -> Result<T, S::Err>
772     where F: FnOnce(&mut Constructed<S>) -> Result<T, S::Err> {
773         match self.take_opt_constructed_if(expected, op)? {
774             Some(res) => Ok(res),
775             None => {
776                 xerr!(Err(Error::Malformed.into()))
777             }
778         }
779     }
780 
781     /// Processes an optional constructed value if it has a given tag.
782     ///
783     /// If the next value is a constructed value with a tag equal to
784     /// `expected`, its content is given to the closure `op` which has to
785     /// process it completely. If the closure succeeds, its return value
786     /// is returned.
787     ///
788     /// If the next value is not constructed, does not have the expected tag,
789     /// or the end of this value has been reached, the method returns
790     /// `Ok(None)`. It returns a malformed error if the closure does not
791     /// process the content of the next value fully.
792     ///
793     /// An error is also returned if the closure returns one or if accessing
794     /// the underlying source fails.
take_opt_constructed_if<F, T>( &mut self, expected: Tag, op: F ) -> Result<Option<T>, S::Err> where F: FnOnce(&mut Constructed<S>) -> Result<T, S::Err>795     pub fn take_opt_constructed_if<F, T>(
796         &mut self,
797         expected: Tag,
798         op: F
799     ) -> Result<Option<T>, S::Err>
800     where F: FnOnce(&mut Constructed<S>) -> Result<T, S::Err> {
801         self.process_next_value(Some(expected), |_, content| {
802             op(content.as_constructed()?)
803         })
804     }
805 
806     /// Processes a primitive value.
807     ///
808     /// If the next value is primitive, its tag and content are given to the
809     /// closure `op` which has to process it fully. Upon success, the
810     /// closure’s return value is returned.
811     ///
812     /// If the next value is not primitive, if the end of value has been
813     /// reached, or if the closure fails to process the next value’s content
814     /// fully, a malformed error is returned. An error is also returned if
815     /// the closure returns one or if accessing the underlying source fails.
take_primitive<F, T>(&mut self, op: F) -> Result<T, S::Err> where F: FnOnce(Tag, &mut Primitive<S>) -> Result<T, S::Err>816     pub fn take_primitive<F, T>(&mut self, op: F) -> Result<T, S::Err>
817     where F: FnOnce(Tag, &mut Primitive<S>) -> Result<T, S::Err> {
818         match self.take_opt_primitive(op)? {
819             Some(res) => Ok(res),
820             None => {
821                 xerr!(Err(Error::Malformed.into()))
822             }
823         }
824     }
825 
826     /// Processes an optional primitive value.
827     ///
828     /// If the next value is primitive, its tag and content are given to the
829     /// closure `op` which has to process it fully. Upon success, the
830     /// closure’s return value is returned.
831     ///
832     /// If the next value is not primitive or if the end of value has been
833     /// reached, `Ok(None)` is returned.
834     /// If the closure fails to process the next value’s content fully, a
835     /// malformed error is returned. An error is also returned if
836     /// the closure returns one or if accessing the underlying source fails.
take_opt_primitive<F, T>( &mut self, op: F ) -> Result<Option<T>, S::Err> where F: FnOnce(Tag, &mut Primitive<S>) -> Result<T, S::Err>837     pub fn take_opt_primitive<F, T>(
838         &mut self,
839         op: F
840     ) -> Result<Option<T>, S::Err>
841     where F: FnOnce(Tag, &mut Primitive<S>) -> Result<T, S::Err> {
842         self.process_next_value(None, |tag, content| {
843             op(tag, content.as_primitive()?)
844         })
845     }
846 
847     /// Processes a primitive value if it has the right tag.
848     ///
849     /// If the next value is a primitive and its tag matches `expected`, its
850     /// content is given to the closure `op` which has to process it
851     /// completely or return an error, either of which is returned.
852     ///
853     /// The method returns a malformed error if there is no next value, if the
854     /// next value is not a primitive, if it doesn’t have the right tag, or if
855     /// the closure doesn’t advance over the complete content. If access to
856     /// the underlying source fails, an error is returned, too.
take_primitive_if<F, T>( &mut self, expected: Tag, op: F ) -> Result<T, S::Err> where F: FnOnce(&mut Primitive<S>) -> Result<T, S::Err>857     pub fn take_primitive_if<F, T>(
858         &mut self,
859         expected: Tag,
860         op: F
861     ) -> Result<T, S::Err>
862     where F: FnOnce(&mut Primitive<S>) -> Result<T, S::Err> {
863         match self.take_opt_primitive_if(expected, op)? {
864             Some(res) => Ok(res),
865             None => {
866                 xerr!(Err(Error::Malformed.into()))
867             }
868         }
869     }
870 
871     /// Processes an optional primitive value of a given tag.
872     ///
873     /// If the next value is a primitive and its tag matches `expected`, its
874     /// content is given to the closure `op` which has to process it
875     /// completely or return an error, either of which is returned.
876     ///
877     /// If the end of this value has been reached, if the next value is not
878     /// a primitive or if its tag doesn’t match, the method returns
879     /// `Ok(None)`. If the closure doesn’t process the next value’s content
880     /// fully the method returns a malformed error. If access to the
881     /// underlying source fails, it returns an appropriate error.
take_opt_primitive_if<F, T>( &mut self, expected: Tag, op: F ) -> Result<Option<T>, S::Err> where F: FnOnce(&mut Primitive<S>) -> Result<T, S::Err>882     pub fn take_opt_primitive_if<F, T>(
883         &mut self,
884         expected: Tag,
885         op: F
886     ) -> Result<Option<T>, S::Err>
887     where F: FnOnce(&mut Primitive<S>) -> Result<T, S::Err> {
888         self.process_next_value(Some(expected), |_, content| {
889             op(content.as_primitive()?)
890         })
891     }
892 
893     /// Captures content for later processing
894     ///
895     /// The method gives a representation of the content to the closure `op`.
896     /// If it succeeds, it returns whatever the closure advanced over as a
897     /// [`Captured`] value.
898     ///
899     /// The closure may process no, one, several, or all values of this
900     /// value’s content.
901     ///
902     /// If the closure returns an error, this error is returned.
903     ///
904     /// [`Captured`]: ../captures/struct.Captured.html
capture<F>(&mut self, op: F) -> Result<Captured, S::Err> where F: FnOnce( &mut Constructed<CaptureSource<LimitedSource<S>>> ) -> Result<(), S::Err>905     pub fn capture<F>(&mut self, op: F) -> Result<Captured, S::Err>
906     where
907         F: FnOnce(
908             &mut Constructed<CaptureSource<LimitedSource<S>>>
909         ) -> Result<(), S::Err>
910     {
911         let limit = self.source.limit();
912         let mut source = LimitedSource::new(CaptureSource::new(self.source));
913         source.set_limit(limit);
914         {
915             let mut constructed = Constructed::new(
916                 &mut source, self.state, self.mode
917             );
918             op(&mut constructed)?;
919             self.state = constructed.state;
920         }
921         Ok(Captured::new(source.unwrap().into_bytes(), self.mode))
922     }
923 
924     /// Captures one value for later processing
925     ///
926     /// The method takes the next value from this value’s content, whatever
927     /// it its, end returns its encoded form as a [`Captured`] value.
928     ///
929     /// If there is no next value, a malformed error is returned. If access
930     /// to the underlying source fails, an appropriate error is returned.
931     ///
932     /// [`Captured`]: ../captures/struct.Captured.html
capture_one(&mut self) -> Result<Captured, S::Err>933     pub fn capture_one(&mut self) -> Result<Captured, S::Err> {
934         self.capture(|cons| {
935             match cons.skip_one()? {
936                 Some(()) => Ok(()),
937                 None => {
938                     xerr!(Err(Error::Malformed.into()))
939                 }
940             }
941         })
942     }
943 
944     /// Captures all remaining content for later processing.
945     ///
946     /// The method takes all remaining values from this value’s content and
947     /// returns their encoded form in a `Bytes` value.
capture_all(&mut self) -> Result<Captured, S::Err>948     pub fn capture_all(&mut self) -> Result<Captured, S::Err> {
949         self.capture(|cons| cons.skip_all())
950     }
951 
952     /// Skips over content.
skip_opt<F>(&mut self, mut op: F) -> Result<Option<()>, S::Err> where F: FnMut(Tag, bool, usize) -> Result<(), S::Err>953     pub fn skip_opt<F>(&mut self, mut op: F) -> Result<Option<()>, S::Err>
954     where F: FnMut(Tag, bool, usize) -> Result<(), S::Err> {
955         // If we already know we are at the end of the value, we can return.
956         if self.is_exhausted() {
957             return Ok(None)
958         }
959 
960         // The stack for unrolling the recursion. For each level, we keep the
961         // limit the source should be set to when the value ends. For
962         // indefinite values, we keep `None`.
963         let mut stack = SmallVec::<[Option<Option<usize>>; 4]>::new();
964 
965         loop {
966             // Get a the ‘header’ of a value.
967             let (tag, constructed) = Tag::take_from(self.source)?;
968             let length = Length::take_from(self.source, self.mode)?;
969 
970             if !constructed {
971                 if tag == Tag::END_OF_VALUE {
972                     if length != Length::Definite(0) {
973                         xerr!(return Err(Error::Malformed.into()))
974                     }
975 
976                     // End-of-value: The top of the stack needs to be an
977                     // indefinite value for it to be allowed. If it is, pop
978                     // that value off the stack and continue. The limit is
979                     // still that from the value one level above.
980                     match stack.pop() {
981                         Some(None) => { }
982                         None => {
983                             // We read end-of-value as the very first value.
984                             // This can only happen if the outer value is
985                             // an indefinite value. If so, change state and
986                             // return.
987                             if self.state == State::Indefinite {
988                                 self.state = State::Done;
989                                 return Ok(None)
990                             }
991                             else {
992                                 xerr!(return Err(Error::Malformed.into()))
993                             }
994                         }
995                         _ => xerr!(return Err(Error::Malformed.into()))
996                     }
997                 }
998                 else {
999                     // Primitive value. Check for the length to be definite,
1000                     // check that the caller likes it, then try to read over it.
1001                     if let Length::Definite(len) = length {
1002                         op(tag, constructed, stack.len())?;
1003                         self.source.advance(len)?;
1004                     }
1005                     else {
1006                         xerr!(return Err(Error::Malformed.into()));
1007                     }
1008                 }
1009             }
1010             else if let Length::Definite(len) = length {
1011                 // Definite constructed value. First check if the caller likes
1012                 // it. Check that there is enough limit left for the value. If
1013                 // so, push the limit at the end of the value to the stack,
1014                 // update the limit to our length, and continue.
1015                 op(tag, constructed, stack.len())?;
1016                 stack.push(Some(match self.source.limit() {
1017                     Some(limit) => {
1018                         match limit.checked_sub(len) {
1019                             Some(len) => Some(len),
1020                             None => {
1021                                 xerr!(return Err(Error::Malformed.into()));
1022                             }
1023                         }
1024                     }
1025                     None => None,
1026                 }));
1027                 self.source.set_limit(Some(len));
1028             }
1029             else {
1030                 // Indefinite constructed value. Simply push a `None` to the
1031                 // stack, if the caller likes it.
1032                 op(tag, constructed, stack.len())?;
1033                 stack.push(None);
1034                 continue;
1035             }
1036 
1037             // Now we need to check if we have reached the end of a
1038             // constructed value. This happens if the limit of the
1039             // source reaches 0. Since the ends of several stacked values
1040             // can align, we need to loop here. Also, if we run out of
1041             // stack, we are done.
1042             loop {
1043                 if stack.is_empty() {
1044                     return Ok(Some(()))
1045                 }
1046                 else if self.source.limit() == Some(0) {
1047                     match stack.pop() {
1048                         Some(Some(limit)) => {
1049                             self.source.set_limit(limit)
1050                         }
1051                         Some(None) => {
1052                             // We need a End-of-value, so running out of
1053                             // data is an error.
1054                             xerr!(return Err(Error::Malformed.into()));
1055                         }
1056                         None => unreachable!(),
1057                     }
1058                 }
1059                 else {
1060                     break;
1061                 }
1062             }
1063 
1064         }
1065     }
1066 
skip<F>(&mut self, op: F) -> Result<(), S::Err> where F: FnMut(Tag, bool, usize) -> Result<(), S::Err>1067     pub fn skip<F>(&mut self, op: F) -> Result<(), S::Err>
1068     where F: FnMut(Tag, bool, usize) -> Result<(), S::Err> {
1069         if self.skip_opt(op)? == None {
1070             xerr!(Err(Error::Malformed.into()))
1071         }
1072         else {
1073             Ok(())
1074         }
1075     }
1076 
1077     /// Skips over all remaining content.
skip_all(&mut self) -> Result<(), S::Err>1078     pub fn skip_all(&mut self) -> Result<(), S::Err> {
1079         while let Some(()) = self.skip_one()? { }
1080         Ok(())
1081     }
1082 
1083     /// Attempts to skip over the next value.
1084     ///
1085     /// If there is a next value, returns `Ok(Some(()))`, if the end of value
1086     /// has already been reached, returns `Ok(None)`.
skip_one(&mut self) -> Result<Option<()>, S::Err>1087     pub fn skip_one(&mut self) -> Result<Option<()>, S::Err> {
1088         if self.is_exhausted() {
1089             Ok(None)
1090         }
1091         else {
1092             self.skip(|_, _, _| Ok(()))?;
1093             Ok(Some(()))
1094         }
1095     }
1096 }
1097 
1098 
1099 /// # Processing Standard Values
1100 ///
1101 /// These methods provide short-cuts for processing fundamental values in
1102 /// their standard form. That is, the values use their regular tag and
1103 /// encoding.
1104 impl<'a, S: Source + 'a> Constructed<'a, S> {
1105     /// Processes and returns a mandatory boolean value.
take_bool(&mut self) -> Result<bool, S::Err>1106     pub fn take_bool(&mut self) -> Result<bool, S::Err> {
1107         self.take_primitive_if(Tag::BOOLEAN, |prim| prim.to_bool())
1108     }
1109 
1110     /// Processes and returns an optional boolean value.
take_opt_bool(&mut self) -> Result<Option<bool>, S::Err>1111     pub fn take_opt_bool(&mut self) -> Result<Option<bool>, S::Err> {
1112         self.take_opt_primitive_if(Tag::BOOLEAN, |prim| prim.to_bool())
1113     }
1114 
1115     /// Processes a mandatory NULL value.
take_null(&mut self) -> Result<(), S::Err>1116     pub fn take_null(&mut self) -> Result<(), S::Err> {
1117         self.take_primitive_if(Tag::NULL, |_| Ok(())).map(|_| ())
1118     }
1119 
1120     /// Processes an optional NULL value.
take_opt_null(&mut self) -> Result<(), S::Err>1121     pub fn take_opt_null(&mut self) -> Result<(), S::Err> {
1122         self.take_opt_primitive_if(Tag::NULL, |_| Ok(())).map(|_| ())
1123     }
1124 
1125     /// Processes a mandatory INTEGER value of the `u8` range.
1126     ///
1127     /// If the integer value is less than 0 or greater than 255, a malformed
1128     /// error is returned.
take_u8(&mut self) -> Result<u8, S::Err>1129     pub fn take_u8(&mut self) -> Result<u8, S::Err> {
1130         self.take_primitive_if(Tag::INTEGER, |prim| prim.to_u8())
1131     }
1132 
1133     /// Processes an optional INTEGER value of the `u8` range.
1134     ///
1135     /// If the integer value is less than 0 or greater than 255, a malformed
1136     /// error is returned.
take_opt_u8(&mut self) -> Result<Option<u8>, S::Err>1137     pub fn take_opt_u8(&mut self) -> Result<Option<u8>, S::Err> {
1138         self.take_opt_primitive_if(Tag::INTEGER, |prim| prim.to_u8())
1139     }
1140 
1141     /// Skips over a mandatory INTEGER if it has the given value.
1142     ///
1143     /// If the next value is an integer but of a different value, returns
1144     /// a malformed error.
skip_u8_if(&mut self, expected: u8) -> Result<(), S::Err>1145     pub fn skip_u8_if(&mut self, expected: u8) -> Result<(), S::Err> {
1146         self.take_primitive_if(Tag::INTEGER, |prim| {
1147             let got = prim.take_u8()?;
1148             if got != expected {
1149                 xerr!(Err(Error::Malformed.into()))
1150             }
1151             else {
1152                 Ok(())
1153             }
1154         })
1155     }
1156 
1157     /// Skips over an optional INTEGER if it has the given value.
1158     ///
1159     /// If the next value is an integer but of a different value, returns
1160     /// a malformed error.
skip_opt_u8_if(&mut self, expected: u8) -> Result<(), S::Err>1161     pub fn skip_opt_u8_if(&mut self, expected: u8) -> Result<(), S::Err> {
1162         self.take_opt_primitive_if(Tag::INTEGER, |prim| {
1163             let got = prim.take_u8()?;
1164             if got != expected {
1165                 xerr!(Err(Error::Malformed.into()))
1166             }
1167             else {
1168                 Ok(())
1169             }
1170         }).map(|_| ())
1171     }
1172 
1173     /// Processes a mandatory INTEGER value of the `u16` range.
1174     ///
1175     /// If the integer value is less than 0 or greater than 65535, a malformed
1176     /// error is returned.
take_u16(&mut self) -> Result<u16, S::Err>1177     pub fn take_u16(&mut self) -> Result<u16, S::Err> {
1178         self.take_primitive_if(Tag::INTEGER, |prim| prim.to_u16())
1179     }
1180 
1181     /// Processes an optional INTEGER value of the `u16` range.
1182     ///
1183     /// If the integer value is less than 0 or greater than 65535, a malformed
1184     /// error is returned.
take_opt_u16(&mut self) -> Result<Option<u16>, S::Err>1185     pub fn take_opt_u16(&mut self) -> Result<Option<u16>, S::Err> {
1186         self.take_opt_primitive_if(Tag::INTEGER, |prim| prim.to_u16())
1187     }
1188 
1189     /// Processes a mandatory INTEGER value of the `u32` range.
1190     ///
1191     /// If the integer value is less than 0 or greater than 2^32-1, a
1192     /// malformed error is returned.
take_u32(&mut self) -> Result<u32, S::Err>1193     pub fn take_u32(&mut self) -> Result<u32, S::Err> {
1194         self.take_primitive_if(Tag::INTEGER, |prim| prim.to_u32())
1195     }
1196 
1197     /// Processes a optional INTEGER value of the `u32` range.
1198     ///
1199     /// If the integer value is less than 0 or greater than 2^32-1, a
1200     /// malformed error is returned.
take_opt_u32(&mut self) -> Result<Option<u32>, S::Err>1201     pub fn take_opt_u32(&mut self) -> Result<Option<u32>, S::Err> {
1202         self.take_opt_primitive_if(Tag::INTEGER, |prim| prim.to_u32())
1203     }
1204 
1205     /// Processes a mandatory INTEGER value of the `u64` range.
1206     ///
1207     /// If the integer value is less than 0 or greater than 2^64-1, a
1208     /// malformed error is returned.
take_u64(&mut self) -> Result<u64, S::Err>1209     pub fn take_u64(&mut self) -> Result<u64, S::Err> {
1210         self.take_primitive_if(Tag::INTEGER, |prim| prim.to_u64())
1211     }
1212 
1213     /// Processes a optional INTEGER value of the `u64` range.
1214     ///
1215     /// If the integer value is less than 0 or greater than 2^64-1, a
1216     /// malformed error is returned.
take_opt_u64(&mut self) -> Result<Option<u64>, S::Err>1217     pub fn take_opt_u64(&mut self) -> Result<Option<u64>, S::Err> {
1218         self.take_opt_primitive_if(Tag::INTEGER, |prim| prim.to_u64())
1219     }
1220 
1221     /// Processes a mandatory SEQUENCE value.
1222     ///
1223     /// This is a shortcut for `self.take_constructed(Tag::SEQUENCE, op)`.
take_sequence<F, T>(&mut self, op: F) -> Result<T, S::Err> where F: FnOnce(&mut Constructed<S>) -> Result<T, S::Err>1224     pub fn take_sequence<F, T>(&mut self, op: F) -> Result<T, S::Err>
1225     where F: FnOnce(&mut Constructed<S>) -> Result<T, S::Err> {
1226         self.take_constructed_if(Tag::SEQUENCE, op)
1227     }
1228 
1229     /// Processes an optional SEQUENCE value.
1230     ///
1231     /// This is a shortcut for `self.take_opt_constructed(Tag::SEQUENCE, op)`.
take_opt_sequence<F, T>( &mut self, op: F ) -> Result<Option<T>, S::Err> where F: FnOnce(&mut Constructed<S>) -> Result<T, S::Err>1232     pub fn take_opt_sequence<F, T>(
1233         &mut self,
1234         op: F
1235     ) -> Result<Option<T>, S::Err>
1236     where F: FnOnce(&mut Constructed<S>) -> Result<T, S::Err> {
1237         self.take_opt_constructed_if(Tag::SEQUENCE, op)
1238     }
1239 
1240     /// Processes a mandatory SET value.
1241     ///
1242     /// This is a shortcut for `self.take_constructed(Tag::SET, op)`.
take_set<F, T>(&mut self, op: F) -> Result<T, S::Err> where F: FnOnce(&mut Constructed<S>) -> Result<T, S::Err>1243     pub fn take_set<F, T>(&mut self, op: F) -> Result<T, S::Err>
1244     where F: FnOnce(&mut Constructed<S>) -> Result<T, S::Err> {
1245         self.take_constructed_if(Tag::SET, op)
1246     }
1247 
1248     /// Processes an optional SET value.
1249     ///
1250     /// This is a shortcut for `self.take_opt_constructed(Tag::SET, op)`.
take_opt_set<F, T>(&mut self, op: F) -> Result<Option<T>, S::Err> where F: FnOnce(&mut Constructed<S>) -> Result<T, S::Err>1251     pub fn take_opt_set<F, T>(&mut self, op: F) -> Result<Option<T>, S::Err>
1252     where F: FnOnce(&mut Constructed<S>) -> Result<T, S::Err> {
1253         self.take_opt_constructed_if(Tag::SET, op)
1254     }
1255 }
1256 
1257 
1258 //------------ State ---------------------------------------------------------
1259 
1260 /// The processing state of a constructed value.
1261 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
1262 enum State {
1263     /// We are reading until the end of the reader.
1264     Definite,
1265 
1266     /// Indefinite value, we haven’t reached the end yet.
1267     Indefinite,
1268 
1269     /// End of indefinite value reached.
1270     Done,
1271 
1272     /// Unbounded value: read as far as we get.
1273     Unbounded,
1274 }
1275 
1276 
1277 //============ Tests =========================================================
1278 
1279 #[cfg(test)]
1280 mod test {
1281     use super::*;
1282 
1283     #[test]
constructed_skip()1284     fn constructed_skip() {
1285         // Two primitives.
1286         Constructed::decode(
1287             b"\x02\x01\x00\x02\x01\x00".as_ref(), Mode::Ber, |cons| {
1288                 cons.skip(|_, _, _| Ok(())).unwrap();
1289                 cons.skip(|_, _, _| Ok(())).unwrap();
1290                 Ok(())
1291             }
1292         ).unwrap();
1293 
1294         // One definite constructed with two primitives, then one primitive
1295         Constructed::decode(
1296             b"\x30\x06\x02\x01\x00\x02\x01\x00\x02\x01\x00".as_ref(),
1297             Mode::Ber,
1298             |cons| {
1299                 cons.skip(|_, _, _| Ok(())).unwrap();
1300                 cons.skip(|_, _, _| Ok(())).unwrap();
1301                 Ok(())
1302             }
1303         ).unwrap();
1304 
1305         // Two nested definite constructeds with two primitives, then one
1306         // primitive.
1307         Constructed::decode(
1308             b"\x30\x08\
1309             \x30\x06\
1310             \x02\x01\x00\x02\x01\x00\
1311             \x02\x01\x00".as_ref(),
1312             Mode::Ber,
1313             |cons| {
1314                 cons.skip(|_, _, _| Ok(())).unwrap();
1315                 cons.skip(|_, _, _| Ok(())).unwrap();
1316                 Ok(())
1317             }
1318         ).unwrap();
1319 
1320         // One definite constructed with one indefinite with two primitives.
1321         Constructed::decode(
1322             b"\x30\x0A\
1323             \x30\x80\
1324             \x02\x01\x00\x02\x01\x00\
1325             \0\0".as_ref(),
1326             Mode::Ber,
1327             |cons| {
1328                 cons.skip(|_, _, _| Ok(())).unwrap();
1329                 Ok(())
1330             }
1331         ).unwrap();
1332     }
1333 }
1334 
1335