1use alloc::vec::Vec;
4use bitvec::prelude::*;
5use num_traits::ToPrimitive;
6
7use crate::{
8 oer::EncodingRules,
9 types::{
10 Any, BitStr, BmpString, Choice, Constraints, Constructed, Date, Enumerated, GeneralString,
11 GeneralizedTime, GraphicString, Ia5String, Identifier, IntegerType, NumericString,
12 PrintableString, RealType, SetOf, Tag, TeletexString, UtcTime, VisibleString,
13 },
14 Codec, Encode,
15};
16
17use crate::error::{CoerEncodeErrorKind, EncodeError, EncodeErrorKind};
21
22pub const ITU_T_X696_OER_EDITION: f32 = 3.0;
24
25#[derive(Clone, Copy, Debug)]
27pub struct EncoderOptions {
28 encoding_rules: EncodingRules,
29 set_encoding: bool,
30}
31
32impl EncoderOptions {
33 #[must_use]
35 pub const fn coer() -> Self {
36 Self {
37 encoding_rules: EncodingRules::Coer,
38 set_encoding: false,
39 }
40 }
41 fn without_set_encoding(mut self) -> Self {
42 self.set_encoding = false;
43 self
44 }
45 #[must_use]
46 fn current_codec(self) -> Codec {
47 match self.encoding_rules {
48 EncodingRules::Oer => Codec::Oer,
49 EncodingRules::Coer => Codec::Coer,
50 }
51 }
52}
53
54impl Default for EncoderOptions {
55 fn default() -> Self {
56 Self::coer()
57 }
58}
59
60#[derive(Debug, Clone, Copy)]
64struct ConstructedCursor<const RC: usize, const EC: usize> {
65 number_optional_default: usize,
66 preamble_width: usize,
67 preamble_cursor: usize,
68 extension_missing_bits: u8,
69 extension_bitfield_width: usize,
70 extension_bitmap_width: usize,
71 extension_bitmap_total_width: usize,
72 extension_bitmap_cursor: usize,
73}
74
75impl<const RC: usize, const EC: usize> ConstructedCursor<RC, EC> {
76 const fn new(number_optional_default: usize, is_extensible: bool) -> Self {
78 let preamble_missing_bits =
79 (8 - ((is_extensible as usize + number_optional_default) & 7)) & 7;
80 debug_assert!(
81 (preamble_missing_bits + is_extensible as usize + number_optional_default)
82 .is_multiple_of(8)
83 );
84 let preamble_width =
85 (number_optional_default + is_extensible as usize + preamble_missing_bits) / 8;
86 let extension_missing_bits: u8 =
87 ((EC > 0) as u8).wrapping_neg() & ((8 - (EC & 7) as u8) & 7);
88 debug_assert!((EC + extension_missing_bits as usize).is_multiple_of(8));
89 let extension_bitfield_width = (EC + extension_missing_bits as usize) / 8;
90 let extension_bitmap_width = 1 + extension_bitfield_width;
91 let extension_bitmap_width_length = if extension_bitmap_width <= 127 {
92 1 } else {
94 1 + (extension_bitmap_width as u32).ilog2().div_ceil(8) as usize };
96 let extension_bitmap_total_width = extension_bitmap_width + extension_bitmap_width_length;
97 Self {
98 number_optional_default,
99 preamble_width,
100 preamble_cursor: 0,
101 extension_missing_bits,
102 extension_bitfield_width,
103 extension_bitmap_width,
104 extension_bitmap_total_width,
105 extension_bitmap_cursor: 0,
106 }
107 }
108 fn set_extension_bitmap_cursor(&mut self, cursor: usize) {
109 self.extension_bitmap_cursor = cursor;
110 }
111 fn set_preamble_cursor(&mut self, cursor: usize) {
112 self.preamble_cursor = cursor;
113 }
114 const fn default() -> Self {
115 Self {
116 number_optional_default: 0,
117 preamble_width: 0,
118 preamble_cursor: 0,
119 extension_bitfield_width: 0,
120 extension_bitmap_width: 0,
121 extension_missing_bits: 0,
122 extension_bitmap_total_width: 0,
123 extension_bitmap_cursor: 0,
124 }
125 }
126}
127
128#[derive(Debug)]
133pub struct Encoder<'buffer, const RCL: usize = 0, const ECL: usize = 0> {
134 options: EncoderOptions,
135 output: &'buffer mut Vec<u8>,
136 set_output: alloc::collections::BTreeMap<Tag, Vec<u8>>,
137 is_extension_sequence: bool,
138 root_bitfield: (usize, [(bool, Tag); RCL]),
139 extension_bitfield: (usize, [bool; ECL]),
140 cursor: ConstructedCursor<RCL, ECL>,
142 worker: &'buffer mut Vec<u8>,
145}
146
147impl<'buffer, const RCL: usize, const ECL: usize> Encoder<'buffer, RCL, ECL> {
164 #[must_use]
165 pub fn from_buffer(
167 options: EncoderOptions,
168 output: &'buffer mut Vec<u8>,
169 worker: &'buffer mut Vec<u8>,
170 ) -> Self {
171 Self {
172 options,
173 output,
174 set_output: <_>::default(),
175 root_bitfield: (0, [(false, Tag::new_private(0)); RCL]),
176 extension_bitfield: (0, [false; ECL]),
177 cursor: ConstructedCursor::default(),
178 is_extension_sequence: bool::default(),
179 worker,
180 }
181 }
182
183 fn codec(&self) -> Codec {
184 self.options.current_codec()
185 }
186
187 #[must_use]
189 pub fn output(&mut self) -> Vec<u8> {
190 core::mem::take(self.output)
191 }
192
193 fn collect_set(&mut self) {
195 self.output.append(
196 self.set_output
197 .values()
198 .flatten()
199 .copied()
200 .collect::<Vec<u8>>()
201 .as_mut(),
202 );
203 }
204
205 fn set_presence(&mut self, tag: Tag, bit: bool) {
208 if RCL > 0 {
211 if self.cursor.number_optional_default < self.root_bitfield.0 + 1 {
212 return;
216 }
217 self.root_bitfield.1[self.root_bitfield.0] = (bit, tag);
218 self.root_bitfield.0 += 1;
219 }
220 }
221 fn set_extension_presence(&mut self, bit: bool) {
222 if ECL > 0 {
225 self.extension_bitfield.1[self.extension_bitfield.0] = bit;
226 self.extension_bitfield.0 += 1;
227 }
228 }
229 fn extend(&mut self, tag: Tag) {
230 if self.options.set_encoding {
231 self.set_output.insert(tag, core::mem::take(self.output));
233 }
234 }
235 fn encode_tag(&self, tag: Tag, bv: &mut BitSlice<u8, Msb0>) -> usize {
239 use crate::types::Class;
240 let mut index = 0;
242 match tag.class {
243 Class::Universal => {
244 bv.set(index, false);
245 bv.set(index + 1, false);
246 index += 2;
247 }
248 Class::Application => {
249 bv.set(index, false);
250 bv.set(index + 1, true);
251 index += 2;
252 }
253 Class::Context => {
254 bv.set(index, true);
255 bv.set(index + 1, false);
256 index += 2;
257 }
258 Class::Private => {
259 bv.set(index, true);
260 bv.set(index + 1, true);
261 index += 2;
262 }
263 }
264 let mut tag_number = tag.value;
265 if tag_number < 63 {
267 for i in (0..6).rev() {
268 bv.set(index, tag_number & (1 << i) != 0);
269 index += 1;
270 }
271 } else {
272 for i in 0..6 {
273 bv.set(index + i, true);
274 }
275 index += 6;
276 let mut tag_number_bits = 0;
278 let mut temp_tag_number = tag_number;
279 while temp_tag_number > 0 {
280 temp_tag_number >>= 1;
281 tag_number_bits += 1;
282 }
283 let mut remainer = 7 - tag_number_bits % 7;
284 bv.set(index, true);
286 index += 1;
287 for _ in 0..7 {
289 if remainer != 0 {
290 bv.set(index, false);
291 index += 1;
292 remainer -= 1;
293 continue;
294 }
295 bv.set(index, tag_number & 1 != 0);
296 tag_number >>= 1;
297 index += 1;
298 }
299 while tag_number > 0 {
300 bv.set(index, true);
302 index += 1;
303 for _ in 0..7 {
304 bv.set(index, tag_number & 1 != 0);
305 tag_number >>= 1;
306 index += 1;
307 }
308 }
309 let bv_last_8bit = &bv[..index].len() - 8;
311 bv.replace(bv_last_8bit, false);
312 debug_assert!(&bv[2..8].all());
313 debug_assert!(&bv[9..16].any());
314 }
315 index
316 }
317
318 fn encode_unconstrained_enum_index(&mut self, value: isize) -> Result<(), EncodeError> {
319 let (bytes, needed) = value.to_signed_bytes_be();
320 let mut length = u8::try_from(needed).map_err(|err| {
321 EncodeError::integer_type_conversion_failed(
322 alloc::format!(
323 "Length of length conversion failed when encoding enumerated index.\
324 value likely too large: {err}"
325 ),
326 self.codec(),
327 )
328 })?;
329 if length > 127 {
330 return Err(CoerEncodeErrorKind::TooLongValue {
333 length: needed as u128,
334 }
335 .into());
336 }
337 length |= 0b_1000_0000;
340 self.output.extend_from_slice(&length.to_be_bytes());
341 self.output.extend_from_slice(&bytes.as_ref()[..needed]);
342 Ok(())
343 }
344 fn encode_length(buffer: &mut Vec<u8>, length: usize) -> Result<(), EncodeError> {
349 let (bytes, needed) = length.to_unsigned_bytes_be();
350 if length < 128 {
351 buffer.extend_from_slice(&bytes.as_ref()[..needed]);
353 return Ok(());
354 }
355 let mut length_of_length = u8::try_from(needed).map_err(|err| {
356 EncodeError::integer_type_conversion_failed(
357 alloc::format!("Length of length conversion failed: {err}"),
358 Codec::Coer,
359 )
360 })?;
361 if length_of_length > 127 {
362 return Err(CoerEncodeErrorKind::TooLongValue {
363 length: length as u128,
364 }
365 .into());
366 }
367 length_of_length |= 0b_1000_0000;
370 buffer.extend_from_slice(&length_of_length.to_be_bytes());
371 buffer.extend_from_slice(&bytes.as_ref()[..needed]);
372 Ok(())
373 }
374 fn encode_unconstrained_integer<I: IntegerType>(
377 &mut self,
378 value_to_enc: &I,
379 signed: bool,
380 ) -> Result<(), EncodeError> {
381 if signed {
382 let (bytes, needed) = value_to_enc.to_signed_bytes_be();
383 Self::encode_length(self.output, needed)?;
384 self.output.extend_from_slice(&bytes.as_ref()[..needed]);
385 } else {
386 let (bytes, needed) = value_to_enc.to_unsigned_bytes_be();
387 Self::encode_length(self.output, needed)?;
388 self.output.extend_from_slice(&bytes.as_ref()[..needed]);
389 };
390 Ok(())
391 }
392
393 fn encode_integer_with_constraints<I: IntegerType>(
404 &mut self,
405 tag: Tag,
406 constraints: &Constraints,
407 value_to_enc: &I,
408 ) -> Result<(), EncodeError> {
409 if let Some(value) = constraints.value() {
410 if !value.constraint.value.in_bound(value_to_enc) && value.extensible.is_none() {
411 return Err(EncodeError::value_constraint_not_satisfied(
412 value_to_enc.to_bigint().unwrap_or_default(),
413 &value.constraint.value,
414 self.codec(),
415 ));
416 }
417 let (signed, octets) = if value.extensible.is_some() {
418 (true, None)
419 } else {
420 (value.constraint.get_sign(), value.constraint.get_range())
421 };
422 if let Some(octets) = octets {
423 self.encode_constrained_integer_with_padding(
424 usize::from(octets),
425 value_to_enc,
426 signed,
427 )?;
428 } else {
429 self.encode_unconstrained_integer(value_to_enc, signed)?;
430 }
431 } else {
432 self.encode_unconstrained_integer(value_to_enc, true)?;
433 }
434 self.extend(tag);
435 Ok(())
436 }
437
438 fn encode_constrained_integer_with_padding<I: IntegerType>(
441 &mut self,
442 octets: usize,
443 value: &I,
444 signed: bool,
445 ) -> Result<(), EncodeError> {
446 use core::cmp::Ordering;
447 if octets > 8 {
448 return Err(CoerEncodeErrorKind::InvalidConstrainedIntegerOctetSize.into());
449 }
450 let signed_ref;
451 let unsigned_ref;
452 let needed: usize;
453 let bytes = if signed {
454 (signed_ref, needed) = value.to_signed_bytes_be();
455 signed_ref.as_ref()
456 } else {
457 (unsigned_ref, needed) = value.to_unsigned_bytes_be();
458 unsigned_ref.as_ref()
459 };
460
461 match octets.cmp(&needed) {
462 Ordering::Greater => {
463 const PADDED_BYTES_NEG: [u8; 8] = [0xffu8; 8];
464 const PADDED_BYTES_POS: [u8; 8] = [0x00u8; 8];
465 let idx = usize::from(signed && value.is_negative());
467 let padded_bytes = [&PADDED_BYTES_POS, &PADDED_BYTES_NEG][idx];
468 self.output
469 .extend_from_slice(&padded_bytes[..octets - needed]);
470 }
471 Ordering::Less => {
472 return Err(EncodeError::from_kind(
473 EncodeErrorKind::MoreBytesThanExpected {
474 value: needed,
475 expected: octets,
476 },
477 self.codec(),
478 ));
479 }
480 Ordering::Equal => {}
482 };
483 self.output.extend_from_slice(&bytes[..needed]);
484 Ok(())
485 }
486 fn check_fixed_size_constraint(
487 &self,
488 length: usize,
489 constraints: &Constraints,
490 ) -> Result<bool, EncodeError> {
491 if let Some(size) = constraints.size() {
492 if !size.constraint.contains(&length) && size.extensible.is_none() {
493 return Err(EncodeError::size_constraint_not_satisfied(
494 length,
495 &size.constraint,
496 self.codec(),
497 ));
498 }
499 if size.constraint.is_fixed() && size.extensible.is_none() {
501 return Ok(true);
502 }
503 }
504 const MAX_PERMITTED_LENGTH: usize = usize::MAX / 8;
506 if length > MAX_PERMITTED_LENGTH {
507 return Err(EncodeError::length_exceeds_platform_size(self.codec()));
508 }
509 Ok(false)
510 }
511
512 fn extension_bitmap_reserve(&mut self) {
515 self.cursor.set_extension_bitmap_cursor(self.output.len());
516 self.output.extend(core::iter::repeat_n(
517 0,
518 self.cursor.extension_bitmap_total_width,
519 ));
520 }
521
522 fn encode_constructed<const RC: usize, const EC: usize, C: Constructed<RC, EC>>(
525 &mut self,
526 tag: Tag,
527 set_output: Option<&mut alloc::collections::BTreeMap<Tag, Vec<u8>>>,
528 ) -> Result<(), EncodeError> {
529 let mut preamble = BitArray::<[u8; RC], Msb0>::default();
532 let mut preamble_index = 0;
533 let mut extensions_present = false;
534 if C::IS_EXTENSIBLE {
535 extensions_present = self.extension_bitfield.1.iter().any(|b| *b);
536 if RC > 0 {
538 preamble.set(0, extensions_present);
539 preamble_index += 1;
540 }
541 }
542 let (needed, option_bitfield) = if self.options.set_encoding {
544 self.root_bitfield
546 .1
547 .sort_by(|(_, tag1), (_, tag2)| tag1.const_cmp(tag2));
548 self.root_bitfield
549 } else {
550 self.root_bitfield
551 };
552 debug_assert!(C::FIELDS.number_of_optional_and_default_fields() == needed);
553 for (bit, _tag) in &option_bitfield[..needed] {
554 preamble.set(preamble_index, *bit);
555 preamble_index += 1;
556 }
557 if needed > 0 || C::IS_EXTENSIBLE {
560 if RC == 0 && C::IS_EXTENSIBLE {
562 self.output.push(u8::from(extensions_present) << 7);
563 } else {
564 if self.options.set_encoding {
566 self.output
567 .extend_from_slice(&preamble.as_raw_slice()[..self.cursor.preamble_width]);
568 } else {
569 self.output[self.cursor.preamble_cursor
570 ..self.cursor.preamble_cursor + self.cursor.preamble_width]
571 .copy_from_slice(&preamble.as_raw_slice()[..self.cursor.preamble_width]);
572 }
573 }
574 }
575 if !C::IS_EXTENSIBLE || !extensions_present {
577 if let Some(set_output) = set_output {
578 set_output.insert(tag, core::mem::take(self.output));
579 }
580 return Ok(());
581 }
582
583 debug_assert_ne!(self.cursor.extension_bitmap_cursor, 0);
587 let mut extension_bitmap_buffer: BitArray<[u8; EC], Msb0> = BitArray::default();
590 Self::encode_length(self.worker, self.cursor.extension_bitmap_width)?;
591 let mut cursor = self.cursor.extension_bitmap_cursor + self.worker.len();
592 self.output[self.cursor.extension_bitmap_cursor..cursor].copy_from_slice(self.worker);
593 self.worker.clear();
594 self.output[cursor..=cursor]
595 .copy_from_slice(&self.cursor.extension_missing_bits.to_be_bytes());
596 cursor += 1;
597 for (i, bit) in self.extension_bitfield.1.iter().enumerate() {
598 extension_bitmap_buffer.set(i, *bit);
599 }
600 self.output[cursor..cursor + self.cursor.extension_bitfield_width].copy_from_slice(
602 &extension_bitmap_buffer.as_raw_slice()[..self.cursor.extension_bitfield_width],
603 );
604
605 if let Some(set_output) = set_output {
610 set_output.insert(tag, core::mem::take(self.output));
611 }
612 Ok(())
613 }
614}
615
616impl<'buffer, const RFC: usize, const EFC: usize> crate::Encoder<'buffer>
617 for Encoder<'buffer, RFC, EFC>
618{
619 type Ok = ();
620 type Error = EncodeError;
621 type AnyEncoder<'this, const R: usize, const E: usize> = Encoder<'this, R, E>;
622
623 fn codec(&self) -> Codec {
624 self.options.current_codec()
625 }
626
627 fn encode_any(
628 &mut self,
629 tag: Tag,
630 value: &Any,
631 _: Identifier,
632 ) -> Result<Self::Ok, Self::Error> {
633 self.encode_octet_string(
634 tag,
635 <Constraints>::default(),
636 value.as_bytes(),
637 Identifier::EMPTY,
638 )
639 }
640
641 fn encode_bool(
645 &mut self,
646 tag: Tag,
647 value: bool,
648 _: Identifier,
649 ) -> Result<Self::Ok, Self::Error> {
650 self.output
651 .extend_from_slice(if value { &[0xffu8] } else { &[0x00u8] });
652 self.extend(tag);
653 Ok(())
654 }
655
656 fn encode_bit_string(
657 &mut self,
658 tag: Tag,
659 constraints: Constraints,
660 value: &BitStr,
661 _: Identifier,
662 ) -> Result<Self::Ok, Self::Error> {
663 let mut bit_string_encoding = BitVec::<u8, Msb0>::with_capacity(value.len());
668
669 if let Some(size) = constraints.size() {
670 if size.constraint.is_fixed() && size.extensible.is_none() {
673 if size.constraint.contains(&value.len()) {
679 let missing_bits: usize = (8 - (value.len() & 7)) & 7;
680 bit_string_encoding.extend(value);
681 if missing_bits > 0 {
682 bit_string_encoding.extend(core::iter::repeat_n(false, missing_bits));
683 }
684 self.output
685 .extend_from_slice(bit_string_encoding.as_raw_slice());
686 } else {
687 return Err(EncodeError::size_constraint_not_satisfied(
688 value.len(),
689 &size.constraint,
690 self.codec(),
691 ));
692 }
693 self.extend(tag);
694 return Ok(());
695 }
696 }
697
698 if value.is_empty() {
700 Self::encode_length(self.output, 1)?;
701 self.output.extend_from_slice(&[0x00u8]);
702 } else {
703 let missing_bits: usize = (8 - value.len() % 8) % 8;
715 let trailing = [false; 8];
716 let trailing = &trailing[..missing_bits];
717 bit_string_encoding.extend(missing_bits.to_u8().unwrap_or(0).to_be_bytes());
719 bit_string_encoding.extend(value);
720 bit_string_encoding.extend(trailing);
721 Self::encode_length(self.output, bit_string_encoding.len() / 8)?;
722 self.output
723 .extend_from_slice(bit_string_encoding.as_raw_slice());
724 }
725 self.extend(tag);
726 Ok(())
727 }
728
729 fn encode_enumerated<E: Enumerated>(
730 &mut self,
731 tag: Tag,
732 value: &E,
733 _: Identifier,
734 ) -> Result<Self::Ok, Self::Error> {
735 let number = value.discriminant();
740 if 0isize <= number && number <= i8::MAX.into() {
741 self.encode_constrained_integer_with_padding(1, &number, false)?;
742 } else {
743 self.encode_unconstrained_enum_index(number)?;
746 }
747 self.extend(tag);
748 Ok(())
749 }
750
751 fn encode_object_identifier(
752 &mut self,
753 tag: Tag,
754 value: &[u32],
755 _: Identifier,
756 ) -> Result<Self::Ok, Self::Error> {
757 let mut enc = crate::ber::enc::Encoder::new(crate::ber::enc::EncoderOptions::ber());
758 let mut octets = enc.object_identifier_as_bytes(value)?;
759 Self::encode_length(self.output, octets.len())?;
760 self.output.append(&mut octets);
761 self.extend(tag);
762 Ok(())
763 }
764
765 fn encode_integer<I: IntegerType>(
766 &mut self,
767 tag: Tag,
768 constraints: Constraints,
769 value: &I,
770 _: Identifier,
771 ) -> Result<Self::Ok, Self::Error> {
772 self.encode_integer_with_constraints(tag, &constraints, value)
773 }
774
775 fn encode_real<R: RealType>(
776 &mut self,
777 tag: Tag,
778 _constraints: Constraints,
779 value: &R,
780 _: Identifier,
781 ) -> Result<Self::Ok, Self::Error> {
782 let (bytes, len) = value.to_ieee754_bytes();
783 self.output.extend_from_slice(&bytes.as_ref()[..len]);
784 self.extend(tag);
785
786 Ok(())
787 }
788
789 fn encode_null(&mut self, _tag: Tag, _: Identifier) -> Result<Self::Ok, Self::Error> {
790 Ok(())
791 }
792
793 fn encode_octet_string(
794 &mut self,
795 tag: Tag,
796 constraints: Constraints,
797 value: &[u8],
798 _: Identifier,
799 ) -> Result<Self::Ok, Self::Error> {
800 if self.check_fixed_size_constraint(value.len(), &constraints)? {
801 self.output.extend_from_slice(value);
802 } else {
803 Self::encode_length(self.output, value.len())?;
805 self.output.extend_from_slice(value);
806 }
807 self.extend(tag);
808 Ok(())
809 }
810
811 fn encode_general_string(
812 &mut self,
813 tag: Tag,
814 constraints: Constraints,
815 value: &GeneralString,
816 _: Identifier,
817 ) -> Result<Self::Ok, Self::Error> {
818 self.encode_octet_string(tag, constraints, value, Identifier::EMPTY)
820 }
821
822 fn encode_graphic_string(
823 &mut self,
824 tag: Tag,
825 constraints: Constraints,
826 value: &GraphicString,
827 _: Identifier,
828 ) -> Result<Self::Ok, Self::Error> {
829 self.encode_octet_string(tag, constraints, value, Identifier::EMPTY)
831 }
832
833 fn encode_utf8_string(
834 &mut self,
835 tag: Tag,
836 constraints: Constraints,
837 value: &str,
838 _: Identifier,
839 ) -> Result<Self::Ok, Self::Error> {
840 self.encode_octet_string(tag, constraints, value.as_bytes(), Identifier::EMPTY)
841 }
842
843 fn encode_visible_string(
844 &mut self,
845 tag: Tag,
846 constraints: Constraints,
847 value: &VisibleString,
848 _: Identifier,
849 ) -> Result<Self::Ok, Self::Error> {
850 self.encode_octet_string(tag, constraints, value.as_iso646_bytes(), Identifier::EMPTY)
851 }
852
853 fn encode_ia5_string(
854 &mut self,
855 tag: Tag,
856 constraints: Constraints,
857 value: &Ia5String,
858 _: Identifier,
859 ) -> Result<Self::Ok, Self::Error> {
860 self.encode_octet_string(tag, constraints, value.as_iso646_bytes(), Identifier::EMPTY)
861 }
862
863 fn encode_printable_string(
864 &mut self,
865 tag: Tag,
866 constraints: Constraints,
867 value: &PrintableString,
868 _: Identifier,
869 ) -> Result<Self::Ok, Self::Error> {
870 self.encode_octet_string(tag, constraints, value.as_bytes(), Identifier::EMPTY)
871 }
872
873 fn encode_numeric_string(
874 &mut self,
875 tag: Tag,
876 constraints: Constraints,
877 value: &NumericString,
878 _: Identifier,
879 ) -> Result<Self::Ok, Self::Error> {
880 self.encode_octet_string(tag, constraints, value.as_bytes(), Identifier::EMPTY)
881 }
882
883 fn encode_teletex_string(
884 &mut self,
885 tag: Tag,
886 constraints: Constraints,
887 value: &TeletexString,
888 _: Identifier,
889 ) -> Result<Self::Ok, Self::Error> {
890 self.encode_octet_string(tag, constraints, &value.to_bytes(), Identifier::EMPTY)
894 }
895
896 fn encode_bmp_string(
897 &mut self,
898 tag: Tag,
899 constraints: Constraints,
900 value: &BmpString,
901 _: Identifier,
902 ) -> Result<Self::Ok, Self::Error> {
903 self.encode_octet_string(tag, constraints, &value.to_bytes(), Identifier::EMPTY)
904 }
905
906 fn encode_generalized_time(
907 &mut self,
908 tag: Tag,
909 value: &GeneralizedTime,
910 _: Identifier,
911 ) -> Result<Self::Ok, Self::Error> {
912 self.encode_octet_string(
913 tag,
914 Constraints::default(),
915 &crate::der::enc::Encoder::datetime_to_canonical_generalized_time_bytes(value),
916 Identifier::EMPTY,
917 )
918 }
919
920 fn encode_utc_time(
921 &mut self,
922 tag: Tag,
923 value: &UtcTime,
924 _: Identifier,
925 ) -> Result<Self::Ok, Self::Error> {
926 self.encode_octet_string(
927 tag,
928 Constraints::default(),
929 &crate::der::enc::Encoder::datetime_to_canonical_utc_time_bytes(value),
930 Identifier::EMPTY,
931 )
932 }
933
934 fn encode_date(
935 &mut self,
936 tag: Tag,
937 value: &Date,
938 _: Identifier,
939 ) -> Result<Self::Ok, Self::Error> {
940 self.encode_octet_string(
941 tag,
942 Constraints::default(),
943 &crate::der::enc::Encoder::naivedate_to_date_bytes(value),
944 Identifier::EMPTY,
945 )
946 }
947 fn encode_explicit_prefix<V: Encode>(
948 &mut self,
949 tag: Tag,
950 value: &V,
951 _: Identifier,
952 ) -> Result<Self::Ok, Self::Error> {
953 if V::IS_CHOICE {
955 value.encode(self)
956 } else {
957 value.encode_with_tag(self, tag)
958 }
959 }
960
961 fn encode_sequence<'b, const RL: usize, const EL: usize, C, F>(
962 &'b mut self,
963 tag: Tag,
964 encoder_scope: F,
965 _: Identifier,
966 ) -> Result<Self::Ok, Self::Error>
967 where
968 C: Constructed<RL, EL>,
969 F: FnOnce(&mut Self::AnyEncoder<'b, RL, EL>) -> Result<(), Self::Error>,
970 {
971 let mut encoder = Encoder::<'_, RL, EL>::from_buffer(
972 self.options.without_set_encoding(),
973 self.output,
974 self.worker,
975 );
976 let mut cursor = ConstructedCursor::<RL, EL>::new(
977 C::FIELDS.number_of_optional_and_default_fields(),
978 C::IS_EXTENSIBLE,
979 );
980 cursor.set_preamble_cursor(encoder.output.len());
981 for _ in 0..cursor.preamble_width {
983 encoder.output.push(0);
984 }
985
986 encoder.cursor = cursor;
987 encoder_scope(&mut encoder)?;
988 if self.options.set_encoding {
989 encoder.encode_constructed::<RL, EL, C>(tag, Some(&mut self.set_output))?;
990 } else {
991 encoder.encode_constructed::<RL, EL, C>(tag, None)?;
992 }
993 Ok(())
994 }
995
996 fn encode_sequence_of<E: Encode>(
997 &mut self,
998 tag: Tag,
999 value: &[E],
1000 _: Constraints,
1001 _: Identifier,
1002 ) -> Result<Self::Ok, Self::Error> {
1003 self.encode_unconstrained_integer(&value.len(), false)?;
1005 self.output.reserve(core::mem::size_of_val(value));
1006
1007 let mut encoder = Encoder::<0>::from_buffer(self.options, self.output, self.worker);
1008 {
1009 for one in value {
1010 E::encode(one, &mut encoder)?;
1011 }
1012 }
1013 self.extend(tag);
1014 Ok(())
1015 }
1016
1017 fn encode_set<'b, const RL: usize, const EL: usize, C, F>(
1018 &'b mut self,
1019 tag: Tag,
1020 encoder_scope: F,
1021 _: Identifier,
1022 ) -> Result<Self::Ok, Self::Error>
1023 where
1024 C: Constructed<RL, EL>,
1025 F: FnOnce(&mut Self::AnyEncoder<'b, RL, EL>) -> Result<(), Self::Error>,
1026 {
1027 let mut options = self.options;
1028 options.set_encoding = true;
1029 let mut encoder = Encoder::<RL, EL>::from_buffer(options, self.output, self.worker);
1030 let cursor = ConstructedCursor::<RL, EL>::new(
1031 C::FIELDS.number_of_optional_and_default_fields(),
1032 C::IS_EXTENSIBLE,
1033 );
1034 encoder.cursor = cursor;
1035 encoder_scope(&mut encoder)?;
1036 if self.options.set_encoding {
1037 encoder.encode_constructed::<RL, EL, C>(tag, Some(&mut self.set_output))?;
1038 } else {
1039 encoder.encode_constructed::<RL, EL, C>(tag, None)?;
1040 }
1041 encoder.collect_set();
1042 Ok(())
1043 }
1044
1045 fn encode_set_of<E: Encode + Eq + core::hash::Hash>(
1046 &mut self,
1047 tag: Tag,
1048 value: &SetOf<E>,
1049 constraints: Constraints,
1050 _: Identifier,
1051 ) -> Result<Self::Ok, Self::Error> {
1052 self.encode_sequence_of(tag, &value.to_vec(), constraints, Identifier::EMPTY)
1053 }
1054
1055 fn encode_some<E: Encode>(
1056 &mut self,
1057 value: &E,
1058 _: Identifier,
1059 ) -> Result<Self::Ok, Self::Error> {
1060 self.set_presence(E::TAG, true);
1061 value.encode(self)
1062 }
1063
1064 fn encode_some_with_tag_and_constraints<E: Encode>(
1065 &mut self,
1066 tag: Tag,
1067 constraints: Constraints,
1068 value: &E,
1069 _: Identifier,
1070 ) -> Result<Self::Ok, Self::Error> {
1071 self.set_presence(tag, true);
1072 value.encode_with_tag_and_constraints(self, tag, constraints, Identifier::EMPTY)
1073 }
1074
1075 fn encode_none<E: Encode>(&mut self, _: Identifier) -> Result<Self::Ok, Self::Error> {
1076 self.set_presence(E::TAG, false);
1077 Ok(())
1078 }
1079
1080 fn encode_none_with_tag(&mut self, tag: Tag, _: Identifier) -> Result<Self::Ok, Self::Error> {
1081 self.set_presence(tag, false);
1082 Ok(())
1083 }
1084
1085 fn encode_choice<E: Encode + Choice>(
1086 &mut self,
1087 _: Constraints,
1088 tag: Tag,
1089 encode_fn: impl FnOnce(&mut Self) -> Result<Tag, Self::Error>,
1090 _: Identifier,
1091 ) -> Result<Self::Ok, Self::Error> {
1092 let mut tag_buffer: BitArray<[u8; core::mem::size_of::<Tag>() + 1], Msb0> =
1094 BitArray::default();
1095 let needed = self.encode_tag(tag, tag_buffer.as_mut_bitslice());
1096 self.output
1097 .extend_from_slice(&tag_buffer.as_raw_slice()[..(needed / 8)]);
1098
1099 let buffer_end = self.output.len();
1100 let _tag = encode_fn(self)?;
1102 debug_assert_eq!(_tag, tag);
1103 let is_root_extension = crate::types::TagTree::tag_contains(&tag, E::VARIANTS);
1104 if is_root_extension {
1105 } else {
1107 self.worker.append(&mut self.output.split_off(buffer_end));
1111 Self::encode_length(self.output, self.worker.len())?;
1112 self.output.append(self.worker);
1113 }
1114 self.extend(tag);
1115 Ok(())
1116 }
1117
1118 fn encode_extension_addition<E: Encode>(
1119 &mut self,
1120 tag: Tag,
1121 constraints: Constraints,
1122 value: E,
1123 _: Identifier,
1124 ) -> Result<Self::Ok, Self::Error> {
1125 if value.is_present() {
1127 if self.cursor.extension_bitmap_cursor == 0 {
1128 self.extension_bitmap_reserve();
1129 }
1130 let cursor = self.output.len();
1131 let mut encoder = Encoder::<0>::from_buffer(self.options, self.worker, self.output);
1135 E::encode_with_tag_and_constraints(
1136 &value,
1137 &mut encoder,
1138 tag,
1139 constraints,
1140 Identifier::EMPTY,
1141 )?;
1142 encoder.worker.truncate(cursor);
1144 Self::encode_length(encoder.worker, encoder.output.len())?;
1145 self.output.append(self.worker);
1146 self.set_extension_presence(true);
1147 } else {
1148 self.set_extension_presence(false);
1149 }
1150 Ok(())
1151 }
1152 fn encode_extension_addition_group<const RL: usize, const EL: usize, E>(
1153 &mut self,
1154 value: Option<&E>,
1155 _: Identifier,
1156 ) -> Result<Self::Ok, Self::Error>
1157 where
1158 E: Encode + Constructed<RL, EL>,
1159 {
1160 let Some(value) = value else {
1161 self.set_extension_presence(false);
1162 return Ok(());
1163 };
1164 if self.cursor.extension_bitmap_cursor == 0 {
1165 self.extension_bitmap_reserve();
1166 }
1167 self.is_extension_sequence = true;
1168 let cursor = self.output.len();
1172 let mut encoder = Encoder::<0>::from_buffer(self.options, self.worker, self.output);
1173 value.encode(&mut encoder)?;
1174 encoder.worker.truncate(cursor);
1176 self.is_extension_sequence = false;
1177 Self::encode_length(encoder.worker, encoder.output.len())?;
1178 self.output.append(self.worker);
1179 self.set_extension_presence(true);
1180 Ok(())
1181 }
1182}
1183
1184#[cfg(test)]
1185mod tests {
1186 use num_bigint::BigInt;
1187
1188 use super::*;
1189 use crate::prelude::{AsnType, Decode, Encode};
1190
1191 #[test]
1192 fn test_encode_bool() {
1193 let output = crate::coer::encode(&true).unwrap();
1194 let bv = BitVec::<u8, Msb0>::from_slice(&[0xffu8]);
1195 assert_eq!(output, bv.as_raw_slice());
1196 let output = crate::coer::encode(&false).unwrap();
1197 let bv = BitVec::<u8, Msb0>::from_slice(&[0x00u8]);
1198 assert_eq!(output, bv.as_raw_slice());
1199 let decoded = crate::coer::encode(&true).unwrap();
1200 assert_eq!(decoded, &[0xffu8]);
1201 let decoded = crate::coer::encode(&false).unwrap();
1202 assert_eq!(decoded, &[0x0]);
1203 }
1204 #[test]
1205 fn test_encode_integer_manual_setup() {
1206 const CONSTRAINT_1: Constraints = constraints!(value_constraint!(0, 255));
1207 let mut buffer = vec![];
1208 let mut wb = vec![];
1209 let mut encoder =
1210 Encoder::<0, 0>::from_buffer(EncoderOptions::coer(), &mut buffer, &mut wb);
1211 let result = encoder.encode_integer_with_constraints(Tag::INTEGER, &CONSTRAINT_1, &244);
1212 assert!(result.is_ok());
1213 let v = vec![244u8];
1214 assert_eq!(encoder.output.clone(), v);
1215 encoder.output.clear();
1216 let value = BigInt::from(256);
1217 let result = encoder.encode_integer_with_constraints(Tag::INTEGER, &CONSTRAINT_1, &value);
1218 assert!(result.is_err());
1219 }
1220 #[test]
1221 fn test_integer_with_length_determinant() {
1222 let constraints = Constraints::default();
1224 let mut buffer = vec![];
1225 let mut wb = vec![];
1226 let mut encoder =
1227 Encoder::<0, 0>::from_buffer(EncoderOptions::coer(), &mut buffer, &mut wb);
1228 let result =
1229 encoder.encode_integer_with_constraints(Tag::INTEGER, &constraints, &BigInt::from(244));
1230 assert!(result.is_ok());
1231 let v = vec![2u8, 0, 244];
1232 assert_eq!(encoder.output.to_vec(), v);
1233 encoder.output.clear();
1234 let result = encoder.encode_integer_with_constraints(
1235 Tag::INTEGER,
1236 &constraints,
1237 &BigInt::from(-1_234_567),
1238 );
1239 assert!(result.is_ok());
1240 let v = vec![0x03u8, 0xED, 0x29, 0x79];
1241 assert_eq!(encoder.output.to_vec(), v);
1242 }
1243 #[test]
1244 fn test_large_lengths() {
1245 let constraints = Constraints::default();
1246 let mut buffer = vec![];
1247 let mut wb = vec![];
1248 let mut encoder =
1249 Encoder::<0, 0>::from_buffer(EncoderOptions::coer(), &mut buffer, &mut wb);
1250
1251 let number: BigInt = BigInt::from(256).pow(127) - 1;
1254 let result = encoder.encode_integer_with_constraints(Tag::INTEGER, &constraints, &number);
1255 assert!(result.is_ok());
1256 let vc = [
1257 0x81, 0x80, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1258 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1259 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1260 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1261 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1262 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1263 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1264 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1265 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1266 0xff, 0xff, 0xff, 0xff,
1267 ];
1268 assert_eq!(encoder.output(), vc);
1269 }
1270 #[test]
1271 fn test_choice() {
1272 use crate as rasn;
1273 use crate::types::Integer;
1274 #[derive(AsnType, Decode, Debug, Encode, PartialEq)]
1275 #[rasn(choice, automatic_tags)]
1276 #[non_exhaustive]
1277 enum Choice {
1278 Normal(Integer),
1279 High(Integer),
1280 #[rasn(extension_addition)]
1281 Medium(Integer),
1282 }
1283 let mut buffer = vec![];
1284 let mut wb = vec![];
1285 let mut encoder =
1286 Encoder::<0, 0>::from_buffer(EncoderOptions::coer(), &mut buffer, &mut wb);
1287
1288 let choice = Choice::Normal(333.into());
1289 choice.encode(&mut encoder).unwrap();
1290
1291 assert_eq!(encoder.output(), &[128, 2, 1, 77]);
1292 }
1293}