rasn/
per.rs

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