Do not quote \" and \' unnecessarily

This commit is contained in:
David Tolnay
2016-10-08 10:45:46 -07:00
parent f2ac6bd8e3
commit 6b76d2a2e6
2 changed files with 39 additions and 13 deletions
+19 -11
View File
@@ -24,19 +24,27 @@ impl<T: ToTokens> ToTokens for Option<T> {
}
}
macro_rules! impl_to_tokens_debug {
($ty:ty) => {
impl ToTokens for $ty {
fn to_tokens(&self, tokens: &mut Tokens) {
tokens.append(&format!("{:?}", self));
}
}
};
impl ToTokens for str {
fn to_tokens(&self, tokens: &mut Tokens) {
tokens.append(&format!("{:?}", self).replace("\\'", "'"));
}
}
impl_to_tokens_debug!(str);
impl_to_tokens_debug!(String);
impl_to_tokens_debug!(char);
impl ToTokens for String {
fn to_tokens(&self, tokens: &mut Tokens) {
tokens.append(&format!("{:?}", self).replace("\\'", "'"));
}
}
impl ToTokens for char {
fn to_tokens(&self, tokens: &mut Tokens) {
if *self == '"' {
tokens.append("'\"'");
} else {
tokens.append(&format!("{:?}", self));
}
}
}
#[derive(Debug)]
pub struct ByteStr<'a>(pub &'a str);
+20 -2
View File
@@ -156,13 +156,31 @@ fn test_floating() {
fn test_char() {
let zero = '\x00';
let pound = '#';
let quote = '"';
let apost = '\'';
let newline = '\n';
let heart = '\u{2764}';
let tokens = quote! {
#zero #pound #newline #heart
#zero #pound #quote #apost #newline #heart
};
let expected = "'\\u{0}' '#' '\\n' '\u{2764}' ";
let expected = "'\\u{0}' '#' '\"' '\\'' '\\n' '\u{2764}' ";
assert_eq!(expected, tokens.to_string());
}
#[test]
fn test_str() {
let s = "a 'b \" c";
let tokens = quote!(#s);
let expected = "\"a 'b \\\" c\" ";
assert_eq!(expected, tokens.to_string());
}
#[test]
fn test_string() {
let s = "a 'b \" c".to_string();
let tokens = quote!(#s);
let expected = "\"a 'b \\\" c\" ";
assert_eq!(expected, tokens.to_string());
}