summaryrefslogtreecommitdiff
path: root/nrf-softdevice-macro/src/uuid.rs
blob: a2e4f3d315d448bc2d2e0b7f2867fc4ba2a697b2 (plain)
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
use core::str::FromStr;

use darling::FromMeta;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;

#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Uuid {
    Uuid16(u16),
    Uuid128([u8; 16]),
}

impl FromMeta for Uuid {
    fn from_string(value: &str) -> darling::Result<Self> {
        if let Ok(u) = uuid::Uuid::from_str(value) {
            let mut bytes = *u.as_bytes();
            bytes.reverse(); // Softdevice uses uuids in little endian format.
            return Ok(Uuid::Uuid128(bytes));
        }

        if value.len() == 4 {
            if let Ok(u) = u16::from_str_radix(value, 16) {
                return Ok(Uuid::Uuid16(u));
            }
        }

        Err(darling::Error::custom(
            "Invalid UUID (must be a 16-bit or 128-bit UUID)",
        ))
    }
}

impl quote::ToTokens for Uuid {
    fn to_tokens(&self, tokens: &mut TokenStream2) {
        match self {
            Uuid::Uuid16(u) => tokens.extend(quote!(::nrf_softdevice::ble::Uuid::new_16(#u))),
            Uuid::Uuid128(u) => {
                let mut s = TokenStream2::new();
                for b in u {
                    s.extend(quote!(#b,))
                }
                tokens.extend(quote!(::nrf_softdevice::ble::Uuid::new_128(&[#s])));
            }
        }
    }
}