1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
use std::fmt::{Debug, Display, Formatter};
use std::hash::{Hash, Hasher};
use std::num::{NonZeroU128, NonZeroU16};
use std::ops::Deref;
use std::ptr;

use num_enum::TryFromPrimitive;
use structbuf::{Packer, Unpack};

const SHIFT: u32 = u128::BITS - u32::BITS;
const BASE: u128 = 0x00000000_0000_1000_8000_00805F9B34FB;
const MASK_16: u128 = !((u16::MAX as u128) << SHIFT);
const MASK_32: u128 = !((u32::MAX as u128) << SHIFT);

/// 16-, 32-, or 128-bit UUID ([Vol 3] Part B, Section 2.5.1).
#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[repr(transparent)]
pub struct Uuid(NonZeroU128);

impl Uuid {
    /// UUID size in bytes.
    pub const BYTES: usize = std::mem::size_of::<Self>();
    /// Maximum UUID value.
    pub const MAX: Self = Self(
        // SAFETY: Non-zero
        unsafe { NonZeroU128::new_unchecked(u128::MAX) },
    );

    /// Creates a UUID from a `u128`.
    #[inline]
    #[must_use]
    pub const fn new(v: u128) -> Option<Self> {
        match NonZeroU128::new(v) {
            Some(nz) => Some(Self(nz)),
            None => None,
        }
    }

    /// Creates a UUID from a `u128` without checking whether the value is
    /// non-zero.
    ///
    /// # Safety
    ///
    /// The value must not be zero.
    #[inline]
    #[must_use]
    pub const unsafe fn new_unchecked(v: u128) -> Self {
        Self(NonZeroU128::new_unchecked(v))
    }

    /// Returns the UUID type. Returns [`UuidType::NonSig`] for non-SIG UUID.
    #[inline]
    #[must_use]
    pub fn typ(self) -> UuidType {
        self.as_uuid16().map_or(UuidType::NonSig, Uuid16::typ)
    }

    /// Returns a [`Uuid16`] representation or [`None`] if the UUID is not an
    /// assigned 16-bit UUID.
    #[inline]
    #[must_use]
    pub fn as_uuid16(self) -> Option<Uuid16> {
        self.as_u16().map(uuid16)
    }

    /// Converts an assigned 16-bit Bluetooth SIG UUID to `u16`. This is
    /// mutually exclusive with `as_u32` and `as_u128`.
    #[inline]
    #[must_use]
    pub fn as_u16(self) -> Option<u16> {
        #[allow(clippy::cast_possible_truncation)]
        let v = (self.0.get() >> SHIFT) as u16;
        (self.0.get() & MASK_16 == BASE && v > 0).then_some(v)
    }

    /// Converts an assigned 32-bit Bluetooth SIG UUID to `u32`. This is
    /// mutually exclusive with `as_u16` and `as_u128`.
    #[inline]
    #[must_use]
    pub fn as_u32(self) -> Option<u32> {
        let v = (self.0.get() >> SHIFT) as u32;
        (self.0.get() & MASK_32 == BASE && v > u32::from(u16::MAX)).then_some(v)
    }

    /// Converts an unassigned UUID to `u128`. This is mutually exclusive with
    /// `as_u16` and `as_u32`.
    #[inline]
    #[must_use]
    pub fn as_u128(self) -> Option<u128> {
        (self.0.get() & MASK_32 != BASE).then_some(self.0.get())
    }

    /// Returns the UUID as a little-endian byte array.
    #[inline]
    #[must_use]
    pub const fn to_bytes(self) -> [u8; Self::BYTES] {
        self.0.get().to_le_bytes()
    }
}

impl From<Uuid16> for Uuid {
    #[inline]
    fn from(u: Uuid16) -> Self {
        u.as_uuid()
    }
}

impl TryFrom<&[u8]> for Uuid {
    type Error = ();

    #[inline]
    fn try_from(v: &[u8]) -> Result<Self, Self::Error> {
        match v.len() {
            Self::BYTES => Self::new(v.unpack().u128()),
            Uuid16::BYTES => Uuid16::new(v.unpack().u16()).map(Uuid16::as_uuid),
            _ => None,
        }
        .ok_or(())
    }
}

