bluetooth_host/
address.rs1use core::fmt;
4use core::str::FromStr;
5
6use serde::{Deserialize, Serialize};
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
10#[serde(rename_all = "snake_case")]
11pub enum AddressType {
12 Public,
14 Random,
16}
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum RandomKind {
21 Static,
23 Resolvable,
25 NonResolvable,
27 Reserved,
29}
30
31#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
34pub struct Address {
35 pub kind: AddressType,
37 pub bytes: [u8; 6],
39}
40
41impl Address {
42 pub const fn public(bytes: [u8; 6]) -> Self {
44 Address {
45 kind: AddressType::Public,
46 bytes,
47 }
48 }
49
50 pub const fn random(bytes: [u8; 6]) -> Self {
52 Address {
53 kind: AddressType::Random,
54 bytes,
55 }
56 }
57
58 pub fn random_kind(&self) -> Option<RandomKind> {
60 (self.kind == AddressType::Random).then(|| match self.bytes[5] >> 6 {
61 0b11 => RandomKind::Static,
62 0b01 => RandomKind::Resolvable,
63 0b00 => RandomKind::NonResolvable,
64 _ => RandomKind::Reserved,
65 })
66 }
67
68 pub fn is_resolvable(&self) -> bool {
70 self.random_kind() == Some(RandomKind::Resolvable)
71 }
72
73 pub fn hci_type(&self) -> u8 {
75 match self.kind {
76 AddressType::Public => 0,
77 AddressType::Random => 1,
78 }
79 }
80
81 pub fn from_hci(kind: u8, bytes: [u8; 6]) -> Self {
84 Address {
85 kind: if kind & 1 == 0 {
86 AddressType::Public
87 } else {
88 AddressType::Random
89 },
90 bytes,
91 }
92 }
93
94 pub fn new_static_random() -> Self {
96 let mut b = [0u8; 6];
97 crate::crypto::random_bytes(&mut b);
98 b[5] |= 0xc0;
99 Address::random(b)
100 }
101}
102
103impl fmt::Display for Address {
104 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106 let b = &self.bytes;
107 write!(
108 f,
109 "{:02X}:{:02X}:{:02X}:{:02X}:{:02X}:{:02X}",
110 b[5], b[4], b[3], b[2], b[1], b[0]
111 )
112 }
113}
114
115impl fmt::Debug for Address {
116 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117 match self.kind {
118 AddressType::Public => write!(f, "{self}"),
119 AddressType::Random => write!(f, "{self}/random"),
120 }
121 }
122}
123
124#[derive(Debug, Clone, thiserror::Error)]
126#[error("not a Bluetooth address: {0:?} (want AA:BB:CC:DD:EE:FF, optionally /public or /random)")]
127pub struct AddressParseError(String);
128
129impl FromStr for Address {
130 type Err = AddressParseError;
131
132 fn from_str(s: &str) -> Result<Self, Self::Err> {
135 let err = || AddressParseError(s.to_string());
136 let (addr, kind) = match s.rsplit_once('/') {
137 Some((a, "random")) => (a, AddressType::Random),
138 Some((a, "public")) => (a, AddressType::Public),
139 Some(_) => return Err(err()),
140 None => (s, AddressType::Public),
141 };
142 let hex: String = addr.chars().filter(|c| *c != ':' && *c != '-').collect();
143 let v = hex::decode(&hex).map_err(|_| err())?;
144 let mut bytes: [u8; 6] = v.try_into().map_err(|_| err())?;
145 bytes.reverse();
146 Ok(Address { kind, bytes })
147 }
148}
149
150impl Serialize for Address {
151 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
152 s.collect_str(&format_args!("{self:?}"))
153 }
154}
155
156impl<'de> Deserialize<'de> for Address {
157 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
158 let s = String::deserialize(d)?;
159 s.parse().map_err(serde::de::Error::custom)
160 }
161}
162
163#[cfg(test)]
164mod tests {
165 use super::*;
166
167 #[test]
168 fn parse_print() {
169 let a: Address = "C0:11:22:33:44:55/random".parse().unwrap();
170 assert_eq!(a.bytes, [0x55, 0x44, 0x33, 0x22, 0x11, 0xc0]);
171 assert_eq!(a.random_kind(), Some(RandomKind::Static));
172 assert_eq!(a.to_string(), "C0:11:22:33:44:55");
173 assert_eq!(format!("{a:?}"), "C0:11:22:33:44:55/random");
174 let p: Address = "bc5729000001".parse().unwrap();
175 assert_eq!(p.kind, AddressType::Public);
176 assert!(p.random_kind().is_none());
177 assert!("zz".parse::<Address>().is_err());
178 assert!(Address::new_static_random().random_kind() == Some(RandomKind::Static));
179 }
180}