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
use proc_macro::TokenStream as RawTokenStream;
use proc_macro2::{Span, TokenStream};
use quote::quote;
use std::ffi::CString;
use syn::parse::{Parse, ParseBuffer};
use syn::{Error, Ident, LitByteStr, LitStr, Result};
#[proc_macro]
pub fn cstr(input: RawTokenStream) -> RawTokenStream {
let tokens = match build_byte_str(input.into()) {
Ok(s) => quote!(unsafe { ::std::ffi::CStr::from_bytes_with_nul_unchecked(#s) }),
Err(e) => e.to_compile_error(),
};
tokens.into()
}
fn build_byte_str(input: TokenStream) -> Result<LitByteStr> {
let Input(bytes, span) = syn::parse2::<Input>(input)?;
CString::new(bytes)
.map(|s| LitByteStr::new(s.as_bytes_with_nul(), span))
.map_err(|_| Error::new(span, "nul byte found in the literal"))
}
struct Input(Vec<u8>, Span);
impl Parse for Input {
fn parse<'a>(input: &'a ParseBuffer<'a>) -> Result<Self> {
let lookahead = input.lookahead1();
if lookahead.peek(LitByteStr) {
let b = input.parse::<LitByteStr>().unwrap();
return Ok(Input(b.value(), b.span()));
}
if lookahead.peek(LitStr) {
let s = input.parse::<LitStr>().unwrap();
return Ok(Input(s.value().into_bytes(), s.span()));
}
if lookahead.peek(Ident) {
let i = input.parse::<Ident>().unwrap();
return Ok(Input(i.to_string().into_bytes(), i.span()));
}
Err(lookahead.error())
}
}