impl Debug for Uuid {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        #[allow(clippy::cast_possible_truncation)]
        if let Some(v) = self.as_u16() {
            write!(f, "{v:#06X}")
        } else if let Some(v) = self.as_u32() {
            write!(f, "{v:#010X}")
        } else {
            let v = self.0.get();
            write!(
                f,
                "{:08X}-{:04X}-{:04X}-{:04X}-{:012X}",
                (v >> 96) as u32,
                (v >> 80) as u16,
                (v >> 64) as u16,
                (v >> 48) as u16,
                (v & ((1 << 48) - 1)) as u64
            )
        }
    }
}

impl Display for Uuid {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self.typ() {
            UuidType::NonSig => Debug::fmt(self, f),
            typ => Debug::fmt(&typ, f),
        }
    }
}

impl From<Uuid> for u128 {
    #[inline]
    fn from(u: Uuid) -> Self {
        u.0.get()
    }
}

/// 16-bit Bluetooth SIG UUID.
#[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd)]
#[repr(transparent)]
pub struct Uuid16(NonZeroU16);

impl Uuid16 {
    /// UUID size in bytes.
    pub const BYTES: usize = std::mem::size_of::<Self>();

    /// Creates a 16-bit SIG UUID from a `u16`.
    #[inline]
    #[must_use]
    pub const fn new(v: u16) -> Option<Self> {
        match NonZeroU16::new(v) {
            Some(nz) => Some(Self(nz)),
            None => None,
        }
    }

    /// Returns the UUID type.
    #[inline(always)]
    pub fn typ(self) -> UuidType {
        let u = self.0.get();
        // SAFETY: UUID_MAP has 256 entries
        (unsafe { &*UUID_MAP.as_ptr().add((u >> 8) as _) })(u)
    }

    /// Returns 128-bit UUID representation.
    #[inline]
    #[must_use]
    pub const fn as_uuid(self) -> Uuid {
        // TODO: Use NonZeroU128::from() when it is const
        // SAFETY: Always non-zero
        unsafe { Uuid::new_unchecked((self.0.get() as u128) << SHIFT | BASE) }
    }

    /// Returns the raw 16-bit UUID value.
    #[inline(always)]
    #[must_use]
    pub(crate) const fn raw(self) -> u16 {
        self.0.get()
    }

    /// Returns the UUID as a little-endian byte array.
    #[inline]
    #[must_use]
    pub const fn to_bytes(self) -> [u8; Self::BYTES] {
        self.0.get().to_le_bytes()
    }
}

impl Debug for Uuid16 {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:#06X}", self.0.get())
    }
}

impl Display for Uuid16 {
    #[inline(always)]
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        Debug::fmt(&self.typ(), f)
    }
}

#[allow(clippy::derived_hash_with_manual_eq)]
impl Hash for Uuid16 {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.as_uuid().hash(state);
    }
}

impl From<Uuid16> for u16 {
    #[inline]
    fn from(u: Uuid16) -> Self {
        u.raw()
    }
}

/// 16-bit UUID type.
#[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd)]
#[non_exhaustive]
pub enum UuidType {
    Protocol(u16),
    ServiceClass(ServiceClass),
    Service(Service),
    Unit(Unit),
    Declaration(Declaration),
    Descriptor(Descriptor),
    Characteristic(Characteristic),
    // TODO: Are Member Service UUIDs used anywhere?
    // ([Assigned Numbers] Section 3.11)
    Member(u16),
    Unknown(u16),
    NonSig,
}

impl From<Uuid> for UuidType {
    #[inline(always)]
    fn from(u: Uuid) -> Self {
        u.typ()
    }
}

impl From<Uuid16> for UuidType {
    #[inline(always)]
    fn from(u: Uuid16) -> Self {
        u.typ()
    }
}

type UuidMap = [fn(u16) -> UuidType; 256];

