| 1 | use core::ops::RangeInclusive; |
| 2 | |
| 3 | use crate::{Error, ErrorKind, Tag}; |
| 4 | |
| 5 | /// Trait automatically derived on structs, by the `BitString` macro. |
| 6 | /// Used for checking if binary data fits into defined struct. |
| 7 | /// |
| 8 | /// ``` |
| 9 | /// /// Bit length of 2 |
| 10 | /// struct MyBitString { |
| 11 | /// flag1: bool, |
| 12 | /// flag2: bool, |
| 13 | /// } |
| 14 | /// ``` |
| 15 | /// |
| 16 | /// ```rust,ignore |
| 17 | /// use der::BitString; |
| 18 | /// |
| 19 | /// /// Bit length of 3..=4 |
| 20 | /// #[derive(BitString)] |
| 21 | /// struct MyBitString { |
| 22 | /// flag1: bool, |
| 23 | /// flag2: bool, |
| 24 | /// flag3: bool, |
| 25 | /// |
| 26 | /// #[asn1(optional = "true")] |
| 27 | /// flag4: bool, |
| 28 | /// } |
| 29 | /// ``` |
| 30 | pub trait AllowedLenBitString { |
| 31 | /// Implementer must specify how many bits are allowed |
| 32 | const ALLOWED_LEN_RANGE: RangeInclusive<u16>; |
| 33 | |
| 34 | /// Check the bit length. |
| 35 | /// |
| 36 | /// # Errors |
| 37 | /// Returns an error if the bitstring is not in expected length range. |
| 38 | fn check_bit_len(bit_len: u16) -> Result<(), Error> { |
| 39 | let allowed_len_range = Self::ALLOWED_LEN_RANGE; |
| 40 | |
| 41 | // forces allowed range to e.g. 3..=4 |
| 42 | if !allowed_len_range.contains(&bit_len) { |
| 43 | Err(ErrorKind::Length { |
| 44 | tag: Tag::BitString, |
| 45 | } |
| 46 | .into()) |
| 47 | } else { |
| 48 | Ok(()) |
| 49 | } |
| 50 | } |
| 51 | } |