Skip to main content

bluetooth_adv/
uuid.rs

1//! Bluetooth UUIDs in their three wire sizes.
2
3use core::fmt;
4
5/// The Bluetooth Base UUID, `00000000-0000-1000-8000-00805F9B34FB`, most
6/// significant byte first.
7pub const BASE_UUID: [u8; 16] = [
8    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb,
9];
10
11/// A Bluetooth UUID as it appeared on the wire: 16, 32 or 128 bits.
12///
13/// 16 and 32-bit UUIDs are shorthand for UUIDs on the Bluetooth Base UUID;
14/// [`Uuid::to_u128_bytes`] expands them, and equality compares the expanded
15/// forms, so `Uuid16(0x180f) == Uuid128(0000180f-0000-1000-8000-00805f9b34fb)`.
16#[derive(Debug, Clone, Copy, Eq)]
17pub enum Uuid {
18    /// A 16-bit UUID.
19    Uuid16(u16),
20    /// A 32-bit UUID.
21    Uuid32(u32),
22    /// A 128-bit UUID, most significant byte first (as written).
23    Uuid128([u8; 16]),
24}
25
26impl Uuid {
27    /// Reads a UUID from its little-endian wire form, by length (2, 4 or 16 bytes).
28    pub fn from_le_bytes(b: &[u8]) -> Option<Uuid> {
29        match b.len() {
30            2 => Some(Uuid::Uuid16(u16::from_le_bytes([b[0], b[1]]))),
31            4 => Some(Uuid::Uuid32(u32::from_le_bytes([b[0], b[1], b[2], b[3]]))),
32            16 => {
33                let mut a = [0u8; 16];
34                for (i, x) in b.iter().rev().enumerate() {
35                    a[i] = *x;
36                }
37                Some(Uuid::Uuid128(a))
38            }
39            _ => None,
40        }
41    }
42
43    /// The little-endian wire form, in its own size.
44    pub fn to_le_bytes(&self) -> Vec<u8> {
45        match self {
46            Uuid::Uuid16(v) => v.to_le_bytes().to_vec(),
47            Uuid::Uuid32(v) => v.to_le_bytes().to_vec(),
48            Uuid::Uuid128(a) => a.iter().rev().copied().collect(),
49        }
50    }
51
52    /// The full 128-bit form, most significant byte first.
53    pub fn to_u128_bytes(&self) -> [u8; 16] {
54        match self {
55            Uuid::Uuid16(v) => Self::expand(u32::from(*v)),
56            Uuid::Uuid32(v) => Self::expand(*v),
57            Uuid::Uuid128(a) => *a,
58        }
59    }
60
61    fn expand(v: u32) -> [u8; 16] {
62        let mut a = BASE_UUID;
63        a[..4].copy_from_slice(&v.to_be_bytes());
64        a
65    }
66
67    /// The shortest form: a 128-bit UUID on the Base UUID becomes 16 or 32 bits.
68    pub fn shortened(&self) -> Uuid {
69        let a = self.to_u128_bytes();
70        if a[4..] == BASE_UUID[4..] {
71            let v = u32::from_be_bytes([a[0], a[1], a[2], a[3]]);
72            match u16::try_from(v) {
73                Ok(s) => Uuid::Uuid16(s),
74                Err(_) => Uuid::Uuid32(v),
75            }
76        } else {
77            Uuid::Uuid128(a)
78        }
79    }
80
81    /// The 16-bit value, when this UUID has one.
82    pub fn as_u16(&self) -> Option<u16> {
83        match self.shortened() {
84            Uuid::Uuid16(v) => Some(v),
85            _ => None,
86        }
87    }
88
89    /// The SIG's name for this UUID, from the assigned numbers.
90    pub fn name(&self) -> Option<&'static str> {
91        self.as_u16()
92            .and_then(bluetooth_numbers::uuid16)
93            .map(|u| u.name)
94    }
95
96    /// Parses `180f`, `0x180f`, `0000180f` or the canonical
97    /// `0000180f-0000-1000-8000-00805f9b34fb` form.
98    pub fn parse(s: &str) -> Option<Uuid> {
99        let s = s.trim();
100        let s = s
101            .strip_prefix("0x")
102            .or_else(|| s.strip_prefix("0X"))
103            .unwrap_or(s);
104        let hex: String = s.chars().filter(|c| *c != '-').collect();
105        match hex.len() {
106            4 => u16::from_str_radix(&hex, 16).ok().map(Uuid::Uuid16),
107            8 => u32::from_str_radix(&hex, 16).ok().map(Uuid::Uuid32),
108            32 => {
109                let v = hex::decode(&hex).ok()?;
110                let a: [u8; 16] = v.try_into().ok()?;
111                Some(Uuid::Uuid128(a))
112            }
113            _ => None,
114        }
115    }
116}
117
118impl PartialEq for Uuid {
119    fn eq(&self, other: &Self) -> bool {
120        self.to_u128_bytes() == other.to_u128_bytes()
121    }
122}
123
124impl core::hash::Hash for Uuid {
125    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
126        self.to_u128_bytes().hash(state);
127    }
128}
129
130impl PartialOrd for Uuid {
131    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
132        Some(self.cmp(other))
133    }
134}
135
136impl Ord for Uuid {
137    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
138        self.to_u128_bytes().cmp(&other.to_u128_bytes())
139    }
140}
141
142impl From<u16> for Uuid {
143    fn from(v: u16) -> Self {
144        Uuid::Uuid16(v)
145    }
146}
147
148impl fmt::Display for Uuid {
149    /// 16 and 32-bit UUIDs print as 4 or 8 hex digits, 128-bit ones in the
150    /// canonical hyphenated form; all lower case.
151    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152        match self {
153            Uuid::Uuid16(v) => write!(f, "{v:04x}"),
154            Uuid::Uuid32(v) => write!(f, "{v:08x}"),
155            Uuid::Uuid128(a) => {
156                let h = hex::encode(a);
157                write!(
158                    f,
159                    "{}-{}-{}-{}-{}",
160                    &h[0..8],
161                    &h[8..12],
162                    &h[12..16],
163                    &h[16..20],
164                    &h[20..32]
165                )
166            }
167        }
168    }
169}
170
171#[cfg(feature = "serde")]
172impl serde::Serialize for Uuid {
173    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
174        s.collect_str(self)
175    }
176}
177
178#[cfg(feature = "serde")]
179impl<'de> serde::Deserialize<'de> for Uuid {
180    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
181        let s = <String as serde::Deserialize>::deserialize(d)?;
182        Uuid::parse(&s).ok_or_else(|| serde::de::Error::custom(format!("not a UUID: {s}")))
183    }
184}
185
186#[cfg(test)]
187mod tests {
188    use super::*;
189
190    #[test]
191    fn forms_and_equality() {
192        let short = Uuid::Uuid16(0x180f);
193        let long = Uuid::parse("0000180f-0000-1000-8000-00805f9b34fb").unwrap();
194        assert_eq!(short, long);
195        assert_eq!(long.shortened(), Uuid::Uuid16(0x180f));
196        assert_eq!(short.to_string(), "180f");
197        assert_eq!(long.to_string(), "0000180f-0000-1000-8000-00805f9b34fb");
198        assert_eq!(Uuid::from_le_bytes(&[0x0f, 0x18]), Some(short));
199        let wire = long.to_le_bytes();
200        assert_eq!(Uuid::from_le_bytes(&wire), Some(long));
201        assert_eq!(short.name(), Some("Battery"));
202        assert_eq!(Uuid::parse("0x2A19"), Some(Uuid::Uuid16(0x2a19)));
203        assert_eq!(Uuid::parse("nope"), None);
204    }
205}