const_c_str_impl/
lib.rs

1extern crate proc_macro;
2
3use proc_macro::TokenStream;
4use proc_macro_hack::proc_macro_hack;
5
6use quote::quote;
7use syn::parse_macro_input;
8
9#[proc_macro_hack]
10pub fn c_str(input: TokenStream) -> TokenStream {
11    let input = parse_macro_input!(input as syn::LitStr);
12
13    let mut bytes = input.value().into_bytes();
14    bytes.push(0);
15
16    TokenStream::from(
17        if let Some(_) = std::ffi::CStr::from_bytes_with_nul(&bytes).err() {
18            syn::Error::new_spanned(input, "The string contains interior nul byte(s).")
19                .to_compile_error()
20        } else {
21            quote! {
22                unsafe { std::ffi::CStr::from_bytes_with_nul_unchecked(&[#(#bytes,)*]) }
23            }
24        },
25    )
26}