hex_literal_impl/
lib.rs

1extern crate proc_macro;
2
3use proc_macro::{TokenStream, TokenTree, Delimiter};
4use proc_macro_hack::proc_macro_hack;
5
6fn is_hex_char(c: &char) -> bool {
7    match *c {
8        '0'..='9' | 'a'..='f' | 'A'..='F' => true,
9        _ => false,
10    }
11}
12
13fn is_format_char(c: &char) -> bool {
14    match *c {
15        ' ' | '\r' | '\n' | '\t' => true,
16        _ => false,
17    }
18}
19
20
21/// Strips any outer `Delimiter::None` groups from the input,
22/// returning a `TokenStream` consisting of the innermost
23/// non-empty-group `TokenTree`.
24/// This is used to handle a proc macro being invoked
25/// by a `macro_rules!` expansion.
26/// See https://github.com/rust-lang/rust/issues/72545 for background
27fn ignore_groups(mut input: TokenStream) -> TokenStream {
28    let mut tokens = input.clone().into_iter();
29    loop {
30        if let Some(TokenTree::Group(group)) = tokens.next() {
31            if group.delimiter() == Delimiter::None {
32                input = group.stream();
33                continue;
34            }
35        }
36        return input;
37    }
38}
39
40#[proc_macro_hack]
41pub fn hex(mut input: TokenStream) -> TokenStream {
42    input = ignore_groups(input);
43    let mut ts = input.into_iter();
44    let input = match (ts.next(), ts.next()) {
45        (Some(TokenTree::Literal(literal)), None) => literal.to_string(),
46        _ => panic!("expected one string literal"),
47    };
48
49    let bytes = input.as_bytes();
50    let n = bytes.len();
51    // trim quote characters
52    let input = &input[1..n-1];
53
54    for (i, c) in input.chars().enumerate() {
55        if !(is_hex_char(&c) || is_format_char(&c)) {
56            panic!("invalid character (position {}): {:?})", i + 1, c);
57        }
58    };
59    let n = input.chars().filter(is_hex_char).count() / 2;
60    let mut s = String::with_capacity(2 + 7*n);
61
62    s.push('[');
63    let mut iter = input.chars().filter(is_hex_char);
64    while let Some(c1) = iter.next() {
65        if let Some(c2) = iter.next() {
66            s += "0x";
67            s.push(c1);
68            s.push(c2);
69            s += "u8,";
70        } else {
71            panic!("expected even number of hex characters");
72        }
73    }
74    s.push(']');
75
76    s.parse().unwrap()
77}