about summary refs log tree commit diff
path: root/src/libstd
diff options
context:
space:
mode:
authorbors <bors@rust-lang.org>2014-11-05 03:31:33 +0000
committerbors <bors@rust-lang.org>2014-11-05 03:31:33 +0000
commit4375b32dabf8096a1137a68c1070fc9a9292cb06 (patch)
tree99a0794fa4839b48edcf0a3212392bb775f4982c /src/libstd
parentceeac26de859bd217d8ff576ff291dbd38ff3951 (diff)
parente8d6031c71a5ab42648f26a253671ba17584407a (diff)
auto merge of #18504 : pcwalton/rust/small-escapes, r=pcwalton
Use `\u0080`-`\u00ff` instead. ASCII/byte literals are unaffected.

This PR introduces a new function, `escape_default`, into the ASCII
module. This was necessary for the pretty printer to continue to
function.

RFC #326.

Closes #18062.

[breaking-change]

r? @aturon
Diffstat (limited to 'src/libstd')
-rw-r--r--src/libstd/ascii.rs32
1 files changed, 32 insertions, 0 deletions
diff --git a/src/libstd/ascii.rs b/src/libstd/ascii.rs
index 6b64959a843..2953b60e674 100644
--- a/src/libstd/ascii.rs
+++ b/src/libstd/ascii.rs
@@ -461,6 +461,38 @@ impl OwnedAsciiExt for Vec<u8> {
     }
 }
 
+/// Returns a 'default' ASCII and C++11-like literal escape of a `u8`
+///
+/// The default is chosen with a bias toward producing literals that are
+/// legal in a variety of languages, including C++11 and similar C-family
+/// languages. The exact rules are:
+///
+/// - Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively.
+/// - Single-quote, double-quote and backslash chars are backslash-escaped.
+/// - Any other chars in the range [0x20,0x7e] are not escaped.
+/// - Any other chars are given hex escapes.
+/// - Unicode escapes are never generated by this function.
+pub fn escape_default(c: u8, f: |u8|) {
+    match c {
+        b'\t' => { f(b'\\'); f(b't'); }
+        b'\r' => { f(b'\\'); f(b'r'); }
+        b'\n' => { f(b'\\'); f(b'n'); }
+        b'\\' => { f(b'\\'); f(b'\\'); }
+        b'\'' => { f(b'\\'); f(b'\''); }
+        b'"'  => { f(b'\\'); f(b'"'); }
+        b'\x20' ... b'\x7e' => { f(c); }
+        _ => {
+            f(b'\\');
+            f(b'x');
+            for &offset in [4u, 0u].iter() {
+                match ((c as i32) >> offset) & 0xf {
+                    i @ 0 ... 9 => f(b'0' + (i as u8)),
+                    i => f(b'a' + (i as u8 - 10)),
+                }
+            }
+        }
+    }
+}
 
 pub static ASCII_LOWER_MAP: [u8, ..256] = [
     0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,