1 #![allow(clippy::all)] 2 #![allow(unused)] 3 #![allow(missing_docs)] 4 5 pub mod l2cap { 6 include!(concat!(env!("OUT_DIR"), "/l2cap_packets.rs")); 7 } 8 9 pub mod hci { 10 include!(concat!(env!("OUT_DIR"), "/hci_packets.rs")); 11 12 pub const EMPTY_ADDRESS: Address = Address(0x000000000000); 13 14 impl fmt::Display for Address { fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result15 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 16 let bytes = u64::to_le_bytes(self.0); 17 write!( 18 f, 19 "{:02X}:{:02X}:{:02X}:{:02X}:{:02X}:{:02X}", 20 bytes[5], bytes[4], bytes[3], bytes[2], bytes[1], bytes[0], 21 ) 22 } 23 } 24 25 impl From<&[u8; 6]> for Address { from(bytes: &[u8; 6]) -> Self26 fn from(bytes: &[u8; 6]) -> Self { 27 Self(u64::from_le_bytes([ 28 bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], 0, 0, 29 ])) 30 } 31 } 32 33 impl From<Address> for [u8; 6] { from(Address(addr): Address) -> Self34 fn from(Address(addr): Address) -> Self { 35 let bytes = u64::to_le_bytes(addr); 36 bytes[0..6].try_into().unwrap() 37 } 38 } 39 40 pub struct GapData { 41 pub data_type: GapDataType, 42 pub data: Vec<u8>, 43 } 44 45 impl GapData { parse(bytes: &[u8]) -> std::result::Result<Self, String>46 pub fn parse(bytes: &[u8]) -> std::result::Result<Self, String> { 47 // In case of parsing EIR, we can get normal data, or all zeroes. Normal data always 48 // have at least 2 bytes: one for the length, and another for the type. Therefore we 49 // can terminate early if the data has less than 2 bytes. 50 if (bytes.len() == 0) { 51 return Err("no data to parse".to_string()); 52 } else if (bytes.len() == 1) { 53 if (bytes[0] != 0) { 54 return Err(format!("can't parse 1 byte of data: {}", bytes[0])); 55 } 56 return Ok(GapData { data_type: GapDataType::Invalid, data: vec![] }); 57 } 58 59 let mut data_size = bytes[0] as usize; 60 if (data_size == 0) { 61 // Data size already include the data_type, so size = 0 is possible only when 62 // parsing EIR, where all data are zeroes. Here we just assume that assumption is 63 // correct, and don't really check all the elements. 64 return Ok(GapData { data_type: GapDataType::Invalid, data: bytes[2..].to_vec() }); 65 } 66 67 if (data_size > bytes.len() - 1) { 68 return Err(format!( 69 "size {} is bigger than remaining length {}", 70 data_size, 71 bytes.len() - 1 72 )); 73 } 74 let data_type = match GapDataType::try_from(bytes[1]) { 75 Ok(data_type) => Ok(data_type), 76 Err(_) => Err(format!("can't parse data type {}", bytes[1])), 77 }?; 78 return Ok(GapData { data_type, data: bytes[2..(data_size + 1)].to_vec() }); 79 } 80 } 81 } 82