Debian Codegraph @

third_party/rust/cstr/src/lib.rs

raw
1 //! A macro for getting `&'static CStr` from literal or identifier.
2 //!
3 //! This macro checks whether the given literal is valid for `CStr`
4 //! at compile time, and returns a static reference of `CStr`.
5 //!
6 //! This macro can be used to to initialize constants on Rust 1.64 and above.
7 //!
8 //! ## Example
9 //!
10 //! ```
11 //! use cstr::cstr;
12 //! use std::ffi::CStr;
13 //!
14 //! let test = cstr!(b"hello\xff");
15 //! assert_eq!(test, CStr::from_bytes_with_nul(b"hello\xff\0").unwrap());
16 //! let test = cstr!("hello");
17 //! assert_eq!(test, CStr::from_bytes_with_nul(b"hello\0").unwrap());
18 //! let test = cstr!(hello);
19 //! assert_eq!(test, CStr::from_bytes_with_nul(b"hello\0").unwrap());
20 //! ```
21
22 // While this isn't necessary when using Cargo >= 1.42, omitting it actually requires path-less
23 // `--extern proc_macro` to be passed to `rustc` when building this crate. Some tools may not do
24 // this correctly. So it's added as a precaution.
25 extern crate proc_macro;
26
27 use crate::parse::parse_input;
28 use proc_macro::TokenStream as RawTokenStream;
29 use proc_macro2::{Literal, Span, TokenStream};
30 use quote::{quote, quote_spanned};
31 use std::ffi::CString;
32
33 mod parse;
34
35 struct Error(Span, &'static str);
36
37 #[proc_macro]
38 pub fn cstr(input: RawTokenStream) -> RawTokenStream {
39 let tokens = match build_byte_str(input.into()) {
40 Ok(s) => quote!(unsafe { ::core::ffi::CStr::from_bytes_with_nul_unchecked(#s) }),
41 Err(Error(span, msg)) => quote_spanned!(span => compile_error!(#msg)),
42 };
43 tokens.into()
44 }
45
46 fn build_byte_str(input: TokenStream) -> Result<Literal, Error> {
47 let (bytes, span) = parse_input(input)?;
48 match CString::new(bytes) {
49 Ok(s) => {
50 let mut lit = Literal::byte_string(s.as_bytes_with_nul());
51 lit.set_span(span);
52 Ok(lit)
53 }
54 Err(_) => Err(Error(span, "nul byte found in the literal")),
55 }
56 }