static UUID_MAP: UuidMap = {
    use UuidType::*;
    #[inline(always)]
    fn is<T: TryFromPrimitive<Primitive = u16>>(u: u16, f: impl FnOnce(T) -> UuidType) -> UuidType {
        T::try_from_primitive(u).map_or(Unknown(u), f)
    }
    let mut m: UuidMap = [Unknown; 256];
    m[0x00] = Protocol;
    m[0x01] = Protocol;
    m[0x10] = |u| is(u, ServiceClass);
    m[0x11] = |u| is(u, ServiceClass);
    m[0x12] = |u| is(u, ServiceClass);
    m[0x13] = |u| is(u, ServiceClass);
    m[0x14] = |u| is(u, ServiceClass);
    m[0x18] = |u| is(u, Service);
    m[0x27] = |u| is(u, Unit);
    m[0x28] = |u| is(u, Declaration);
    m[0x29] = |u| is(u, Descriptor);
    m[0x2A] = |u| is(u, Characteristic);
    m[0x2B] = |u| is(u, Characteristic);
    m[0xFC] = Member;
    m[0xFD] = Member;
    m[0xFE] = Member;
    m
};

impl Debug for UuidType {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        use UuidType::*;
        match *self {
            Protocol(u) => (f.debug_tuple("Protocol").field(&format_args!("{u:#06X}"))).finish(),
            ServiceClass(ref u) => f.debug_tuple("ServiceClass").field(u).finish(),
            Service(ref u) => f.debug_tuple("Service").field(u).finish(),
            Unit(ref u) => f.debug_tuple("Unit").field(u).finish(),
            Declaration(ref u) => f.debug_tuple("Declaration").field(u).finish(),
            Descriptor(ref u) => f.debug_tuple("Descriptor").field(u).finish(),
            Characteristic(ref u) => f.debug_tuple("Characteristic").field(u).finish(),
            Member(id) => f.debug_tuple("Company").field(&id).finish(),
            Unknown(u) => (f.debug_tuple("Unknown").field(&format_args!("{u:#06X}"))).finish(),
            NonSig => f.write_str("NonSig"),
        }
    }
}

impl Display for UuidType {
    #[inline(always)]
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        Debug::fmt(self, f)
    }
}

/// An owned little-endian vector representation of a UUID.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct UuidVec {
    n: u8,
    v: [u8; Uuid::BYTES],
}

impl UuidVec {
    /// Creates a vector representation of a UUID.
    #[inline]
    #[must_use]
    pub fn new(u: Uuid) -> Self {
        let (n, v) = u.as_uuid16().map_or_else(
            || (Uuid::BYTES, u.to_bytes()),
            |u| {
                let mut v = [0; Uuid::BYTES];
                v[..Uuid16::BYTES].copy_from_slice(&u.to_bytes());
                (Uuid16::BYTES, v)
            },
        );
        #[allow(clippy::cast_possible_truncation)]
        Self { n: n as _, v }
    }
}

impl Deref for UuidVec {
    type Target = [u8];

    #[inline(always)]
    fn deref(&self) -> &Self::Target {
        // SAFETY: `n` is 0, 2, or 16
        unsafe { &*ptr::slice_from_raw_parts(self.v.as_ptr().cast(), self.n as _) }
    }
}

/// Packer extension functions.
pub trait UuidPacker {
    fn uuid(&mut self, u: impl Into<Uuid>);
}

impl UuidPacker for Packer<'_> {
    /// Writes either a 16- or a 128-bit UUID at the current index.
    #[inline]
    fn uuid(&mut self, u: impl Into<Uuid>) {
        let u = u.into();
        match u.as_u16() {
            Some(u) => self.u16(u),
            None => self.u128(u),
        };
    }
}

/// Creates an assigned 16-bit SIG UUID from a `u16`.
#[inline]
#[must_use]
const fn uuid16(v: u16) -> Uuid16 {
    // SAFETY: All crate uses guarantee that v != 0
    Uuid16(unsafe { NonZeroU16::new_unchecked(v) })
}

