Skip to content

Commit

Permalink
OER: small choice encoding optimization
Browse files Browse the repository at this point in the history
  • Loading branch information
Nicceboy committed Nov 23, 2024
1 parent 0f28bf4 commit 6b86240
Showing 1 changed file with 13 additions and 7 deletions.
20 changes: 13 additions & 7 deletions src/oer/enc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
use alloc::vec::Vec;
use bitvec::prelude::*;
use nom::AsBytes;
use num_traits::ToPrimitive;

use crate::{
Expand Down Expand Up @@ -929,21 +928,28 @@ impl<'buffer, const RFC: usize, const EFC: usize> crate::Encoder<'buffer>
fn encode_choice<E: Encode + Choice>(
&mut self,
_: Constraints,
_tag: Tag,
tag: Tag,
encode_fn: impl FnOnce(&mut Self) -> Result<Tag, Self::Error>,
) -> Result<Self::Ok, Self::Error> {
let buffer_end = self.output.len();
let tag = encode_fn(self)?;
let is_root_extension = crate::types::TagTree::tag_contains(&tag, E::VARIANTS);
let mut output = self.output.split_off(buffer_end);
// Encode tag
let mut tag_buffer: BitArray<[u8; core::mem::size_of::<Tag>() + 1], Msb0> =
BitArray::default();
let needed = self.encode_tag(tag, tag_buffer.as_mut_bitslice());
self.output
.extend_from_slice(&tag_buffer.as_raw_slice()[..(needed / 8)]);

let buffer_end = self.output.len();
// Encode the value
let _tag = encode_fn(self)?;
debug_assert_eq!(_tag, tag);
let is_root_extension = crate::types::TagTree::tag_contains(&tag, E::VARIANTS);
if is_root_extension {
self.output.append(&mut output);
// all good, correct data in the buffer already
} else {
// Extension with length determinant
// Unfortunatelly, we really cannot avoid extra allocating here
// We don't know the length of the data length before encoding
let mut output = self.output.split_off(buffer_end);
self.encode_length(output.len())?;
self.output.append(&mut output);
}
Expand Down

0 comments on commit 6b86240

Please sign in to comment.