Avoid needless escape of quotes
diff --git a/src/fallback.rs b/src/fallback.rs
index 05fe8ed..2ce32f1 100644
--- a/src/fallback.rs
+++ b/src/fallback.rs
@@ -734,17 +734,31 @@
}
pub fn string(t: &str) -> Literal {
- let mut s = t
- .chars()
- .flat_map(|c| c.escape_default())
- .collect::<String>();
- s.push('"');
- s.insert(0, '"');
- Literal::_new(s)
+ let mut text = String::with_capacity(t.len() + 2);
+ text.push('"');
+ for c in t.chars() {
+ if c == '\'' {
+ // escape_default turns this into "\'" which is unnecessary.
+ text.push(c);
+ } else {
+ text.extend(c.escape_default());
+ }
+ }
+ text.push('"');
+ Literal::_new(text)
}
pub fn character(t: char) -> Literal {
- Literal::_new(format!("'{}'", t.escape_default().collect::<String>()))
+ let mut text = String::new();
+ text.push('\'');
+ if t == '"' {
+ // escape_default turns this into '\"' which is unnecessary.
+ text.push(t);
+ } else {
+ text.extend(t.escape_default());
+ }
+ text.push('\'');
+ Literal::_new(text)
}
pub fn byte_string(bytes: &[u8]) -> Literal {
diff --git a/tests/test.rs b/tests/test.rs
index f5660c0..370392b 100644
--- a/tests/test.rs
+++ b/tests/test.rs
@@ -80,9 +80,21 @@
}
#[test]
-fn literals() {
+fn literal_string() {
assert_eq!(Literal::string("foo").to_string(), "\"foo\"");
assert_eq!(Literal::string("\"").to_string(), "\"\\\"\"");
+ assert_eq!(Literal::string("didn't").to_string(), "\"didn't\"");
+}
+
+#[test]
+fn literal_character() {
+ assert_eq!(Literal::character('x').to_string(), "'x'");
+ assert_eq!(Literal::character('\'').to_string(), "'\\''");
+ assert_eq!(Literal::character('"').to_string(), "'\"'");
+}
+
+#[test]
+fn literal_float() {
assert_eq!(Literal::f32_unsuffixed(10.0).to_string(), "10.0");
}