Skip to main content

burble/hci/
handle.rs

1use std::fmt::{Debug, Formatter};
2use std::num::{NonZeroU16, NonZeroU8};
3
4use crate::name_of;
5
6/// Connection handle ([Vol 4] Part E, Section 5.4.2).
7#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
8#[repr(transparent)]
9pub struct ConnHandle(NonZeroU16);
10
11impl ConnHandle {
12    /// Number of meaningful bits.
13    pub(crate) const BITS: u16 = 12;
14    /// Maximum valid connection handle.
15    const MAX: u16 = 0xEFF;
16
17    /// Wraps a raw connection handle. Returns `None` if the handle is invalid.
18    #[inline]
19    #[must_use]
20    pub(crate) fn new(mut v: u16) -> Option<Self> {
21        v &= (1 << Self::BITS) - 1;
22        // SAFETY: v can't be 0xFFFF, so !v is never 0
23        (v <= Self::MAX).then_some(Self(unsafe { NonZeroU16::new_unchecked(!v) }))
24    }
25}
26
27impl From<ConnHandle> for u16 {
28    #[inline]
29    fn from(cn: ConnHandle) -> Self {
30        !cn.0.get()
31    }
32}
33
34impl Debug for ConnHandle {
35    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
36        write!(f, "{}({:#05X})", name_of!(ConnHandle), u16::from(*self))
37    }
38}
39
40/// Advertising set handle ([Vol 4] Part E, Section 7.8.53).
41#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
42#[repr(transparent)]
43pub struct AdvHandle(NonZeroU8);
44
45impl AdvHandle {
46    /// Minimum valid advertising handle.
47    pub(super) const MIN: u8 = 0x00;
48    /// Maximum valid advertising handle.
49    pub(super) const MAX: u8 = 0xEF;
50
51    /// Wraps a raw advertising handle. Returns `None` if the handle is invalid.
52    #[inline]
53    #[must_use]
54    pub(super) fn new(v: u8) -> Option<Self> {
55        // SAFETY: v can't be 0xFF, so !v is never 0
56        (v <= Self::MAX).then_some(Self(unsafe { NonZeroU8::new_unchecked(!v) }))
57    }
58}
59
60impl From<AdvHandle> for u8 {
61    #[inline]
62    fn from(h: AdvHandle) -> Self {
63        !h.0.get()
64    }
65}
66
67impl Debug for AdvHandle {
68    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
69        write!(f, "{}({:#04X})", name_of!(AdvHandle), u8::from(*self))
70    }
71}
72
73crate::impl_display_via_debug! { ConnHandle, AdvHandle }