/// Provides implementations for a 16-bit UUID enum.
macro_rules! uuid16_enum {
    (
        $(#[$outer:meta])*
        $vis:vis enum $typ:ident {
            $($item:ident = $uuid:literal,)+
        }
    ) => {
        $(#[$outer])*
        #[derive(
            Clone,
            Copy,
            Debug,
            Eq,
            Ord,
            PartialEq,
            PartialOrd,
            ::num_enum::IntoPrimitive,
            ::num_enum::TryFromPrimitive,
        )]
        #[cfg_attr(test, derive(enum_iterator::Sequence))]
        #[non_exhaustive]
        #[repr(u16)]
        $vis enum $typ {
            $($item = $uuid,)+
        }

        impl $typ {
            ::paste::paste! {$(
                pub const [<$item:snake:upper>]: $crate::Uuid16 = Self::$item.uuid16();
            )+}

            /// Returns the `Uuid` representation of the variant.
            #[inline]
            #[must_use]
            pub const fn uuid(self) -> $crate::Uuid {
                self.uuid16().as_uuid()
            }

            /// Returns the `Uuid16` representation of the variant.
            #[inline(always)]
            #[must_use]
            pub const fn uuid16(self) -> $crate::Uuid16 {
                uuid16(self as _)
            }
        }

        impl ::core::fmt::Display for $typ {
            #[inline(always)]
            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                ::core::fmt::Debug::fmt(self, f)
            }
        }

        impl ::core::convert::TryFrom<$crate::Uuid16> for $typ {
            type Error = ::num_enum::TryFromPrimitiveError<Self>;

            #[inline]
            fn try_from(u: $crate::Uuid16) -> Result<Self, Self::Error> {
                use ::num_enum::TryFromPrimitive;
                Self::try_from_primitive(u.raw())
            }
        }

        impl ::core::cmp::PartialEq<$crate::Uuid> for $typ {
            #[inline(always)]
            fn eq(&self, rhs: &$crate::Uuid) -> bool {
                // Converting to 128-bit avoids branches
                self.uuid() == *rhs
            }
        }

        impl ::core::cmp::PartialEq<$crate::Uuid16> for $typ {
            #[inline(always)]
            fn eq(&self, rhs: &$crate::Uuid16) -> bool {
                *self as u16 == rhs.raw()
            }
        }

        impl ::core::cmp::PartialEq<$typ> for $crate::Uuid {
            #[inline(always)]
            fn eq(&self, rhs: &$typ) -> bool {
                *self == rhs.uuid()
            }
        }

        impl ::core::cmp::PartialEq<$typ> for $crate::Uuid16 {
            #[inline(always)]
            fn eq(&self, rhs: &$typ) -> bool {
                self.raw() == *rhs as u16
            }
        }

        impl ::core::convert::From<$typ> for $crate::Uuid {
            #[inline]
            fn from(v: $typ) -> Self {
                v.uuid()
            }
        }

        impl ::core::convert::From<$typ> for $crate::Uuid16 {
            #[inline]
            fn from(v: $typ) -> Self {
                v.uuid16()
            }
        }
    }
}

include!("uuid16.rs");

#[cfg(test)]
mod tests {
    use enum_iterator::all;

    use super::*;

    #[test]
    fn uuid_type() {
        assert_eq!(uuid16(0x0001).typ(), UuidType::Protocol(0x0001));
        for v in all::<ServiceClass>() {
            assert_eq!(v.uuid16().typ(), UuidType::ServiceClass(v));
        }
        for v in all::<Service>() {
            assert_eq!(v.uuid16().typ(), UuidType::Service(v));
        }
        for v in all::<Unit>() {
            assert_eq!(v.uuid16().typ(), UuidType::Unit(v));
        }
        for v in all::<Declaration>() {
            assert_eq!(v.uuid16().typ(), UuidType::Declaration(v));
        }
        for v in all::<Descriptor>() {
            assert_eq!(v.uuid16().typ(), UuidType::Descriptor(v));
        }
        for v in all::<Characteristic>() {
            assert_eq!(v.uuid16().typ(), UuidType::Characteristic(v));
        }
        assert_eq!(uuid16(0xFEFF).typ(), UuidType::Member(0xFEFF));
        assert_eq!(uuid16(0xFFFF).typ(), UuidType::Unknown(0xFFFF));
    }
}