chiark / gitweb /
Provide toml_quote_string
authorIan Jackson <ijackson@chiark.greenend.org.uk>
Sat, 14 May 2022 00:50:55 +0000 (01:50 +0100)
committerIan Jackson <ijackson@chiark.greenend.org.uk>
Sat, 14 May 2022 01:15:39 +0000 (02:15 +0100)
Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
src/utils.rs

index 33da9663d7a81c4122e585c34160bf7db2c31d6a..d2b640bb324c28a03120e8200c95a510a94ac486 100644 (file)
@@ -332,7 +332,30 @@ impl<Y: Sync, E: Sync, F: Sync + FnOnce() -> Result<Y,E>>
 
 // todo: DerefMut
 
-//========== toml_merge ====================
+//========== toml ====================
+
+// We reimplement this because the toml crate doesn't expose it, and
+// looking at the github issues etc. for that crate isn't encuraging.
+pub fn toml_quote_string(s: &str) -> String {
+  let mut o = String::new();
+  for c in s.chars() {
+    match c {
+      '"' | '\\'=> { o.push('\\'); o.push(c); },
+      c if (c < ' ' && c != '\t') || c == '\x7f' => {
+        write!(o, r#"\u{:04x}"#, c as u32).unwrap();
+        continue;
+      }
+      c => o.push(c),
+    }
+  }
+  o
+}
+
+#[test]
+fn toml_quote_string_test(){
+  assert_eq!(toml_quote_string(r#"w \ "        \a\7fƒ."#),
+                                r#"w \\ \"     \u0007\u007fƒ."#);
+}
 
 pub fn toml_merge<'u,
                   S: 'u + AsRef<str>,