rasn/oer/
enc.rs

1use alloc::{string::ToString, vec::Vec};
2
3use crate::oer::ranges;
4use crate::prelude::{
5    Any, BitStr, BmpString, Choice, Constructed, Enumerated, GeneralString, GeneralizedTime,
6    Ia5String, NumericString, PrintableString, SetOf, TeletexString, UtcTime, VisibleString,
7};
8use crate::Codec;
9use bitvec::prelude::*;
10use num_traits::{Signed, ToPrimitive};
11
12use crate::types::{fields::FieldPresence, BitString, Constraints, Integer};
13use crate::{Encode, Tag};
14
15/// ITU-T X.696 (02/2021) version of (C)OER encoding
16/// On this crate, only canonical version will be used to provide unique and reproducible encodings.
17/// Basic-OER is not supported and it might be that never will.
18use crate::error::{CoerEncodeErrorKind, EncodeError, EncodeErrorKind};
19
20pub const ITU_T_X696_OER_EDITION: f32 = 3.0;
21
22/// Options for configuring the [`Encoder`][super::Encoder].
23#[derive(Clone, Copy, Debug)]
24pub struct EncoderOptions {
25    encoding_rules: EncodingRules,
26    set_encoding: bool,
27}
28
29impl EncoderOptions {
30    // Return the default configuration for COER.
31    // We reserve the possibility to use OER in the future by using the rules.
32    #[must_use]
33    pub const fn coer() -> Self {
34        Self {
35            encoding_rules: EncodingRules::Coer,
36            set_encoding: false,
37        }
38    }
39    fn without_set_encoding(mut self) -> Self {
40        self.set_encoding = false;
41        self
42    }
43    #[must_use]
44    fn current_codec(self) -> Codec {
45        match self.encoding_rules {
46            EncodingRules::Oer => Codec::Oer,
47            EncodingRules::Coer => Codec::Coer,
48        }
49    }
50}
51impl Default for EncoderOptions {
52    fn default() -> Self {
53        Self::coer()
54    }
55}
56#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
57pub enum EncodingRules {
58    Oer,
59    Coer,
60}
61
62impl EncodingRules {
63    #[must_use]
64    pub fn is_coer(self) -> bool {
65        matches!(self, Self::Coer)
66    }
67    #[must_use]
68    pub fn is_oer(self) -> bool {
69        matches!(self, Self::Oer)
70    }
71}
72impl Default for Encoder {
73    fn default() -> Self {
74        Self::new(EncoderOptions::coer())
75    }
76}
77/// COER encoder. A subset of OER to provide canonical and unique encoding.  
78#[derive(Debug)]
79pub struct Encoder {
80    options: EncoderOptions,
81    output: Vec<u8>,
82    set_output: alloc::collections::BTreeMap<Tag, Vec<u8>>,
83    field_bitfield: alloc::collections::BTreeMap<Tag, (FieldPresence, bool)>,
84    extension_fields: Vec<Vec<u8>>,
85    is_extension_sequence: bool,
86    parent_output_length: Option<usize>,
87}
88// ITU-T X.696 8.2.1 Only the following constraints are OER-visible:
89// a) non-extensible single value constraints and value range constraints on integer types;
90// b) non-extensible single value constraints on real types where the single value is either plus zero or minus zero or
91// one of the special real values PLUS-INFINITY, MINUS-INFINITY and NOT-A-NUMBER;
92// c) non-extensible size constraints on known-multiplier character string types, octetstring types, and bitstring
93// types;
94// d) non-extensible property settings constraints on the time type or on the useful and defined time types;
95// e) inner type constraints applying OER-visible constraints to real types when used to restrict the mantissa, base,
96// or exponent;
97// f) inner type constraints applied to CHARACTER STRING or EMBEDDED-PDV types when used to restrict
98// the value of the syntaxes component to a single value, or when used to restrict identification to the fixed
99// alternative;
100// g) contained subtype constraints in which the constraining type carries an OER-visible constraint.
101
102// Tags are encoded only as part of the encoding of a choice type, where the tag indicates
103// which alternative of the choice type is the chosen alternative (see 20.1).
104impl Encoder {
105    // pub fn new(options: EncoderOptions) -> Self {
106    #[must_use]
107    pub fn new(options: EncoderOptions) -> Self {
108        Self {
109            options,
110            output: <_>::default(),
111            set_output: <_>::default(),
112            field_bitfield: <_>::default(),
113            extension_fields: <_>::default(),
114            is_extension_sequence: bool::default(),
115            parent_output_length: <_>::default(),
116        }
117    }
118    fn codec(&self) -> Codec {
119        self.options.current_codec()
120    }
121
122    #[must_use]
123    pub fn output(self) -> Vec<u8> {
124        self.options
125            .set_encoding
126            .then(|| {
127                self.set_output
128                    .values()
129                    .flatten()
130                    .copied()
131                    .collect::<Vec<u8>>()
132            })
133            .unwrap_or(self.output)
134    }
135    pub fn set_bit(&mut self, tag: Tag, bit: bool) {
136        self.field_bitfield.entry(tag).and_modify(|(_, b)| *b = bit);
137    }
138    fn extend(&mut self, tag: Tag, bytes: Vec<u8>) -> Result<(), EncodeError> {
139        match self.output.len().checked_add(bytes.len()) {
140            Some(_) => {
141                if self.options.set_encoding {
142                    self.set_output.insert(tag, bytes);
143                } else {
144                    self.output.extend(bytes);
145                }
146            }
147            _ => Err(EncodeError::length_exceeds_platform_size(self.codec()))?,
148        }
149        Ok(())
150    }
151    /// Encode a tag as specified in ITU-T X.696 8.7
152    ///
153    /// Encoding of the tag is only required when encoding a choice type.
154    fn encode_tag(tag: Tag) -> Vec<u8> {
155        use crate::types::Class;
156        let mut bv: BitVec<u8, Msb0> = BitVec::new();
157        // Encode the tag class
158        match tag.class {
159            Class::Universal => bv.extend(&[false, false]),
160            Class::Application => bv.extend(&[false, true]),
161            Class::Context => bv.extend(&[true, false]),
162            Class::Private => bv.extend(&[true, true]),
163        }
164        let mut tag_number = tag.value;
165        // Encode the tag number
166        if tag_number < 63 {
167            for i in (0..6).rev() {
168                bv.push(tag_number & (1 << i) != 0);
169            }
170        } else {
171            bv.extend([true; 6].iter());
172            // Generate the bits for the tag number
173            let mut tag_bits = BitVec::<u8, Msb0>::new();
174            while tag_number > 0 {
175                tag_bits.push(tag_number & 1 != 0);
176                tag_number >>= 1;
177            }
178            // Add leading zeros if needed to make length a multiple of 7
179            while tag_bits.len() % 7 != 0 {
180                tag_bits.push(false);
181            }
182            // Encode the bits in the "big-endian" format, with continuation bits
183            for chunk in tag_bits.chunks(7).rev() {
184                // 8th bit is continuation marker; true for all but the last octet
185                bv.push(true);
186                bv.extend(chunk);
187            }
188            // Correct the 8th bit of the last octet to be false
189            let bv_last_8bit = bv.len() - 8;
190            bv.replace(bv_last_8bit, false);
191            debug_assert!(&bv[2..8].all());
192            debug_assert!(&bv[9..16].any());
193        }
194        bv.into_vec()
195    }
196
197    fn encode_unconstrained_enum_index(
198        &mut self,
199        buffer: &mut Vec<u8>,
200        value: isize,
201    ) -> Result<(), EncodeError> {
202        let bytes =
203            crate::bits::integer_to_bytes(&Integer::from(value), true).ok_or_else(|| {
204                EncodeError::integer_type_conversion_failed(
205                    "Unconstrained enumerated index conversion failed".to_string(),
206                    self.codec(),
207                )
208            })?;
209        let mut length = u8::try_from(bytes.len()).map_err(|err| {
210            EncodeError::integer_type_conversion_failed(
211                alloc::format!(
212                    "Length of length conversion failed when encoding enumerated index.\
213                value likely too large: {err}"
214                ),
215                self.codec(),
216            )
217        })?;
218        if length > 127 {
219            // There seems to be an error in standard. It states that enumerated index can be
220            // between –2^1015 and 2^1015 – 1, but then it limits the amount of subsequent bytes to 127
221            return Err(CoerEncodeErrorKind::TooLongValue {
222                length: bytes.len() as u128,
223            }
224            .into());
225        }
226        // We must swap the first bit to show long form
227        // It is always zero by default with u8 type when value being < 128
228        length |= 0b_1000_0000;
229        buffer.extend(&length.to_be_bytes());
230        buffer.extend(&bytes);
231        Ok(())
232    }
233    /// Encode the length of the value to output.
234    /// `Length` of the data should be provided as full bytes.
235    ///
236    /// COER tries to use the shortest possible encoding and avoids leading zeros.
237    fn encode_length(&mut self, buffer: &mut Vec<u8>, length: usize) -> Result<(), EncodeError> {
238        let bytes =
239            crate::bits::integer_to_bytes(&Integer::from(length), false).ok_or_else(|| {
240                EncodeError::integer_type_conversion_failed(
241                    "For unknown reason, length conversion failed when encoding length".to_string(),
242                    self.codec(),
243                )
244            })?;
245
246        if length < 128 {
247            // First bit should be always zero when below 128: ITU-T X.696 8.6.4
248            buffer.extend(&bytes);
249            return Ok(());
250        }
251        let mut length_of_length = u8::try_from(bytes.len()).map_err(|err| {
252            EncodeError::integer_type_conversion_failed(
253                alloc::format!("Length of length conversion failed: {err}"),
254                self.codec(),
255            )
256        })?;
257        if length_of_length > 127 {
258            return Err(CoerEncodeErrorKind::TooLongValue {
259                length: length as u128,
260            }
261            .into());
262        }
263        // We must swap the first bit to show long form
264        // It is always zero by default with u8 type when value being < 128
265        length_of_length |= 0b_1000_0000;
266        buffer.extend(&length_of_length.to_be_bytes());
267        buffer.extend(&bytes);
268        Ok(())
269    }
270    /// Encode integer `value_to_enc` with length determinant
271    /// Either as signed or unsigned, set by `signed`
272    fn encode_unconstrained_integer(
273        &mut self,
274        value_to_enc: &Integer,
275        signed: bool,
276    ) -> Result<Vec<u8>, EncodeError> {
277        let mut buffer = Vec::new();
278        let bytes = crate::bits::integer_to_bytes(value_to_enc, signed).ok_or_else(|| {
279            EncodeError::integer_type_conversion_failed(
280                "Negative integer value has been provided to be converted into unsigned bytes"
281                    .to_string(),
282                self.codec(),
283            )
284        })?;
285        self.encode_length(&mut buffer, bytes.len())?;
286        buffer.extend(bytes);
287        Ok(buffer)
288    }
289
290    /// Encode an integer value with constraints.
291    ///
292    /// Encoding depends on the range constraint, and has two scenarios.
293    /// a) The effective value constraint has a lower bound, and that lower bound is zero or positive.
294    /// b) The effective value constraint has either a negative lower bound or no lower bound.
295    /// Other integer constraints are OER-invisible.
296    /// Unlike PER, OER does not add an extension bit at the beginning of the encoding of an integer
297    /// type with an extensible OER-visible constraint. Such a type is encoded as an integer type with no bounds.
298    ///
299    /// If the Integer is not bound or outside of range, we encode with the smallest number of octets possible.
300    fn encode_integer_with_constraints(
301        &mut self,
302        tag: Tag,
303        constraints: &Constraints,
304        value_to_enc: &Integer,
305    ) -> Result<(), EncodeError> {
306        let mut buffer = Vec::new();
307
308        if let Some(value) = constraints.value() {
309            if !value.constraint.0.bigint_contains(value_to_enc) && value.extensible.is_none() {
310                return Err(EncodeError::value_constraint_not_satisfied(
311                    value_to_enc.clone(),
312                    &value.constraint.0,
313                    self.codec(),
314                ));
315            }
316            ranges::determine_integer_size_and_sign(
317                &value,
318                value_to_enc,
319                |value_to_enc, sign, octets| -> Result<(), EncodeError> {
320                    let bytes: Vec<u8>;
321                    if let Some(octets) = octets {
322                        bytes = self.encode_constrained_integer_with_padding(
323                            usize::from(octets),
324                            value_to_enc,
325                            sign,
326                        )?;
327                    } else {
328                        bytes = self.encode_unconstrained_integer(value_to_enc, sign)?;
329                    }
330                    buffer.extend(bytes);
331                    Ok(())
332                },
333            )?;
334        } else {
335            let bytes = self.encode_unconstrained_integer(value_to_enc, true)?;
336            buffer.extend(bytes);
337        }
338        self.extend(tag, buffer)?;
339        Ok(())
340    }
341
342    /// When range constraints are present, the integer is encoded as a fixed-size number.
343    /// This means that the zero padding is possible even with COER encoding.
344    fn encode_constrained_integer_with_padding(
345        &mut self,
346        octets: usize,
347        value: &Integer,
348        signed: bool,
349    ) -> Result<Vec<u8>, EncodeError> {
350        use core::cmp::Ordering;
351        if octets > 8 {
352            return Err(CoerEncodeErrorKind::InvalidConstrainedIntegerOctetSize.into());
353        }
354        let bytes = if signed {
355            value.to_signed_bytes_be()
356        } else {
357            value.to_biguint().unwrap().to_bytes_be()
358        };
359        let mut buffer: Vec<u8> = Vec::new();
360
361        match octets.cmp(&bytes.len()) {
362            Ordering::Greater => {
363                if signed && value.is_negative() {
364                    // 2's complement
365                    buffer.extend(core::iter::repeat(0xff).take(octets - bytes.len()));
366                } else {
367                    buffer.extend(core::iter::repeat(0x00).take(octets - bytes.len()));
368                }
369            }
370            Ordering::Less => {
371                return Err(EncodeError::from_kind(
372                    EncodeErrorKind::MoreBytesThanExpected {
373                        value: bytes.len(),
374                        expected: octets,
375                    },
376                    self.codec(),
377                ));
378            }
379            // As is
380            Ordering::Equal => {}
381        };
382        buffer.extend(bytes);
383        Ok(buffer)
384    }
385    fn check_fixed_size_constraint<T>(
386        &self,
387        value: T,
388        length: usize,
389        constraints: &Constraints,
390        mut is_fixed_fn: impl FnMut(T) -> Result<(), EncodeError>,
391    ) -> Result<bool, EncodeError> {
392        if let Some(size) = constraints.size() {
393            if !size.constraint.contains(&length) && size.extensible.is_none() {
394                return Err(EncodeError::size_constraint_not_satisfied(
395                    length,
396                    &size.constraint,
397                    self.codec(),
398                ));
399            }
400            // Encode without length determinant
401            if size.constraint.is_fixed() && size.extensible.is_none() {
402                return match is_fixed_fn(value) {
403                    Ok(()) => Ok(true),
404                    Err(err) => Err(err),
405                };
406            }
407        }
408        // Prior checks before encoding with length determinant
409        let max_permitted_length = usize::MAX / 8; // In compile time, no performance penalty?
410        if length > max_permitted_length {
411            return Err(EncodeError::length_exceeds_platform_size(self.codec()));
412        }
413        Ok(false)
414    }
415
416    fn output_length(&self) -> usize {
417        let mut output_length = self.output.len();
418        output_length += usize::from(self.is_extension_sequence);
419        output_length += self
420            .field_bitfield
421            .values()
422            .filter(|(presence, _)| presence.is_optional_or_default())
423            .count();
424        output_length += self.parent_output_length.unwrap_or_default();
425
426        if self.options.set_encoding {
427            output_length += self.set_output.values().map(Vec::len).sum::<usize>();
428        }
429        output_length
430    }
431    fn new_set_encoder<C: Constructed>(&self) -> Self {
432        let mut options = self.options;
433        options.set_encoding = true;
434        let mut encoder = Self::new(options);
435        encoder.field_bitfield = C::FIELDS
436            .canonised()
437            .iter()
438            .map(|field| (field.tag_tree.smallest_tag(), (field.presence, false)))
439            .collect();
440        encoder.parent_output_length = Some(self.output_length());
441        encoder
442    }
443
444    fn new_sequence_encoder<C: Constructed>(&self) -> Self {
445        let mut encoder = Self::new(self.options.without_set_encoding());
446        encoder.field_bitfield = C::FIELDS
447            .iter()
448            .map(|field| (field.tag_tree.smallest_tag(), (field.presence, false)))
449            .collect();
450        encoder.parent_output_length = Some(self.output_length());
451        encoder
452    }
453    fn encoded_extension_addition(extension_fields: &[Vec<u8>]) -> bool {
454        !extension_fields.iter().all(Vec::is_empty)
455    }
456    fn encode_constructed<C: Constructed>(
457        &mut self,
458        tag: Tag,
459        mut encoder: Self,
460    ) -> Result<(), EncodeError> {
461        self.set_bit(tag, true);
462        let mut buffer = Vec::new();
463        let mut preamble = BitString::default();
464        // ### PREAMBLE ###
465        // Section 16.2.2
466        let extensions_defined = C::EXTENDED_FIELDS.is_some();
467        let mut extensions_present = false;
468        if extensions_defined {
469            extensions_present = Self::encoded_extension_addition(&encoder.extension_fields);
470            preamble.push(extensions_present);
471        }
472        // Section 16.2.3
473        if C::FIELDS.number_of_optional_and_default_fields() > 0 {
474            for bit in encoder
475                .field_bitfield
476                .values()
477                .filter_map(|(presence, is_present)| {
478                    presence.is_optional_or_default().then_some(is_present)
479                })
480                .copied()
481            {
482                preamble.push(bit);
483            }
484        }
485        // 16.2.4 - fill missing bits from full octet with zeros
486        if preamble.len() % 8 != 0 {
487            preamble.extend(BitString::repeat(false, 8 - preamble.len() % 8));
488        }
489        debug_assert!(preamble.len() % 8 == 0);
490        buffer.extend(crate::bits::to_vec(&preamble));
491        // Section 16.3 ### Encodings of the components in the extension root ###
492        // Must copy before move...
493        let extension_fields = core::mem::take(&mut encoder.extension_fields);
494        if encoder.field_bitfield.values().any(|(_, b)| *b) {
495            buffer.extend(encoder.output());
496        }
497        if !extensions_defined || !extensions_present {
498            self.extend(tag, buffer)?;
499            return Ok(());
500        }
501        // Section 16.4 ### Extension addition presence bitmap ###
502        let bitfield_length = extension_fields.len();
503        let mut extension_bitmap_buffer = BitString::new();
504        #[allow(clippy::cast_possible_truncation)]
505        let missing_bits: u8 = if bitfield_length > 0 {
506            (8u8 - (bitfield_length % 8) as u8) % 8
507        } else {
508            0
509        };
510        debug_assert!((bitfield_length + 8 + missing_bits as usize) % 8 == 0);
511        self.encode_length(
512            &mut buffer,
513            (8 + bitfield_length + missing_bits as usize) / 8,
514        )?;
515        extension_bitmap_buffer.extend(missing_bits.to_be_bytes());
516        for field in &extension_fields {
517            extension_bitmap_buffer.push(!field.is_empty());
518        }
519        extension_bitmap_buffer.extend(BitString::repeat(false, missing_bits as usize));
520        debug_assert!(extension_bitmap_buffer.len() % 8 == 0);
521        buffer.extend(crate::bits::to_vec(&extension_bitmap_buffer));
522        // Section 16.5 # Encodings of the components in the extension addition group, as open type
523        for field in extension_fields
524            .into_iter()
525            .filter(|field| !field.is_empty())
526        {
527            self.encode_length(&mut buffer, field.len())?;
528            buffer.extend(field);
529        }
530        self.extend(tag, buffer)?;
531        Ok(())
532    }
533}
534
535impl crate::Encoder for Encoder {
536    type Ok = ();
537    type Error = EncodeError;
538
539    fn codec(&self) -> Codec {
540        self.options.current_codec()
541    }
542
543    fn encode_any(&mut self, tag: Tag, value: &Any) -> Result<Self::Ok, Self::Error> {
544        self.set_bit(tag, true);
545        self.encode_octet_string(tag, <Constraints>::default(), &value.contents)
546    }
547
548    /// ITU-T X.696 9.
549    /// False is encoded as a single zero octet. In COER, true is always encoded as 0xFF.
550    /// In Basic-OER, any non-zero octet value represents true, but we support only canonical encoding.
551    fn encode_bool(&mut self, tag: Tag, value: bool) -> Result<Self::Ok, Self::Error> {
552        self.set_bit(tag, true);
553        self.extend(tag, alloc::vec![if value { 0xffu8 } else { 0x00u8 }])?;
554        Ok(())
555    }
556
557    fn encode_bit_string(
558        &mut self,
559        tag: Tag,
560        constraints: Constraints,
561        value: &BitStr,
562    ) -> Result<Self::Ok, Self::Error> {
563        // TODO When Rec. ITU-T X.680 | ISO/IEC 8824-1, 22.7 applies (i.e., the bitstring type is defined with a
564        // "NamedBitList"), the bitstring value shall be encoded with trailing 0 bits added or removed as necessary to satisfy the
565        // effective size constraint.
566        // Rasn does not currently support NamedBitList
567        self.set_bit(tag, true);
568        let mut buffer: Vec<u8> = Vec::new();
569        let mut bit_string_encoding = BitVec::<u8, Msb0>::new();
570
571        if let Some(size) = constraints.size() {
572            // Constraints apply only if the lower and upper bounds
573            // of the effective size constraint are identical (13.1)
574            if size.constraint.is_fixed() && size.extensible.is_none() {
575                //  Series of octets will be empty, allowed as 13.2.3,
576                // but this seems impossible to implement for decoder so not supported
577                // Can't say if this is an error in standard or not when not handling NamedBitList
578                // if value.is_empty() {
579                // } else
580                if size.constraint.contains(&value.len()) {
581                    let missing_bits: usize = (8 - value.len() % 8) % 8;
582                    let trailing = BitVec::<u8, Msb0>::repeat(false, missing_bits);
583                    if missing_bits > 0 {
584                        bit_string_encoding.extend(value);
585                        bit_string_encoding.extend(trailing);
586                    } else {
587                        bit_string_encoding.extend(value);
588                    }
589                    buffer.extend(crate::bits::to_vec(&bit_string_encoding));
590                } else {
591                    return Err(EncodeError::size_constraint_not_satisfied(
592                        value.len(),
593                        &size.constraint,
594                        self.codec(),
595                    ));
596                }
597                self.extend(tag, buffer)?;
598                return Ok(());
599            }
600        }
601
602        // If the BitString is empty, length is one and initial octet is zero
603        if value.is_empty() {
604            self.encode_length(&mut buffer, 1)?;
605            buffer.extend(&[0x00u8]);
606        } else {
607            // TODO 22.7 X.680, NamedBitString and COER
608            // if self.options.encoding_rules.is_coer()
609            //     && value.trailing_zeros() > 7
610            // {
611            //     if value.first_one().is_some() {
612            //         // In COER, we strip trailing zeros if they take full octets
613            //         let trimmed_value = &value[..(value.len() - value.trailing_zeros() - 1)];
614            //     }
615            //     else {  }
616            // }
617            // With length determinant
618            let missing_bits: usize = (8 - value.len() % 8) % 8;
619            let trailing = BitVec::<u8, Msb0>::repeat(false, missing_bits);
620            // missing bits never > 8
621            bit_string_encoding.extend(missing_bits.to_u8().unwrap_or(0).to_be_bytes());
622            bit_string_encoding.extend(value);
623            bit_string_encoding.extend(trailing);
624            self.encode_length(&mut buffer, bit_string_encoding.len() / 8)?;
625            buffer.extend(crate::bits::to_vec(&bit_string_encoding));
626        }
627        self.extend(tag, buffer)?;
628        Ok(())
629    }
630
631    fn encode_enumerated<E: Enumerated>(
632        &mut self,
633        tag: Tag,
634        value: &E,
635    ) -> Result<Self::Ok, Self::Error> {
636        // 11.5 The presence of an extension marker in the definition of an enumerated type does not affect the encoding of
637        // the values of the enumerated type.
638        // max size for enumerated value is currently only isize MIN/MAX
639        // Spec allows between –2^1015 and 2^1015 – 1
640        self.set_bit(tag, true);
641        let number = value.discriminant();
642        let mut buffer = Vec::new();
643        if 0isize <= number && number <= i8::MAX.into() {
644            let bytes = self.encode_constrained_integer_with_padding(1, &number.into(), false)?;
645            buffer.extend(bytes);
646        } else {
647            // Value is signed here as defined in section 11.4
648            // Long form but different from regular length determinant encoding
649            self.encode_unconstrained_enum_index(&mut buffer, number)?;
650        }
651        self.extend(tag, buffer)?;
652        Ok(())
653    }
654
655    fn encode_object_identifier(
656        &mut self,
657        tag: Tag,
658        value: &[u32],
659    ) -> Result<Self::Ok, Self::Error> {
660        self.set_bit(tag, true);
661        let mut enc = crate::ber::enc::Encoder::new(crate::ber::enc::EncoderOptions::ber());
662        let octets = enc.object_identifier_as_bytes(value)?;
663        let mut buffer = Vec::new();
664        self.encode_length(&mut buffer, octets.len())?;
665        buffer.extend(&octets);
666        self.extend(tag, buffer)?;
667        Ok(())
668    }
669
670    fn encode_integer(
671        &mut self,
672        tag: Tag,
673        constraints: Constraints,
674        value: &Integer,
675    ) -> Result<Self::Ok, Self::Error> {
676        self.set_bit(tag, true);
677        self.encode_integer_with_constraints(tag, &constraints, value)
678    }
679
680    fn encode_null(&mut self, tag: Tag) -> Result<Self::Ok, Self::Error> {
681        self.set_bit(tag, true);
682        Ok(())
683    }
684
685    fn encode_octet_string(
686        &mut self,
687        tag: Tag,
688        constraints: Constraints,
689        value: &[u8],
690    ) -> Result<Self::Ok, Self::Error> {
691        self.set_bit(tag, true);
692        let mut buffer = Vec::new();
693        let fixed_size_encode = |value: &[u8]| {
694            buffer.extend(value);
695            Ok(())
696        };
697        if !self.check_fixed_size_constraint(value, value.len(), &constraints, fixed_size_encode)? {
698            // Use length determinant on other cases
699            self.encode_length(&mut buffer, value.len())?;
700            buffer.extend(value);
701        }
702        self.extend(tag, buffer)?;
703        Ok(())
704    }
705
706    fn encode_general_string(
707        &mut self,
708        tag: Tag,
709        constraints: Constraints,
710        value: &GeneralString,
711    ) -> Result<Self::Ok, Self::Error> {
712        // Seems like it can be encoded as it is...
713        self.set_bit(tag, true);
714        self.encode_octet_string(tag, constraints, value)
715    }
716
717    fn encode_utf8_string(
718        &mut self,
719        tag: Tag,
720        constraints: Constraints,
721        value: &str,
722    ) -> Result<Self::Ok, Self::Error> {
723        self.set_bit(tag, true);
724        self.encode_octet_string(tag, constraints, value.as_bytes())
725    }
726
727    fn encode_visible_string(
728        &mut self,
729        tag: Tag,
730        constraints: Constraints,
731        value: &VisibleString,
732    ) -> Result<Self::Ok, Self::Error> {
733        self.set_bit(tag, true);
734        self.encode_octet_string(tag, constraints, value.as_iso646_bytes())
735    }
736
737    fn encode_ia5_string(
738        &mut self,
739        tag: Tag,
740        constraints: Constraints,
741        value: &Ia5String,
742    ) -> Result<Self::Ok, Self::Error> {
743        self.set_bit(tag, true);
744        self.encode_octet_string(tag, constraints, value.as_iso646_bytes())
745    }
746
747    fn encode_printable_string(
748        &mut self,
749        tag: Tag,
750        constraints: Constraints,
751        value: &PrintableString,
752    ) -> Result<Self::Ok, Self::Error> {
753        self.set_bit(tag, true);
754        self.encode_octet_string(tag, constraints, value.as_bytes())
755    }
756
757    fn encode_numeric_string(
758        &mut self,
759        tag: Tag,
760        constraints: Constraints,
761        value: &NumericString,
762    ) -> Result<Self::Ok, Self::Error> {
763        self.set_bit(tag, true);
764        self.encode_octet_string(tag, constraints, value.as_bytes())
765    }
766
767    fn encode_teletex_string(
768        &mut self,
769        tag: Tag,
770        constraints: Constraints,
771        value: &TeletexString,
772    ) -> Result<Self::Ok, Self::Error> {
773        // X.690 8.23.5
774        // TODO the octets specified in ISO/IEC 2022 for encodings in an 8-bit environment, using
775        // the escape sequence and character codings registered in accordance with ISO/IEC 2375.
776        self.set_bit(tag, true);
777        self.encode_octet_string(tag, constraints, value)
778    }
779
780    fn encode_bmp_string(
781        &mut self,
782        tag: Tag,
783        constraints: Constraints,
784        value: &BmpString,
785    ) -> Result<Self::Ok, Self::Error> {
786        self.set_bit(tag, true);
787        self.encode_octet_string(tag, constraints, &value.to_bytes())
788    }
789
790    fn encode_generalized_time(
791        &mut self,
792        tag: Tag,
793        value: &GeneralizedTime,
794    ) -> Result<Self::Ok, Self::Error> {
795        self.set_bit(tag, true);
796        self.encode_octet_string(
797            tag,
798            Constraints::default(),
799            &crate::der::enc::Encoder::datetime_to_canonical_generalized_time_bytes(value),
800        )
801    }
802
803    fn encode_utc_time(&mut self, tag: Tag, value: &UtcTime) -> Result<Self::Ok, Self::Error> {
804        self.set_bit(tag, true);
805        self.encode_octet_string(
806            tag,
807            Constraints::default(),
808            &crate::der::enc::Encoder::datetime_to_canonical_utc_time_bytes(value),
809        )
810    }
811
812    fn encode_explicit_prefix<V: Encode>(
813        &mut self,
814        tag: Tag,
815        value: &V,
816    ) -> Result<Self::Ok, Self::Error> {
817        if let Some((_, true)) = self.field_bitfield.get(&tag) {
818            value.encode(self)
819        } else if !self.field_bitfield.contains_key(&tag) {
820            value.encode(self)
821        } else {
822            self.set_bit(tag, true);
823            value.encode_with_tag(self, tag)
824        }
825    }
826
827    fn encode_sequence<C, F>(&mut self, tag: Tag, encoder_scope: F) -> Result<Self::Ok, Self::Error>
828    where
829        C: Constructed,
830        F: FnOnce(&mut Self) -> Result<(), Self::Error>,
831    {
832        let mut encoder = self.new_sequence_encoder::<C>();
833        encoder_scope(&mut encoder)?;
834        self.encode_constructed::<C>(tag, encoder)
835    }
836
837    fn encode_sequence_of<E: Encode>(
838        &mut self,
839        tag: Tag,
840        value: &[E],
841        _: Constraints,
842    ) -> Result<Self::Ok, Self::Error> {
843        // It seems that constraints here are not C/OER visible? No mention in standard...
844        self.set_bit(tag, true);
845        let mut buffer = Vec::new();
846        let value_len_bytes = self.encode_unconstrained_integer(&value.len().into(), false)?;
847        buffer.extend(value_len_bytes);
848        for one in value {
849            let mut encoder = Self::new(self.options);
850            E::encode(one, &mut encoder)?;
851            buffer.extend(encoder.output());
852        }
853        self.extend(tag, buffer)?;
854        Ok(())
855    }
856
857    fn encode_set<C, F>(&mut self, tag: Tag, encoder_scope: F) -> Result<Self::Ok, Self::Error>
858    where
859        C: Constructed,
860        F: FnOnce(&mut Self) -> Result<(), Self::Error>,
861    {
862        let mut set = self.new_set_encoder::<C>();
863        encoder_scope(&mut set)?;
864        self.encode_constructed::<C>(tag, set)
865    }
866
867    fn encode_set_of<E: Encode>(
868        &mut self,
869        tag: Tag,
870        value: &SetOf<E>,
871        constraints: Constraints,
872    ) -> Result<Self::Ok, Self::Error> {
873        self.encode_sequence_of(tag, &value.iter().collect::<Vec<_>>(), constraints)
874    }
875
876    fn encode_some<E: Encode>(&mut self, value: &E) -> Result<Self::Ok, Self::Error> {
877        self.set_bit(E::TAG, true);
878        value.encode(self)
879    }
880
881    fn encode_some_with_tag_and_constraints<E: Encode>(
882        &mut self,
883        tag: Tag,
884        constraints: Constraints,
885        value: &E,
886    ) -> Result<Self::Ok, Self::Error> {
887        self.set_bit(tag, true);
888        value.encode_with_tag_and_constraints(self, tag, constraints)
889    }
890
891    fn encode_none<E: Encode>(&mut self) -> Result<Self::Ok, Self::Error> {
892        self.set_bit(E::TAG, false);
893        Ok(())
894    }
895
896    fn encode_none_with_tag(&mut self, tag: Tag) -> Result<Self::Ok, Self::Error> {
897        self.set_bit(tag, false);
898        Ok(())
899    }
900
901    fn encode_choice<E: Encode + Choice>(
902        &mut self,
903        _: Constraints,
904        _tag: Tag,
905        encode_fn: impl FnOnce(&mut Self) -> Result<Tag, Self::Error>,
906    ) -> Result<Self::Ok, Self::Error> {
907        let mut choice_encoder = Self::new(self.options.without_set_encoding());
908        let tag = encode_fn(&mut choice_encoder)?;
909        let is_root_extension = crate::TagTree::tag_contains(&tag, E::VARIANTS);
910        let tag_bytes: Vec<u8> = Self::encode_tag(tag);
911        let mut buffer = Vec::new();
912        buffer.extend(tag_bytes);
913        if is_root_extension {
914            buffer.extend(choice_encoder.output);
915        } else {
916            self.encode_length(&mut buffer, choice_encoder.output.len())?;
917            buffer.extend(choice_encoder.output);
918        }
919        self.extend(tag, buffer)?;
920        Ok(())
921    }
922    fn encode_extension_addition<E: Encode>(
923        &mut self,
924        tag: Tag,
925        constraints: Constraints,
926        value: E,
927    ) -> Result<Self::Ok, Self::Error> {
928        let mut encoder = Self::new(self.options.without_set_encoding());
929        encoder.field_bitfield = <_>::from([(tag, (FieldPresence::Optional, false))]);
930        E::encode_with_tag_and_constraints(&value, &mut encoder, tag, constraints)?;
931
932        if encoder.field_bitfield.get(&tag).map_or(false, |(_, b)| *b) {
933            self.set_bit(tag, true);
934            self.extension_fields.push(encoder.output());
935        } else {
936            self.set_bit(tag, false);
937            self.extension_fields.push(Vec::new());
938        }
939
940        Ok(())
941    }
942    fn encode_extension_addition_group<E>(
943        &mut self,
944        value: Option<&E>,
945    ) -> Result<Self::Ok, Self::Error>
946    where
947        E: Encode + Constructed,
948    {
949        let Some(value) = value else {
950            self.set_bit(E::TAG, false);
951            self.extension_fields.push(Vec::new());
952            return Ok(());
953        };
954        self.set_bit(E::TAG, true);
955        let mut encoder = self.new_sequence_encoder::<E>();
956        encoder.is_extension_sequence = true;
957        value.encode(&mut encoder)?;
958
959        let output = encoder.output();
960        self.extension_fields.push(output);
961        Ok(())
962    }
963}
964
965#[cfg(test)]
966mod tests {
967    use num_bigint::BigInt;
968
969    use super::*;
970    use crate::prelude::{AsnType, Decode, Encode};
971    use crate::types::constraints::{Bounded, Constraint, Extensible, Value};
972
973    #[test]
974    fn test_encode_bool() {
975        let output = crate::coer::encode(&true).unwrap();
976        let bv = BitVec::<u8, Msb0>::from_slice(&[0xffu8]);
977        assert_eq!(output, bv.as_raw_slice());
978        let output = crate::coer::encode(&false).unwrap();
979        let bv = BitVec::<u8, Msb0>::from_slice(&[0x00u8]);
980        assert_eq!(output, bv.as_raw_slice());
981        let decoded = crate::coer::encode(&true).unwrap();
982        assert_eq!(decoded, &[0xffu8]);
983        let decoded = crate::coer::encode(&false).unwrap();
984        assert_eq!(decoded, &[0x0]);
985    }
986    #[test]
987    fn test_encode_integer_manual_setup() {
988        let range_bound = Bounded::<i128>::Range {
989            start: 0.into(),
990            end: 255.into(),
991        };
992        let value_range = &[Constraint::Value(Extensible::new(Value::new(range_bound)))];
993        let consts = Constraints::new(value_range);
994        let mut encoder = Encoder::default();
995        let result =
996            encoder.encode_integer_with_constraints(Tag::INTEGER, &consts, &BigInt::from(244));
997        assert!(result.is_ok());
998        let v = vec![244u8];
999        assert_eq!(encoder.output, v);
1000        encoder.output.clear();
1001        let value = BigInt::from(256);
1002        let result = encoder.encode_integer_with_constraints(Tag::INTEGER, &consts, &value);
1003        assert!(result.is_err());
1004    }
1005    #[test]
1006    fn test_integer_with_length_determinant() {
1007        // Using defaults, no limits
1008        let constraints = Constraints::default();
1009        let mut encoder = Encoder::default();
1010        let result =
1011            encoder.encode_integer_with_constraints(Tag::INTEGER, &constraints, &BigInt::from(244));
1012        assert!(result.is_ok());
1013        let v = vec![2u8, 0, 244];
1014        assert_eq!(encoder.output, v);
1015        encoder.output.clear();
1016        let result = encoder.encode_integer_with_constraints(
1017            Tag::INTEGER,
1018            &constraints,
1019            &BigInt::from(-1_234_567),
1020        );
1021        assert!(result.is_ok());
1022        let v = vec![0x03u8, 0xED, 0x29, 0x79];
1023        assert_eq!(encoder.output, v);
1024    }
1025    #[test]
1026    fn test_large_lengths() {
1027        let constraints = Constraints::default();
1028        let mut encoder = Encoder::default();
1029
1030        // Signed integer with byte length of 128
1031        // Needs long form to represent
1032        let number = BigInt::from(256).pow(127) - 1;
1033        let result = encoder.encode_integer_with_constraints(Tag::INTEGER, &constraints, &number);
1034        assert!(result.is_ok());
1035        let vc = [
1036            0x81, 0x80, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1037            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1038            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1039            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1040            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1041            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1042            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1043            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1044            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1045            0xff, 0xff, 0xff, 0xff,
1046        ];
1047        assert_eq!(encoder.output(), vc);
1048    }
1049    #[test]
1050    fn test_choice() {
1051        use crate as rasn;
1052        #[derive(AsnType, Decode, Debug, Encode, PartialEq)]
1053        #[rasn(choice, automatic_tags)]
1054        #[non_exhaustive]
1055        enum Choice {
1056            Normal(Integer),
1057            High(Integer),
1058            #[rasn(extension_addition)]
1059            Medium(Integer),
1060        }
1061        let mut encoder = Encoder::default();
1062
1063        let choice = Choice::Normal(333.into());
1064        choice.encode(&mut encoder).unwrap();
1065
1066        assert_eq!(encoder.output(), &[128, 2, 1, 77]);
1067    }
1068}