Skip to main content

rasn/
per.rs

1pub mod de;
2pub mod enc;
3
4use crate::types::Constraints;
5
6pub use self::{de::Decoder, enc::Encoder};
7
8const SIXTEEN_K: u16 = 16384;
9const THIRTY_TWO_K: u16 = 32768;
10const FOURTY_EIGHT_K: u16 = 49152;
11const SIXTY_FOUR_K: u32 = 65536;
12const SMALL_UNSIGNED_CONSTRAINT: Constraints = constraints!(value_constraint!(0, 63));
13const LARGE_UNSIGNED_CONSTRAINT: Constraints = constraints!(value_constraint!(start: 0));
14
15/// Attempts to decode `T` from `input` using PER.
16pub(crate) fn decode<T: crate::Decode>(
17    options: de::DecoderOptions,
18    input: &[u8],
19) -> Result<T, crate::error::DecodeError> {
20    T::decode(&mut crate::per::de::Decoder::<0, 0>::new(
21        crate::types::BitStr::from_slice(input),
22        options,
23    ))
24}
25/// Attempts to decode `T` from `input` using PER. Returns both `T` and reference to the remainder of the input.
26///
27/// # Errors
28/// Returns `DecodeError` if `input` is not valid PER encoding specific to the expected type.
29pub(crate) fn decode_with_remainder<T: crate::Decode>(
30    options: de::DecoderOptions,
31    input: &[u8],
32) -> Result<(T, &[u8]), crate::error::DecodeError> {
33    let decoder = &mut Decoder::<0, 0>::new(crate::types::BitStr::from_slice(input), options);
34    let decoded_instance = T::decode(decoder)?;
35    let remaining_bits = decoder.input().len();
36    // Consider only whole bytes, ignore padding bits
37    let remaining_size = remaining_bits / 8;
38    debug_assert!(input.len() >= remaining_size);
39    Ok((decoded_instance, &input[input.len() - remaining_size..]))
40}
41
42/// Attempts to encode `value` to PER.
43pub(crate) fn encode<T: crate::Encode>(
44    options: enc::EncoderOptions,
45    value: &T,
46) -> Result<alloc::vec::Vec<u8>, crate::error::EncodeError> {
47    let mut enc = crate::per::enc::Encoder::<0, 0>::new(options);
48
49    value.encode(&mut enc)?;
50
51    Ok(enc.output())
52}
53
54/// Attempts to decode `T` from `input` using PER.
55pub(crate) fn decode_with_constraints<T: crate::Decode>(
56    options: de::DecoderOptions,
57    constraints: Constraints,
58    input: &[u8],
59) -> Result<T, crate::error::DecodeError> {
60    T::decode_with_constraints(
61        &mut crate::per::de::Decoder::<0, 0>::new(crate::types::BitStr::from_slice(input), options),
62        constraints,
63    )
64}
65
66/// Attempts to encode `value` to PER.
67pub(crate) fn encode_with_constraints<T: crate::Encode>(
68    options: enc::EncoderOptions,
69    constraints: Constraints,
70    value: &T,
71) -> Result<alloc::vec::Vec<u8>, crate::error::EncodeError> {
72    let mut enc = crate::per::enc::Encoder::<0, 0>::new(options);
73
74    value.encode_with_constraints(&mut enc, constraints)?;
75
76    Ok(enc.output())
77}