bcder/mode.rs
1//! The BER mode.
2//!
3//! This is a private module. It’s public items are re-exported by the parent.
4
5use crate::decode;
6use crate::decode::DecodeError;
7
8
9//------------ Mode ----------------------------------------------------------
10
11/// The BER Mode.
12///
13/// X.680 defines not one but three sets of related encoding rules. All three
14/// follow the same basic ideas but implement them in slightly different
15/// ways.
16///
17/// This type represents these rules. The [`decode`] method provides a way to
18/// decode a source using the specific decoding mode. You can also change
19/// the decoding mode later on through the `set_mode` methods of [`Primitive`]
20/// and [`Constructed`].
21///
22/// [`decode´]: #method.decode
23/// [`Primitive`]: decode/struct.Primitive.html
24/// [`Constructed`]: decode/struct.Constructed.html
25#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
26pub enum Mode {
27 /// Basic Encoding Rules.
28 ///
29 /// These are the most flexible rules, allowing alternative encodings for
30 /// some types as well as indefinite length values.
31 #[default]
32 Ber,
33
34 /// Canonical Encoding Rules.
35 ///
36 /// These rules always employ indefinite length encoding for constructed
37 /// values and the shortest possible form for primitive values. There
38 /// are additional restrictions for certain types.
39 Cer,
40
41 /// Distinguished Encoding Rules.
42 ///
43 /// These rules always employ definite length values and require the
44 /// shortest possible encoding. Additional rules apply to some types.
45 Der,
46}
47
48impl Mode {
49 /// Decode a source using a specific mode.
50 ///
51 /// The method will attempt to decode `source` using the rules represented
52 /// by this value. The closure `op` will be given the content of the
53 /// source as a sequence of values. The closure does not need to process
54 /// all values in the source.
55 pub fn decode<S, F, T>(
56 self, source: S, op: F,
57 ) -> Result<T, DecodeError<<S::Source as decode::Source>::Error>>
58 where
59 S: decode::IntoSource,
60 F: FnOnce(
61 &mut decode::Constructed<S::Source>
62 ) -> Result<T, DecodeError<<S::Source as decode::Source>::Error>>,
63 {
64 decode::Constructed::decode(source, self, op)
65 }
66
67 /// Returns whether the mode is `Mode::Ber`.
68 pub fn is_ber(self) -> bool {
69 matches!(self, Mode::Ber)
70 }
71
72 /// Returns whether the mode is `Mode::Cer`.
73 pub fn is_cer(self) -> bool {
74 matches!(self, Mode::Cer)
75 }
76
77 /// Returns whether the mode is `Mode::Der`.
78 pub fn is_der(self) -> bool {
79 matches!(self, Mode::Der)
80 }
81}
82