diff --git a/Cargo.toml b/Cargo.toml index e284d22..d8ab242 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,7 +13,7 @@ repository = "https://github.com/dtolnay/quote" rust-version = "1.56" [dependencies] -proc-macro2 = { version = "1.0.74", default-features = false } +proc-macro2 = { version = "1.0.80", default-features = false } [dev-dependencies] rustversion = "1.0" diff --git a/src/to_tokens.rs b/src/to_tokens.rs index 726e434..660a9ec 100644 --- a/src/to_tokens.rs +++ b/src/to_tokens.rs @@ -3,6 +3,7 @@ use alloc::borrow::Cow; use alloc::rc::Rc; use core::iter; use proc_macro2::{Group, Ident, Literal, Punct, Span, TokenStream, TokenTree}; +use std::ffi::{CStr, CString}; /// Types that can be interpolated inside a `quote!` invocation. /// @@ -221,6 +222,18 @@ impl ToTokens for bool { } } +impl ToTokens for CStr { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.append(Literal::c_string(self)); + } +} + +impl ToTokens for CString { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.append(Literal::c_string(self)); + } +} + impl ToTokens for Group { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append(self.clone()); diff --git a/tests/test.rs b/tests/test.rs index bc2919b..6ff1402 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -12,6 +12,7 @@ use proc_macro2::{Delimiter, Group, Ident, Span, TokenStream}; use quote::{format_ident, quote, quote_spanned, TokenStreamExt}; use std::borrow::Cow; use std::collections::BTreeSet; +use std::ffi::{CStr, CString}; struct X; @@ -232,6 +233,22 @@ fn test_string() { assert_eq!(expected, tokens.to_string()); } +#[test] +fn test_c_str() { + let s = CStr::from_bytes_with_nul(b"\x01 a 'b \" c\0").unwrap(); + let tokens = quote!(#s); + let expected = "c\"\\u{1} a 'b \\\" c\""; + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_c_string() { + let s = CString::new(&b"\x01 a 'b \" c"[..]).unwrap(); + let tokens = quote!(#s); + let expected = "c\"\\u{1} a 'b \\\" c\""; + assert_eq!(expected, tokens.to_string()); +} + #[test] fn test_interpolated_literal() { macro_rules! m { diff --git a/tests/ui/not-quotable.stderr b/tests/ui/not-quotable.stderr index 7bd2070..3196266 100644 --- a/tests/ui/not-quotable.stderr +++ b/tests/ui/not-quotable.stderr @@ -11,10 +11,10 @@ error[E0277]: the trait bound `Ipv4Addr: ToTokens` is not satisfied &'a T &'a mut T Box + CStr + CString Cow<'a, T> Option Rc - RepInterp - String and $N others = note: this error originates in the macro `quote` (in Nightly builds, run with -Z macro-backtrace for more info)