1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
macro_rules! impl_any_conversions {
($type: ty) => {
impl_any_conversions!($type, );
};
($type: ty, $($li: lifetime)?) => {
impl<'__der: $($li),*, $($li),*> TryFrom<$crate::AnyRef<'__der>> for $type {
type Error = $crate::Error;
fn try_from(any: $crate::AnyRef<'__der>) -> $crate::Result<$type> {
any.decode_as()
}
}
#[cfg(feature = "alloc")]
impl<'__der: $($li),*, $($li),*> TryFrom<&'__der $crate::Any> for $type {
type Error = $crate::Error;
fn try_from(any: &'__der $crate::Any) -> $crate::Result<$type> {
any.decode_as()
}
}
};
}
macro_rules! impl_string_type {
($type: ty, $($li: lifetime)?) => {
impl_any_conversions!($type, $($li),*);
mod __impl_string {
use super::*;
use crate::{
ord::OrdIsValueOrd, BytesRef, DecodeValue, EncodeValue, Header, Length, Reader,
Result, Writer,
};
use core::{fmt, str};
impl<$($li),*> AsRef<str> for $type {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl<$($li),*> AsRef<[u8]> for $type {
fn as_ref(&self) -> &[u8] {
self.as_bytes()
}
}
impl<'__der: $($li),*, $($li),*> DecodeValue<'__der> for $type {
type Error = $crate::Error;
fn decode_value<R: Reader<'__der>>(reader: &mut R, header: Header) -> $crate::Result<Self> {
Self::new(<&'__der BytesRef>::decode_value(reader, header)?.as_slice())
}
}
impl<$($li),*> EncodeValue for $type {
fn value_len(&self) -> Result<Length> {
self.inner.value_len()
}
fn encode_value(&self, writer: &mut impl Writer) -> Result<()> {
self.inner.encode_value(writer)
}
}
impl<$($li),*> OrdIsValueOrd for $type {}
impl<$($li),*> fmt::Display for $type {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
}
};
}
macro_rules! impl_custom_class {
($class_type_name: ident, $class_enum_name: ident, $asn1_class_name: literal, $class_bits_str: literal) => {
#[doc = concat!("`", $asn1_class_name, "` field which wraps an owned inner value.")]
///
/// This type decodes/encodes a field which is specific to a particular context
/// and is identified by a [`TagNumber`].
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
pub struct $class_type_name<T> {
#[doc = concat!("`", $asn1_class_name, "` tag number sans the leading `", $class_bits_str, "` class")]
/// identifier bit and `0b100000` constructed flag.
pub tag_number: TagNumber,
/// Tag mode: `EXPLICIT` VS `IMPLICIT`.
pub tag_mode: TagMode,
/// Value of the field.
pub value: T,
}
impl<T> $class_type_name<T> {
#[doc = concat!("Attempt to decode an `EXPLICIT` ASN.1 `", $asn1_class_name, "` field with the")]
/// provided [`TagNumber`].
///
/// This method has the following behavior which decodes tag numbers one by one
/// in extension fields, which are denoted in an ASN.1 schema using
/// the `...` ellipsis extension marker:
///
/// - Returns `Ok(Some(..))` if tag number matches.
#[doc = concat!("- Returns `Ok(None)` if class other than [`Class::", stringify!($class_enum_name), "`] tag")]
/// is encountered.
/// - Returns `Ok(None)` if a field with a different tag number is encountered.
/// These fields are not consumed in this case.
///
/// # Errors
/// Returns [`ErrorKind::Noncanonical`] if constructed bit is primitive.
pub fn decode_explicit<'a, R: Reader<'a>>(
reader: &mut R,
tag_number: TagNumber,
) -> Result<Option<Self>, T::Error>
where
T: Decode<'a>,
{
if !Tag::peek_matches(reader, Class::$class_enum_name, tag_number)? {
return Ok(None);
}
Ok(Some(Self::decode(reader)?))
}
#[doc = concat!("Attempt to decode an `IMPLICIT` ASN.1 `", $asn1_class_name, "` field with the")]
/// provided [`TagNumber`].
///
/// This method otherwise behaves the same as `decode_explicit`,
/// but should be used in cases where the particular fields are `IMPLICIT`
/// as opposed to `EXPLICIT`.
///
/// Differences from `EXPLICIT`:
/// - Returns [`ErrorKind::Noncanonical`] if constructed bit
/// does not match constructed bit of the base encoding.
///
/// # Errors
/// Returns `T::Error` in the event of a decoding error.
pub fn decode_implicit<'a, R: Reader<'a>>(
reader: &mut R,
tag_number: TagNumber,
) -> Result<Option<Self>, T::Error>
where
T: DecodeValue<'a> + IsConstructed,
{
// Peek tag number
if !Tag::peek_matches(reader, Class::$class_enum_name, tag_number)? {
return Ok(None);
}
// Decode IMPLICIT header
let header = Header::decode(reader)?;
// the encoding shall be constructed if the base encoding is constructed
if header.tag().is_constructed() != T::CONSTRUCTED
&& reader.encoding_rules().is_der() {
return Err(reader.error(header.tag().non_canonical_error()).into());
}
// read_value checks if header matches decoded length
let value = crate::reader::read_value(reader, header, T::decode_value)?;
Ok(Some(Self {
tag_number,
tag_mode: TagMode::Implicit,
value,
}))
}
}
impl<'a, T> Choice<'a> for $class_type_name<T>
where
T: Decode<'a> + Tagged,
{
fn can_decode(tag: Tag) -> bool {
tag.class() == Class::$class_enum_name
}
}
impl<'a, T> Decode<'a> for $class_type_name<T>
where
T: Decode<'a>,
{
type Error = T::Error;
fn decode<R: Reader<'a>>(reader: &mut R) -> Result<Self, Self::Error> {
// Decode EXPLICIT header
let header = Header::decode(reader)?;
// encoding shall be constructed
if !header.tag().is_constructed() {
return Err(reader.error(header.tag().non_canonical_error()).into());
}
match header.tag() {
Tag::$class_enum_name { number, .. } => Ok(Self {
tag_number: number,
tag_mode: TagMode::default(),
value: crate::reader::read_value(reader, header, |reader, _| {
// Decode inner tag-length-value of EXPLICIT
T::decode(reader)
})?,
}),
tag => Err(reader.error(tag.unexpected_error(None)).into())
}
}
}
impl<T> EncodeValue for $class_type_name<T>
where
T: EncodeValue + Tagged,
{
fn value_len(&self) -> Result<Length, Error> {
match self.tag_mode {
TagMode::Explicit => self.value.encoded_len(),
TagMode::Implicit => self.value.value_len(),
}
}
fn encode_value(&self, writer: &mut impl Writer) -> Result<(), Error> {
match self.tag_mode {
TagMode::Explicit => self.value.encode(writer),
TagMode::Implicit => self.value.encode_value(writer),
}
}
}
impl<T> Tagged for $class_type_name<T>
where
T: Tagged,
{
fn tag(&self) -> Tag {
let constructed = match self.tag_mode {
// ISO/IEC 8825-1:2021
// 8.14.3 If implicit tagging (see Rec. ITU-T X.680 | ISO/IEC 8824-1, 31.2.7) was not used in the definition of the type, the
// encoding shall be constructed and the contents octets shall be the complete base encoding [Encode].
TagMode::Explicit => true,
// ISO/IEC 8825-1:2021
// 8.14.4 If implicit tagging was used in the definition of the type, then:
// a) the encoding shall be constructed if the base encoding is constructed, and shall be primitive otherwise; and
// b) the contents octets shall be the same as the contents octets [EncodeValue] of the base encoding.
//
// TODO(dishmaker): use IsConstructed trait for IMPLICIT
TagMode::Implicit => self.value.tag().is_constructed(),
};
Tag::$class_enum_name {
number: self.tag_number,
constructed,
}
}
}
impl<'a, T> TryFrom<AnyRef<'a>> for $class_type_name<T>
where
T: Decode<'a>,
{
type Error = T::Error;
fn try_from(any: AnyRef<'a>) -> Result<$class_type_name<T>, Self::Error> {
match any.tag() {
Tag::$class_enum_name {
number,
constructed: true,
} => Ok(Self {
tag_number: number,
tag_mode: TagMode::default(),
value: T::from_der(any.value())?,
}),
tag => Err(tag.unexpected_error(None).to_error().into()),
}
}
}
impl<T> ValueOrd for $class_type_name<T>
where
T: EncodeValue + ValueOrd + Tagged,
{
fn value_cmp(&self, other: &Self) -> Result<Ordering, Error> {
match self.tag_mode {
TagMode::Explicit => self.der_cmp(other),
TagMode::Implicit => self.value_cmp(other),
}
}
}
};
}
macro_rules! impl_custom_class_ref {
($ref_class_type_name: ident, $class_type_name: ident, $asn1_class_name: literal, $class_bits_str: literal) => {
#[doc = concat!("`", $asn1_class_name, "` field reference.")]
///
///
/// This type encodes a field which is specific to a particular context
/// and is identified by a [`TagNumber`].
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
pub struct $ref_class_type_name<'a, T> {
#[doc = concat!("`", $asn1_class_name, "` tag number sans the leading `", $class_bits_str, "` class")]
/// identifier bit and `0b100000` constructed flag.
pub tag_number: TagNumber,
/// Tag mode: `EXPLICIT` VS `IMPLICIT`.
pub tag_mode: TagMode,
/// Value of the field.
pub value: &'a T,
}
impl<'a, T> $ref_class_type_name<'a, T> {
/// Convert to a [`EncodeValue`] object using [`EncodeValueRef`].
fn encoder(&self) -> $class_type_name<EncodeValueRef<'a, T>> {
$class_type_name {
tag_number: self.tag_number,
tag_mode: self.tag_mode,
value: EncodeValueRef(self.value),
}
}
}
impl<T> EncodeValue for $ref_class_type_name<'_, T>
where
T: EncodeValue + Tagged,
{
fn value_len(&self) -> Result<Length, Error> {
self.encoder().value_len()
}
fn encode_value(&self, writer: &mut impl Writer) -> Result<(), Error> {
self.encoder().encode_value(writer)
}
}
impl<T> Tagged for $ref_class_type_name<'_, T>
where
T: Tagged,
{
fn tag(&self) -> Tag {
self.encoder().tag()
}
}
};
}