sml_rs/parser/octet_string.rs
1//! An OctetString in SML is a sequence of bytes.
2
3use super::{
4 take_n,
5 tlf::{Ty, TypeLengthField},
6 ResTy, SmlParseTlf,
7};
8
9// #[cfg(feature = "alloc")]
10// /// OctetString is the owned version of a sequence of bytes.
11// pub type OctetString = alloc::vec::Vec<u8>;
12
13// #[cfg(feature = "alloc")]
14// impl<'i> SmlParseTlf<'i> for OctetString {
15// fn check_tlf(tlf: &TypeLengthField) -> bool {
16// OctetStr::check_tlf(tlf)
17// }
18
19// fn parse_with_tlf(input: &'i [u8], tlf: &TypeLengthField) -> ResTy<'i, Self> {
20// let (input, octet_str) = OctetStr::parse_with_tlf(input, tlf)?;
21// Ok((input, octet_str.to_vec()))
22// }
23// }
24
25/// OctetStr is the borrowed version of a sequence of bytes.
26pub type OctetStr<'i> = &'i [u8];
27
28impl<'i> SmlParseTlf<'i> for OctetStr<'i> {
29 fn check_tlf(tlf: &TypeLengthField) -> bool {
30 matches!(tlf.ty, Ty::OctetString)
31 }
32
33 fn parse_with_tlf(input: &'i [u8], tlf: &TypeLengthField) -> ResTy<'i, Self> {
34 take_n(input, tlf.len as usize)
35 }
36}
37
38#[cfg(test)]
39mod test {
40
41 use super::*;
42 use crate::parser::SmlParse;
43 use hex_literal::hex;
44
45 #[test]
46 fn test_octet_str() {
47 // simple
48 assert_eq!(
49 OctetStr::parse_complete(&hex!("0648656C6C6F")).expect("Decode Error"),
50 &b"Hello"[..]
51 );
52
53 // long
54 assert_eq!(
55 <&[u8]>::parse_complete(b"\x81\x0Cqwertzuiopasdfghjklyxcvbnm").expect("Decode Error"),
56 &b"qwertzuiopasdfghjklyxcvbnm"[..]
57 );
58
59 // optional
60 assert_eq!(
61 Option::<&[u8]>::parse_complete(b"\x01").expect("Decode Error"),
62 None
63 );
64 }
65}