Skip to main content

bluetooth_adv/
ad.rs

1//! AD structures (Core Specification Supplement, Part A) and the typed
2//! [`Advertisement`] built from them.
3
4use crate::reader::Reader;
5use crate::uuid::Uuid;
6use crate::AddressBytes;
7
8#[cfg(feature = "serde")]
9use serde::Serialize;
10
11#[cfg(feature = "serde")]
12pub(crate) fn ser_hex<S: serde::Serializer, T: AsRef<[u8]>>(
13    v: &T,
14    s: S,
15) -> Result<S::Ok, S::Error> {
16    s.serialize_str(&hex::encode(v.as_ref()))
17}
18
19#[cfg(feature = "serde")]
20fn ser_hex_opt<S: serde::Serializer, T: AsRef<[u8]>>(
21    v: &Option<T>,
22    s: S,
23) -> Result<S::Ok, S::Error> {
24    match v {
25        Some(v) => s.serialize_str(&hex::encode(v.as_ref())),
26        None => s.serialize_none(),
27    }
28}
29
30#[cfg(feature = "serde")]
31fn ser_addrs<S: serde::Serializer>(v: &[AddressBytes], s: S) -> Result<S::Ok, S::Error> {
32    s.collect_seq(v.iter().map(crate::format_address))
33}
34
35/// One AD structure: a type and its data, borrowed from the advertisement.
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub struct AdStructure<'a> {
38    /// The AD type.
39    pub ad_type: u8,
40    /// The data after the type.
41    pub data: &'a [u8],
42}
43
44impl AdStructure<'_> {
45    /// The SIG's name for the AD type.
46    pub fn type_name(&self) -> Option<&'static str> {
47        bluetooth_numbers::ad_type(self.ad_type)
48    }
49}
50
51/// Where an advertisement stopped making sense.
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53#[cfg_attr(feature = "serde", derive(Serialize))]
54pub struct Malformed {
55    /// Offset of the structure whose length runs past the end of the data.
56    pub offset: usize,
57}
58
59/// An iterator over the AD structures of advertising or scan response data.
60///
61/// A zero length octet ends the data early (the rest is padding, as the
62/// Core Specification allows); a length running past the end yields one
63/// [`Malformed`] and stops.
64#[derive(Debug, Clone)]
65pub struct AdStructures<'a> {
66    data: &'a [u8],
67    offset: usize,
68    done: bool,
69}
70
71impl<'a> AdStructures<'a> {
72    /// Iterates over `data`.
73    pub fn new(data: &'a [u8]) -> Self {
74        Self {
75            data,
76            offset: 0,
77            done: false,
78        }
79    }
80}
81
82impl<'a> Iterator for AdStructures<'a> {
83    type Item = Result<AdStructure<'a>, Malformed>;
84
85    fn next(&mut self) -> Option<Self::Item> {
86        if self.done || self.offset >= self.data.len() {
87            return None;
88        }
89        let len = usize::from(self.data[self.offset]);
90        if len == 0 {
91            self.done = true;
92            return None;
93        }
94        let start = self.offset + 1;
95        let end = start + len;
96        if end > self.data.len() {
97            self.done = true;
98            return Some(Err(Malformed {
99                offset: self.offset,
100            }));
101        }
102        self.offset = end;
103        Some(Ok(AdStructure {
104            ad_type: self.data[start],
105            data: &self.data[start + 1..end],
106        }))
107    }
108}
109
110/// The Flags AD type.
111#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
112#[cfg_attr(feature = "serde", derive(Serialize))]
113pub struct Flags {
114    /// The raw octet.
115    pub raw: u8,
116    /// LE Limited Discoverable Mode.
117    pub le_limited_discoverable: bool,
118    /// LE General Discoverable Mode.
119    pub le_general_discoverable: bool,
120    /// BR/EDR Not Supported.
121    pub br_edr_not_supported: bool,
122    /// Simultaneous LE and BR/EDR to Same Device Capable (Controller).
123    pub le_br_edr_controller: bool,
124}
125
126impl From<u8> for Flags {
127    fn from(raw: u8) -> Self {
128        Flags {
129            raw,
130            le_limited_discoverable: raw & 0x01 != 0,
131            le_general_discoverable: raw & 0x02 != 0,
132            br_edr_not_supported: raw & 0x04 != 0,
133            le_br_edr_controller: raw & 0x08 != 0,
134        }
135    }
136}
137
138/// A service UUID listed in the advertisement.
139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
140#[cfg_attr(feature = "serde", derive(Serialize))]
141pub struct ServiceUuid {
142    /// The UUID.
143    pub uuid: Uuid,
144    /// Whether it came from a complete list (rather than an incomplete one).
145    pub complete: bool,
146    /// The SIG's name for it.
147    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
148    pub name: Option<&'static str>,
149}
150
151/// The device's local name.
152#[derive(Debug, Clone, PartialEq, Eq)]
153#[cfg_attr(feature = "serde", derive(Serialize))]
154pub struct LocalName {
155    /// The name, with invalid UTF-8 replaced.
156    pub name: String,
157    /// Complete Local Name (rather than Shortened Local Name).
158    pub complete: bool,
159}
160
161/// Service data: a UUID and the bytes the service defines.
162#[derive(Debug, Clone, PartialEq, Eq)]
163#[cfg_attr(feature = "serde", derive(Serialize))]
164pub struct ServiceData {
165    /// The service UUID.
166    pub uuid: Uuid,
167    /// The SIG's name for the UUID.
168    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
169    pub name: Option<&'static str>,
170    /// The data.
171    #[cfg_attr(feature = "serde", serde(serialize_with = "ser_hex"))]
172    pub data: Vec<u8>,
173}
174
175/// Manufacturer specific data: a company identifier and the company's bytes.
176#[derive(Debug, Clone, PartialEq, Eq)]
177#[cfg_attr(feature = "serde", derive(Serialize))]
178pub struct ManufacturerData {
179    /// The Company Identifier.
180    pub company_id: u16,
181    /// The company it is assigned to.
182    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
183    pub company: Option<&'static str>,
184    /// The data after the identifier.
185    #[cfg_attr(feature = "serde", serde(serialize_with = "ser_hex"))]
186    pub data: Vec<u8>,
187}
188
189/// The Device ID AD type (EIR): who made the device and which product it is.
190#[derive(Debug, Clone, Copy, PartialEq, Eq)]
191#[cfg_attr(feature = "serde", derive(Serialize))]
192pub struct DeviceId {
193    /// 1: Bluetooth SIG company identifier, 2: USB Implementer's Forum vendor id.
194    pub vendor_id_source: u16,
195    /// The vendor.
196    pub vendor_id: u16,
197    /// The product.
198    pub product_id: u16,
199    /// The product version.
200    pub version: u16,
201}
202
203/// An AD structure kept as bytes: a type this crate names but whose contents
204/// belong to another layer (Mesh, LE Audio, ...), or a type the SIG has not
205/// assigned yet.
206#[derive(Debug, Clone, PartialEq, Eq)]
207#[cfg_attr(feature = "serde", derive(Serialize))]
208pub struct RawAd {
209    /// The AD type.
210    pub ad_type: u8,
211    /// The SIG's name for it.
212    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
213    pub name: Option<&'static str>,
214    /// The data.
215    #[cfg_attr(feature = "serde", serde(serialize_with = "ser_hex"))]
216    pub data: Vec<u8>,
217}
218
219/// Every field an advertisement (or a scan response, or both concatenated)
220/// can carry, read into typed values.
221///
222/// A field whose length is wrong for its type is kept in [`Advertisement::other`]
223/// instead, so nothing the device sent is lost.
224#[derive(Debug, Clone, Default, PartialEq)]
225#[cfg_attr(feature = "serde", derive(Serialize))]
226#[non_exhaustive]
227pub struct Advertisement {
228    /// Flags.
229    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
230    pub flags: Option<Flags>,
231    /// Service UUIDs, 16, 32 and 128-bit, complete and incomplete lists.
232    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Vec::is_empty"))]
233    pub services: Vec<ServiceUuid>,
234    /// Service Solicitation UUIDs.
235    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Vec::is_empty"))]
236    pub solicited_services: Vec<Uuid>,
237    /// Shortened or Complete Local Name (the complete one wins).
238    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
239    pub local_name: Option<LocalName>,
240    /// Broadcast_Name (LE Audio broadcasts).
241    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
242    pub broadcast_name: Option<String>,
243    /// TX Power Level, dBm.
244    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
245    pub tx_power: Option<i8>,
246    /// Appearance, raw.
247    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
248    pub appearance: Option<u16>,
249    /// Appearance category and subcategory names.
250    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
251    pub appearance_name: Option<String>,
252    /// Class of Device (BR/EDR), 24 bits.
253    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
254    pub class_of_device: Option<u32>,
255    /// Device ID.
256    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
257    pub device_id: Option<DeviceId>,
258    /// Service Data, 16, 32 and 128-bit.
259    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Vec::is_empty"))]
260    pub service_data: Vec<ServiceData>,
261    /// Manufacturer Specific Data (more than one is allowed in practice).
262    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Vec::is_empty"))]
263    pub manufacturer_data: Vec<ManufacturerData>,
264    /// Peripheral Connection Interval Range, in 1.25 ms units; 0xFFFF means no bound.
265    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
266    pub peripheral_connection_interval: Option<(u16, u16)>,
267    /// Advertising Interval (or Advertising Interval - long), in 0.625 ms units.
268    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
269    pub advertising_interval: Option<u32>,
270    /// Public Target Addresses.
271    #[cfg_attr(
272        feature = "serde",
273        serde(skip_serializing_if = "Vec::is_empty", serialize_with = "ser_addrs")
274    )]
275    pub public_target_addresses: Vec<AddressBytes>,
276    /// Random Target Addresses.
277    #[cfg_attr(
278        feature = "serde",
279        serde(skip_serializing_if = "Vec::is_empty", serialize_with = "ser_addrs")
280    )]
281    pub random_target_addresses: Vec<AddressBytes>,
282    /// LE Bluetooth Device Address: the address, and whether it is random.
283    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
284    pub le_address: Option<(String, bool)>,
285    /// LE Role: 0 peripheral only, 1 central only, 2 both preferring
286    /// peripheral, 3 both preferring central.
287    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
288    pub le_role: Option<u8>,
289    /// URI, with its scheme expanded from the assigned numbers.
290    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
291    pub uri: Option<String>,
292    /// LE Supported Features (bit mask, octet 0 first).
293    #[cfg_attr(
294        feature = "serde",
295        serde(
296            skip_serializing_if = "Option::is_none",
297            serialize_with = "ser_hex_opt"
298        )
299    )]
300    pub le_supported_features: Option<Vec<u8>>,
301    /// Resolvable Set Identifier (Coordinated Set Identification).
302    #[cfg_attr(
303        feature = "serde",
304        serde(
305            skip_serializing_if = "Option::is_none",
306            serialize_with = "ser_hex_opt"
307        )
308    )]
309    pub resolvable_set_identifier: Option<[u8; 6]>,
310    /// Security Manager TK Value (legacy OOB pairing).
311    #[cfg_attr(
312        feature = "serde",
313        serde(
314            skip_serializing_if = "Option::is_none",
315            serialize_with = "ser_hex_opt"
316        )
317    )]
318    pub sm_tk: Option<[u8; 16]>,
319    /// Security Manager Out of Band Flags.
320    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
321    pub sm_oob_flags: Option<u8>,
322    /// LE Secure Connections Confirmation Value (OOB).
323    #[cfg_attr(
324        feature = "serde",
325        serde(
326            skip_serializing_if = "Option::is_none",
327            serialize_with = "ser_hex_opt"
328        )
329    )]
330    pub le_sc_confirmation: Option<[u8; 16]>,
331    /// LE Secure Connections Random Value (OOB).
332    #[cfg_attr(
333        feature = "serde",
334        serde(
335            skip_serializing_if = "Option::is_none",
336            serialize_with = "ser_hex_opt"
337        )
338    )]
339    pub le_sc_random: Option<[u8; 16]>,
340    /// Simple Pairing Hash C-192 or C-256 (BR/EDR OOB), the last one seen.
341    #[cfg_attr(
342        feature = "serde",
343        serde(
344            skip_serializing_if = "Option::is_none",
345            serialize_with = "ser_hex_opt"
346        )
347    )]
348    pub ssp_hash: Option<[u8; 16]>,
349    /// Simple Pairing Randomizer R-192 or R-256, the last one seen.
350    #[cfg_attr(
351        feature = "serde",
352        serde(
353            skip_serializing_if = "Option::is_none",
354            serialize_with = "ser_hex_opt"
355        )
356    )]
357    pub ssp_randomizer: Option<[u8; 16]>,
358    /// Every other structure, by type, with its SIG name: Mesh, BIGInfo,
359    /// Indoor Positioning, Transport Discovery, Encrypted Advertising Data,
360    /// unassigned types, and any field whose length was wrong for its type.
361    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Vec::is_empty"))]
362    pub other: Vec<RawAd>,
363    /// Set when a structure's length ran past the end of the data; every
364    /// structure before it was still read.
365    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
366    pub malformed: Option<Malformed>,
367}
368
369impl Advertisement {
370    /// Reads every AD structure in `data`. Never fails: what cannot be read
371    /// is kept as bytes or marked [`Advertisement::malformed`].
372    pub fn parse(data: &[u8]) -> Advertisement {
373        let mut adv = Advertisement::default();
374        adv.extend(data);
375        adv
376    }
377
378    /// Adds the structures in `data` (a scan response, say) to this advertisement.
379    pub fn extend(&mut self, data: &[u8]) {
380        for s in AdStructures::new(data) {
381            match s {
382                Ok(s) => {
383                    if !self.add(s) {
384                        self.other.push(RawAd {
385                            ad_type: s.ad_type,
386                            name: s.type_name(),
387                            data: s.data.to_vec(),
388                        });
389                    }
390                }
391                Err(m) => self.malformed = Some(m),
392            }
393        }
394    }
395
396    /// Reads one structure into its field; `false` keeps it as raw bytes.
397    fn add(&mut self, s: AdStructure<'_>) -> bool {
398        let d = s.data;
399        let mut r = Reader::new(d);
400        match s.ad_type {
401            0x01 => match d {
402                [f, ..] => self.flags = Some(Flags::from(*f)),
403                [] => return false,
404            },
405            0x02..=0x07 => {
406                let size = match s.ad_type {
407                    0x02 | 0x03 => 2,
408                    0x04 | 0x05 => 4,
409                    _ => 16,
410                };
411                if !d.len().is_multiple_of(size) {
412                    return false;
413                }
414                let complete = s.ad_type % 2 == 1;
415                for c in d.chunks_exact(size) {
416                    if let Some(uuid) = Uuid::from_le_bytes(c) {
417                        self.services.push(ServiceUuid {
418                            uuid,
419                            complete,
420                            name: uuid.name(),
421                        });
422                    }
423                }
424            }
425            0x14 | 0x15 | 0x1f => {
426                let size = match s.ad_type {
427                    0x14 => 2,
428                    0x1f => 4,
429                    _ => 16,
430                };
431                if !d.len().is_multiple_of(size) {
432                    return false;
433                }
434                self.solicited_services
435                    .extend(d.chunks_exact(size).filter_map(Uuid::from_le_bytes));
436            }
437            0x08 | 0x09 => {
438                let complete = s.ad_type == 0x09;
439                if complete || self.local_name.as_ref().is_none_or(|n| !n.complete) {
440                    self.local_name = Some(LocalName {
441                        name: String::from_utf8_lossy(d).into_owned(),
442                        complete,
443                    });
444                }
445            }
446            0x30 => self.broadcast_name = Some(String::from_utf8_lossy(d).into_owned()),
447            0x0a => match d {
448                [p] => self.tx_power = Some(*p as i8),
449                _ => return false,
450            },
451            0x0d => match d {
452                [a, b, c] => self.class_of_device = Some(u32::from_le_bytes([*a, *b, *c, 0])),
453                _ => return false,
454            },
455            0x10 => match d.len() {
456                8 => {
457                    self.device_id = Some(DeviceId {
458                        vendor_id_source: r.u16_le().unwrap_or_default(),
459                        vendor_id: r.u16_le().unwrap_or_default(),
460                        product_id: r.u16_le().unwrap_or_default(),
461                        version: r.u16_le().unwrap_or_default(),
462                    })
463                }
464                16 => self.sm_tk = r.array(),
465                _ => return false,
466            },
467            0x11 => match d {
468                [f] => self.sm_oob_flags = Some(*f),
469                _ => return false,
470            },
471            0x12 => match (r.u16_le(), r.u16_le(), r.remaining()) {
472                (Some(min), Some(max), 0) => self.peripheral_connection_interval = Some((min, max)),
473                _ => return false,
474            },
475            0x16 | 0x20 | 0x21 => {
476                let size = match s.ad_type {
477                    0x16 => 2,
478                    0x20 => 4,
479                    _ => 16,
480                };
481                let Some(uuid) = r.take(size).and_then(Uuid::from_le_bytes) else {
482                    return false;
483                };
484                self.service_data.push(ServiceData {
485                    uuid,
486                    name: uuid.name(),
487                    data: r.rest().to_vec(),
488                });
489            }
490            0x17 | 0x18 => {
491                if d.is_empty() || !d.len().is_multiple_of(6) {
492                    return false;
493                }
494                let list = d.as_chunks::<6>().0.iter().copied();
495                if s.ad_type == 0x17 {
496                    self.public_target_addresses.extend(list);
497                } else {
498                    self.random_target_addresses.extend(list);
499                }
500            }
501            0x19 => match r.u16_le() {
502                Some(v) if r.remaining() == 0 => {
503                    self.appearance = Some(v);
504                    let a = bluetooth_numbers::appearance(v);
505                    self.appearance_name = match (a.category, a.subcategory) {
506                        (Some(c), Some(s)) => Some(format!("{c}: {s}")),
507                        (Some(c), None) => Some(c.to_string()),
508                        _ => None,
509                    };
510                }
511                _ => return false,
512            },
513            0x1a | 0x2f => match d.len() {
514                2..=4 => self.advertising_interval = r.uint_le(d.len()),
515                _ => return false,
516            },
517            0x1b => match (r.array::<6>(), r.u8(), r.remaining()) {
518                (Some(a), Some(t), 0) => {
519                    self.le_address = Some((crate::format_address(&a), t & 1 == 1))
520                }
521                _ => return false,
522            },
523            0x1c => match d {
524                [role] => self.le_role = Some(*role),
525                _ => return false,
526            },
527            0x0e | 0x1d => match r.array() {
528                Some(v) if r.remaining() == 0 => self.ssp_hash = Some(v),
529                _ => return false,
530            },
531            0x0f | 0x1e => match r.array() {
532                Some(v) if r.remaining() == 0 => self.ssp_randomizer = Some(v),
533                _ => return false,
534            },
535            0x22 => match r.array() {
536                Some(v) if r.remaining() == 0 => self.le_sc_confirmation = Some(v),
537                _ => return false,
538            },
539            0x23 => match r.array() {
540                Some(v) if r.remaining() == 0 => self.le_sc_random = Some(v),
541                _ => return false,
542            },
543            0x24 => match decode_uri(d) {
544                Some(u) => self.uri = Some(u),
545                None => return false,
546            },
547            0x27 => self.le_supported_features = Some(d.to_vec()),
548            0x2e => match r.array() {
549                Some(v) if r.remaining() == 0 => self.resolvable_set_identifier = Some(v),
550                _ => return false,
551            },
552            0xff => match r.u16_le() {
553                Some(company_id) => self.manufacturer_data.push(ManufacturerData {
554                    company_id,
555                    company: bluetooth_numbers::company(company_id),
556                    data: r.rest().to_vec(),
557                }),
558                None => return false,
559            },
560            _ => return false,
561        }
562        true
563    }
564
565    /// The service data for a UUID.
566    pub fn service_data_for(&self, uuid: impl Into<Uuid>) -> Option<&[u8]> {
567        let uuid = uuid.into();
568        self.service_data
569            .iter()
570            .find(|s| s.uuid == uuid)
571            .map(|s| s.data.as_slice())
572    }
573
574    /// The manufacturer data for a company.
575    pub fn manufacturer_data_for(&self, company_id: u16) -> Option<&[u8]> {
576        self.manufacturer_data
577            .iter()
578            .find(|m| m.company_id == company_id)
579            .map(|m| m.data.as_slice())
580    }
581}
582
583/// The URI AD type: the scheme is a UTF-8 encoded code point naming an
584/// assigned URI scheme (0x01 for none), then the rest of the URI.
585fn decode_uri(d: &[u8]) -> Option<String> {
586    let s = core::str::from_utf8(d).ok()?;
587    let mut chars = s.chars();
588    let code = chars.next()? as u32;
589    let rest = chars.as_str();
590    if code == 0x01 {
591        return Some(rest.to_string());
592    }
593    let scheme = bluetooth_numbers::uri_scheme(u16::try_from(code).ok()?)?;
594    Some(format!("{scheme}{rest}"))
595}
596
597#[cfg(test)]
598mod tests {
599    use super::*;
600
601    #[test]
602    fn structures_stop_at_padding_and_report_truncation() {
603        let all: Vec<_> = AdStructures::new(&[2, 1, 6, 0, 9, 9]).collect();
604        assert_eq!(
605            all,
606            vec![Ok(AdStructure {
607                ad_type: 1,
608                data: &[6]
609            })]
610        );
611        let all: Vec<_> = AdStructures::new(&[2, 1, 6, 5, 9, b'a']).collect();
612        assert_eq!(all[1], Err(Malformed { offset: 3 }));
613        assert!(AdStructures::new(&[]).next().is_none());
614    }
615
616    #[test]
617    fn parses_common_fields() {
618        let data = hex_lit(concat!(
619            "020106",                 // flags
620            "0303 0f18",              // complete 16-bit: battery
621            "0809 4b42 5072 6f2d 31", // "KBPro-1"
622            "020a f4",                // tx -12
623            "0319 c100",              // appearance: sports watch
624            "0516 0f18 6400",         // service data battery
625            "05ff 4c00 0102",         // apple
626            "0524 17 2f2f 61",        // URI https://a  (0x17 is "https:")
627            "03ee 0102",              // unassigned type
628        ));
629        let adv = Advertisement::parse(&data);
630        assert!(adv.flags.unwrap().le_general_discoverable);
631        assert_eq!(adv.services[0].uuid, Uuid::Uuid16(0x180f));
632        assert!(adv.services[0].complete);
633        assert_eq!(adv.local_name.as_ref().unwrap().name, "KBPro-1");
634        assert_eq!(adv.tx_power, Some(-12));
635        assert_eq!(adv.appearance_name.as_deref(), Some("Watch: Sports Watch"));
636        assert_eq!(adv.service_data_for(0x180f), Some(&[0x64, 0x00][..]));
637        assert_eq!(adv.manufacturer_data[0].company, Some("Apple, Inc."));
638        assert_eq!(adv.uri.as_deref(), Some("https://a"));
639        assert_eq!(adv.other[0].ad_type, 0xee);
640        assert!(adv.malformed.is_none());
641    }
642
643    #[test]
644    fn wrong_lengths_are_kept_raw() {
645        let adv = Advertisement::parse(&hex_lit("030a0102 0219 01"));
646        assert_eq!(adv.tx_power, None);
647        assert_eq!(adv.other.len(), 2);
648    }
649
650    pub(crate) fn hex_lit(s: &str) -> Vec<u8> {
651        hex::decode(s.replace(' ', "")).unwrap()
652    }
653}