rasn/
enc.rs

1//! Generic ASN.1 encoding framework.
2
3use crate::types::{self, AsnType, Constraints, Enumerated, Tag};
4
5pub use rasn_derive::Encode;
6
7/// A **data type** that can be encoded to a ASN.1 data format.
8pub trait Encode: AsnType {
9    /// Encodes `self`'s data into the given `Encoder`.
10    ///
11    /// **Note for implementors** You typically do not need to implement this.
12    /// The default implementation will call `Encode::encode_with_tag` with
13    /// your types associated `AsnType::TAG`. You should only ever need to
14    /// implement this if you have a type that *cannot* be implicitly tagged,
15    /// such as a `CHOICE` type, in which case you want to implement encoding
16    /// in `encode`.
17    fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), E::Error> {
18        self.encode_with_tag_and_constraints(encoder, Self::TAG, Self::CONSTRAINTS)
19    }
20
21    /// Encode this value with `tag` into the given `Encoder`.
22    ///
23    /// **Note** For `CHOICE` and other types that cannot be implicitly tagged
24    /// this will **explicitly tag** the value, for all other types, it will
25    /// **implicitly** tag the value.
26    fn encode_with_tag<E: Encoder>(&self, encoder: &mut E, tag: Tag) -> Result<(), E::Error> {
27        self.encode_with_tag_and_constraints(encoder, tag, Self::CONSTRAINTS)
28    }
29
30    fn encode_with_constraints<E: Encoder>(
31        &self,
32        encoder: &mut E,
33        constraints: Constraints,
34    ) -> Result<(), E::Error> {
35        self.encode_with_tag_and_constraints(encoder, Self::TAG, constraints)
36    }
37
38    fn encode_with_tag_and_constraints<E: Encoder>(
39        &self,
40        encoder: &mut E,
41        tag: Tag,
42        constraints: Constraints,
43    ) -> Result<(), E::Error>;
44}
45
46/// A **data format** encode any ASN.1 data type.
47pub trait Encoder {
48    type Ok;
49    type Error: Error + Into<crate::error::EncodeError> + From<crate::error::EncodeError>;
50
51    /// Returns codec variant of `Codec` that current encoder is encoding.
52    fn codec(&self) -> crate::Codec;
53
54    /// Encode an unknown ASN.1 value.
55    fn encode_any(&mut self, tag: Tag, value: &types::Any) -> Result<Self::Ok, Self::Error>;
56
57    /// Encode a `BOOL` value.
58    fn encode_bool(&mut self, tag: Tag, value: bool) -> Result<Self::Ok, Self::Error>;
59
60    /// Encode a `BIT STRING` value.
61    fn encode_bit_string(
62        &mut self,
63        tag: Tag,
64        constraints: Constraints,
65        value: &types::BitStr,
66    ) -> Result<Self::Ok, Self::Error>;
67
68    /// Encode a `ENUMERATED` value.
69    fn encode_enumerated<E: Enumerated>(
70        &mut self,
71        tag: Tag,
72        value: &E,
73    ) -> Result<Self::Ok, Self::Error>;
74
75    /// Encode a `OBJECT IDENTIFIER` value.
76    fn encode_object_identifier(
77        &mut self,
78        tag: Tag,
79        value: &[u32],
80    ) -> Result<Self::Ok, Self::Error>;
81
82    /// Encode a `INTEGER` value.
83    fn encode_integer(
84        &mut self,
85        tag: Tag,
86        constraints: Constraints,
87        value: &num_bigint::BigInt,
88    ) -> Result<Self::Ok, Self::Error>;
89
90    /// Encode a `NULL` value.
91    fn encode_null(&mut self, tag: Tag) -> Result<Self::Ok, Self::Error>;
92
93    /// Encode a `OCTET STRING` value.
94    fn encode_octet_string(
95        &mut self,
96        tag: Tag,
97        constraints: Constraints,
98        value: &[u8],
99    ) -> Result<Self::Ok, Self::Error>;
100
101    /// Encode a `GeneralString` value.
102    fn encode_general_string(
103        &mut self,
104        tag: Tag,
105        constraints: Constraints,
106        value: &types::GeneralString,
107    ) -> Result<Self::Ok, Self::Error>;
108
109    /// Encode a `Utf8String` value.
110    fn encode_utf8_string(
111        &mut self,
112        tag: Tag,
113        constraints: Constraints,
114        value: &str,
115    ) -> Result<Self::Ok, Self::Error>;
116
117    /// Encode a `VisibleString` value.
118    fn encode_visible_string(
119        &mut self,
120        tag: Tag,
121        constraints: Constraints,
122        value: &types::VisibleString,
123    ) -> Result<Self::Ok, Self::Error>;
124
125    /// Encode a `Ia5String` value.
126    fn encode_ia5_string(
127        &mut self,
128        tag: Tag,
129        constraints: Constraints,
130        value: &types::Ia5String,
131    ) -> Result<Self::Ok, Self::Error>;
132
133    /// Encode a `Ia5String` value.
134    fn encode_printable_string(
135        &mut self,
136        tag: Tag,
137        constraints: Constraints,
138        value: &types::PrintableString,
139    ) -> Result<Self::Ok, Self::Error>;
140
141    /// Encode a `NumericString` value.
142    fn encode_numeric_string(
143        &mut self,
144        tag: Tag,
145        constraints: Constraints,
146        value: &types::NumericString,
147    ) -> Result<Self::Ok, Self::Error>;
148
149    /// Encode a `TeletexString` value.
150    fn encode_teletex_string(
151        &mut self,
152        tag: Tag,
153        constraints: Constraints,
154        value: &types::TeletexString,
155    ) -> Result<Self::Ok, Self::Error>;
156
157    /// Encode a `BmpString` value.
158    fn encode_bmp_string(
159        &mut self,
160        tag: Tag,
161        constraints: Constraints,
162        value: &types::BmpString,
163    ) -> Result<Self::Ok, Self::Error>;
164
165    /// Encode a `GeneralizedTime` value.
166    fn encode_generalized_time(
167        &mut self,
168        tag: Tag,
169        value: &types::GeneralizedTime,
170    ) -> Result<Self::Ok, Self::Error>;
171
172    /// Encode a `UtcTime` value.
173    fn encode_utc_time(
174        &mut self,
175        tag: Tag,
176        value: &types::UtcTime,
177    ) -> Result<Self::Ok, Self::Error>;
178
179    /// Encode a explicitly tagged value.
180    fn encode_explicit_prefix<V: Encode>(
181        &mut self,
182        tag: Tag,
183        value: &V,
184    ) -> Result<Self::Ok, Self::Error>;
185
186    /// Encode a `SEQUENCE` value.
187    fn encode_sequence<C, F>(
188        &mut self,
189        tag: Tag,
190        encoder_scope: F,
191    ) -> Result<Self::Ok, Self::Error>
192    where
193        C: crate::types::Constructed,
194        F: FnOnce(&mut Self) -> Result<(), Self::Error>;
195
196    /// Encode a `SEQUENCE OF` value.
197    fn encode_sequence_of<E: Encode>(
198        &mut self,
199        tag: Tag,
200        value: &[E],
201        constraints: Constraints,
202    ) -> Result<Self::Ok, Self::Error>;
203
204    /// Encode a `SET` value.
205    fn encode_set<C, F>(&mut self, tag: Tag, value: F) -> Result<Self::Ok, Self::Error>
206    where
207        C: crate::types::Constructed,
208        F: FnOnce(&mut Self) -> Result<(), Self::Error>;
209
210    /// Encode a `SET OF` value.
211    fn encode_set_of<E: Encode>(
212        &mut self,
213        tag: Tag,
214        value: &types::SetOf<E>,
215        constraints: Constraints,
216    ) -> Result<Self::Ok, Self::Error>;
217
218    /// Encode the value a field or skip if it matches the default..
219    fn encode_or_default<E: Encode + Default + PartialEq>(
220        &mut self,
221        value: &E,
222    ) -> Result<Self::Ok, Self::Error> {
223        if value != &E::default() {
224            self.encode_some(value)
225        } else {
226            self.encode_none::<E>()
227        }
228    }
229
230    /// Encode the present value of an optional field.
231    fn encode_with_tag_or_default<E: Encode + Default + PartialEq>(
232        &mut self,
233        tag: Tag,
234        value: &E,
235    ) -> Result<Self::Ok, Self::Error> {
236        if value != &E::default() {
237            self.encode_some_with_tag(tag, value)
238        } else {
239            self.encode_none::<E>()
240        }
241    }
242
243    /// Encode the present value of an optional field.
244    fn encode_some<E: Encode>(&mut self, value: &E) -> Result<Self::Ok, Self::Error>;
245
246    /// Encode the present value of an optional field.
247    fn encode_some_with_tag<E: Encode>(
248        &mut self,
249        tag: Tag,
250        value: &E,
251    ) -> Result<Self::Ok, Self::Error> {
252        self.encode_some_with_tag_and_constraints(tag, <_>::default(), value)
253    }
254
255    /// Encode the present value of an optional field.
256    fn encode_some_with_tag_and_constraints<E: Encode>(
257        &mut self,
258        tag: Tag,
259        constraints: Constraints,
260        value: &E,
261    ) -> Result<Self::Ok, Self::Error>;
262
263    /// Encode the absent value of an optional field.
264    fn encode_none<E: Encode>(&mut self) -> Result<Self::Ok, Self::Error>;
265
266    /// Encode the absent value with `tag` of an optional field.
267    fn encode_none_with_tag(&mut self, tag: Tag) -> Result<Self::Ok, Self::Error>;
268
269    /// Encode the present value of an optional field.
270    fn encode_default<E: Encode + PartialEq>(
271        &mut self,
272        value: &E,
273        default: impl FnOnce() -> E,
274    ) -> Result<Self::Ok, Self::Error> {
275        match (*value != (default)()).then_some(value) {
276            Some(value) => self.encode_some(value),
277            None => self.encode_none::<E>(),
278        }
279    }
280
281    /// Encode the present value of an optional field.
282    fn encode_default_with_tag<E: Encode + PartialEq>(
283        &mut self,
284        tag: Tag,
285        value: &E,
286        default: impl FnOnce() -> E,
287    ) -> Result<Self::Ok, Self::Error> {
288        match (*value != (default)()).then_some(value) {
289            Some(value) => self.encode_some_with_tag(tag, value),
290            None => self.encode_none_with_tag(tag),
291        }
292    }
293
294    /// Encode the present value of an optional field.
295    fn encode_default_with_tag_and_constraints<E: Encode + PartialEq>(
296        &mut self,
297        tag: Tag,
298        constraints: Constraints,
299        value: &E,
300        default: impl FnOnce() -> E,
301    ) -> Result<Self::Ok, Self::Error> {
302        match (*value != (default)()).then_some(value) {
303            Some(value) => self.encode_some_with_tag_and_constraints(tag, constraints, value),
304            None => self.encode_none_with_tag(tag),
305        }
306    }
307
308    /// Encode the present constrained value of an optional field.
309    fn encode_default_with_constraints<E: Encode + PartialEq>(
310        &mut self,
311        constraints: Constraints,
312        value: &E,
313        default: impl FnOnce() -> E,
314    ) -> Result<Self::Ok, Self::Error> {
315        match (*value != (default)()).then_some(value) {
316            Some(value) => self.encode_some_with_tag_and_constraints(E::TAG, constraints, value),
317            None => self.encode_none_with_tag(E::TAG),
318        }
319    }
320
321    /// Encode a `CHOICE` value.
322    fn encode_choice<E: Encode + crate::types::Choice>(
323        &mut self,
324        constraints: Constraints,
325        tag: Tag,
326        encode_fn: impl FnOnce(&mut Self) -> Result<Tag, Self::Error>,
327    ) -> Result<Self::Ok, Self::Error>;
328
329    /// Encode a extension addition value.
330    fn encode_extension_addition<E: Encode>(
331        &mut self,
332        tag: Tag,
333        constraints: Constraints,
334        value: E,
335    ) -> Result<Self::Ok, Self::Error>;
336
337    /// Encode a extension addition group value.
338    fn encode_extension_addition_group<E>(
339        &mut self,
340        value: Option<&E>,
341    ) -> Result<Self::Ok, Self::Error>
342    where
343        E: Encode + crate::types::Constructed;
344}
345
346/// A generic error that occurred while trying to encode ASN.1.
347pub trait Error: core::fmt::Display {
348    /// Creates a new general error using `msg` and current `codec` when encoding ASN.1.
349    fn custom<D: core::fmt::Display>(msg: D, codec: crate::Codec) -> Self;
350}
351
352impl Error for core::convert::Infallible {
353    fn custom<D: core::fmt::Display>(msg: D, codec: crate::Codec) -> Self {
354        core::panic!("Infallible error! {}, from: {}", msg, codec)
355    }
356}
357
358impl<E: Encode> Encode for &'_ E {
359    fn encode<EN: Encoder>(&self, encoder: &mut EN) -> Result<(), EN::Error> {
360        E::encode(self, encoder)
361    }
362
363    fn encode_with_tag<EN: Encoder>(&self, encoder: &mut EN, tag: Tag) -> Result<(), EN::Error> {
364        E::encode_with_tag(self, encoder, tag)
365    }
366
367    fn encode_with_constraints<EN: Encoder>(
368        &self,
369        encoder: &mut EN,
370        constraints: Constraints,
371    ) -> Result<(), EN::Error> {
372        E::encode_with_constraints(self, encoder, constraints)
373    }
374
375    fn encode_with_tag_and_constraints<EN: Encoder>(
376        &self,
377        encoder: &mut EN,
378        tag: Tag,
379        constraints: Constraints,
380    ) -> Result<(), EN::Error> {
381        E::encode_with_tag_and_constraints(self, encoder, tag, constraints)
382    }
383}
384
385impl Encode for () {
386    fn encode_with_tag_and_constraints<E: Encoder>(
387        &self,
388        encoder: &mut E,
389        tag: Tag,
390        _: Constraints,
391    ) -> Result<(), E::Error> {
392        encoder.encode_null(tag).map(drop)
393    }
394}
395
396impl<E: Encode> Encode for Option<E> {
397    fn encode<EN: Encoder>(&self, encoder: &mut EN) -> Result<(), EN::Error> {
398        match self {
399            Some(value) => encoder.encode_some::<E>(value),
400            None => encoder.encode_none::<E>(),
401        }
402        .map(drop)
403    }
404
405    fn encode_with_tag<EN: Encoder>(&self, encoder: &mut EN, tag: Tag) -> Result<(), EN::Error> {
406        match self {
407            Some(value) => encoder.encode_some_with_tag(tag, value),
408            None => encoder.encode_none::<E>(),
409        }
410        .map(drop)
411    }
412
413    fn encode_with_constraints<EN: Encoder>(
414        &self,
415        encoder: &mut EN,
416        constraints: Constraints,
417    ) -> Result<(), EN::Error> {
418        match self {
419            Some(value) => {
420                encoder.encode_some_with_tag_and_constraints(Self::TAG, constraints, value)
421            }
422            None => encoder.encode_none::<E>(),
423        }
424        .map(drop)
425    }
426
427    fn encode_with_tag_and_constraints<EN: Encoder>(
428        &self,
429        encoder: &mut EN,
430        tag: Tag,
431        constraints: Constraints,
432    ) -> Result<(), EN::Error> {
433        match self {
434            Some(value) => encoder.encode_some_with_tag_and_constraints(tag, constraints, value),
435
436            None => encoder.encode_none::<E>(),
437        }
438        .map(drop)
439    }
440}
441
442impl Encode for bool {
443    fn encode_with_tag_and_constraints<E: Encoder>(
444        &self,
445        encoder: &mut E,
446        tag: Tag,
447        _: Constraints,
448    ) -> Result<(), E::Error> {
449        encoder.encode_bool(tag, *self).map(drop)
450    }
451}
452
453macro_rules! impl_integers {
454    ($($int:ty),+) => {
455        $(
456            impl Encode for $int {
457                fn encode_with_tag_and_constraints<E: Encoder>(&self, encoder: &mut E, tag: Tag, constraints: Constraints) -> Result<(), E::Error> {
458                    encoder.encode_integer(
459                        tag,
460                        constraints,
461                        &(*self).into()
462                    ).map(drop)
463                }
464            }
465        )+
466    }
467}
468
469impl_integers! {
470    i8,
471    i16,
472    i32,
473    i64,
474    isize,
475    u8,
476    u16,
477    u32,
478    u64,
479    usize
480}
481
482impl<const START: i128, const END: i128> Encode for types::ConstrainedInteger<START, END> {
483    fn encode_with_tag_and_constraints<E: Encoder>(
484        &self,
485        encoder: &mut E,
486        tag: Tag,
487        constraints: Constraints,
488    ) -> Result<(), E::Error> {
489        encoder.encode_integer(tag, constraints, self).map(drop)
490    }
491}
492
493impl Encode for types::Integer {
494    fn encode_with_tag_and_constraints<E: Encoder>(
495        &self,
496        encoder: &mut E,
497        tag: Tag,
498        constraints: Constraints,
499    ) -> Result<(), E::Error> {
500        encoder.encode_integer(tag, constraints, self).map(drop)
501    }
502}
503
504impl Encode for types::OctetString {
505    fn encode_with_tag_and_constraints<E: Encoder>(
506        &self,
507        encoder: &mut E,
508        tag: Tag,
509        constraints: Constraints,
510    ) -> Result<(), E::Error> {
511        encoder
512            .encode_octet_string(tag, constraints, self)
513            .map(drop)
514    }
515}
516
517impl Encode for types::Utf8String {
518    fn encode_with_tag_and_constraints<E: Encoder>(
519        &self,
520        encoder: &mut E,
521        tag: Tag,
522        constraints: Constraints,
523    ) -> Result<(), E::Error> {
524        encoder.encode_utf8_string(tag, constraints, self).map(drop)
525    }
526}
527
528impl Encode for &'_ str {
529    fn encode_with_tag_and_constraints<E: Encoder>(
530        &self,
531        encoder: &mut E,
532        tag: Tag,
533        constraints: Constraints,
534    ) -> Result<(), E::Error> {
535        encoder.encode_utf8_string(tag, constraints, self).map(drop)
536    }
537}
538
539impl Encode for types::ObjectIdentifier {
540    fn encode_with_tag_and_constraints<E: Encoder>(
541        &self,
542        encoder: &mut E,
543        tag: Tag,
544        _: Constraints,
545    ) -> Result<(), E::Error> {
546        encoder.encode_object_identifier(tag, self).map(drop)
547    }
548}
549
550impl Encode for types::Oid {
551    fn encode_with_tag_and_constraints<E: Encoder>(
552        &self,
553        encoder: &mut E,
554        tag: Tag,
555        _: Constraints,
556    ) -> Result<(), E::Error> {
557        encoder.encode_object_identifier(tag, self).map(drop)
558    }
559}
560
561impl Encode for types::UtcTime {
562    fn encode_with_tag_and_constraints<E: Encoder>(
563        &self,
564        encoder: &mut E,
565        tag: Tag,
566        _: Constraints,
567    ) -> Result<(), E::Error> {
568        encoder.encode_utc_time(tag, self).map(drop)
569    }
570}
571
572impl Encode for types::GeneralizedTime {
573    fn encode_with_tag_and_constraints<E: Encoder>(
574        &self,
575        encoder: &mut E,
576        tag: Tag,
577        _: Constraints,
578    ) -> Result<(), E::Error> {
579        encoder.encode_generalized_time(tag, self).map(drop)
580    }
581}
582
583impl Encode for types::Any {
584    fn encode_with_tag_and_constraints<E: Encoder>(
585        &self,
586        encoder: &mut E,
587        tag: Tag,
588        _: Constraints,
589    ) -> Result<(), E::Error> {
590        encoder.encode_any(tag, self).map(drop)
591    }
592}
593
594impl<E: Encode> Encode for alloc::boxed::Box<E> {
595    fn encode<EN: Encoder>(&self, encoder: &mut EN) -> Result<(), EN::Error> {
596        E::encode(self, encoder)
597    }
598
599    fn encode_with_tag<EN: Encoder>(&self, encoder: &mut EN, tag: Tag) -> Result<(), EN::Error> {
600        E::encode_with_tag(self, encoder, tag)
601    }
602
603    fn encode_with_constraints<EN: Encoder>(
604        &self,
605        encoder: &mut EN,
606        constraints: Constraints,
607    ) -> Result<(), EN::Error> {
608        E::encode_with_constraints(self, encoder, constraints)
609    }
610
611    fn encode_with_tag_and_constraints<EN: Encoder>(
612        &self,
613        encoder: &mut EN,
614        tag: Tag,
615        constraints: Constraints,
616    ) -> Result<(), EN::Error> {
617        E::encode_with_tag_and_constraints(self, encoder, tag, constraints)
618    }
619}
620
621impl<E: Encode> Encode for alloc::vec::Vec<E> {
622    fn encode_with_tag_and_constraints<EN: Encoder>(
623        &self,
624        encoder: &mut EN,
625        tag: Tag,
626        constraints: Constraints,
627    ) -> Result<(), EN::Error> {
628        encoder.encode_sequence_of(tag, self, constraints).map(drop)
629    }
630}
631
632impl<E: Encode> Encode for alloc::collections::BTreeSet<E> {
633    fn encode_with_tag_and_constraints<EN: Encoder>(
634        &self,
635        encoder: &mut EN,
636        tag: Tag,
637        constraints: Constraints,
638    ) -> Result<(), EN::Error> {
639        encoder.encode_set_of(tag, self, constraints).map(drop)
640    }
641}
642
643impl<E: Encode, const N: usize> Encode for [E; N] {
644    fn encode_with_tag_and_constraints<EN: Encoder>(
645        &self,
646        encoder: &mut EN,
647        tag: Tag,
648        constraints: Constraints,
649    ) -> Result<(), EN::Error> {
650        encoder.encode_sequence_of(tag, self, constraints).map(drop)
651    }
652}
653
654impl<T: AsnType, V: Encode> Encode for types::Implicit<T, V> {
655    fn encode_with_tag_and_constraints<E: Encoder>(
656        &self,
657        encoder: &mut E,
658        tag: Tag,
659        constraints: Constraints,
660    ) -> Result<(), E::Error> {
661        V::encode_with_tag_and_constraints(&self.value, encoder, tag, constraints).map(drop)
662    }
663}
664
665impl<T: AsnType, V: Encode> Encode for types::Explicit<T, V> {
666    fn encode_with_tag_and_constraints<E: Encoder>(
667        &self,
668        encoder: &mut E,
669        tag: Tag,
670        _: Constraints,
671    ) -> Result<(), E::Error> {
672        encoder.encode_explicit_prefix(tag, &self.value).map(drop)
673    }
674}