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