about summary refs log tree commit diff
diff options
context:
space:
mode:
authorDylan DPC <99973273+Dylan-DPC@users.noreply.github.com>2022-09-12 15:21:30 +0530
committerGitHub <noreply@github.com>2022-09-12 15:21:30 +0530
commit93177758fccdaac08d606348f79b20e9cd9df022 (patch)
tree2d40e1231d79e875258f1414f30b045d083f48c3
parent413703201c59f25a5a2fded13d7ee4b4be4e8545 (diff)
parenta297631bdcc7742b55cf5961fcbc505e91217c7d (diff)
downloadrust-93177758fccdaac08d606348f79b20e9cd9df022.tar.gz
rust-93177758fccdaac08d606348f79b20e9cd9df022.zip
Rollup merge of #100767 - kadiwa4:escape_ascii, r=jackh726
Remove manual <[u8]>::escape_ascii

`@rustbot` label: +C-cleanup
-rw-r--r--compiler/rustc_ast/src/util/literal.rs7
-rw-r--r--compiler/rustc_codegen_ssa/src/back/link.rs25
-rw-r--r--compiler/rustc_middle/src/mir/mod.rs10
-rw-r--r--compiler/rustc_middle/src/ty/print/pretty.rs9
-rw-r--r--library/core/src/ffi/c_str.rs9
-rw-r--r--library/proc_macro/src/lib.rs7
-rw-r--r--library/std/src/os/unix/net/addr.rs16
7 files changed, 16 insertions, 67 deletions
diff --git a/compiler/rustc_ast/src/util/literal.rs b/compiler/rustc_ast/src/util/literal.rs
index 6a1578498e6..536b385606c 100644
--- a/compiler/rustc_ast/src/util/literal.rs
+++ b/compiler/rustc_ast/src/util/literal.rs
@@ -163,12 +163,7 @@ impl LitKind {
             }
             LitKind::Str(symbol, ast::StrStyle::Raw(n)) => (token::StrRaw(n), symbol, None),
             LitKind::ByteStr(ref bytes) => {
-                let string = bytes
-                    .iter()
-                    .cloned()
-                    .flat_map(ascii::escape_default)
-                    .map(Into::<char>::into)
-                    .collect::<String>();
+                let string = bytes.escape_ascii().to_string();
                 (token::ByteStr, Symbol::intern(&string), None)
             }
             LitKind::Byte(byte) => {
diff --git a/compiler/rustc_codegen_ssa/src/back/link.rs b/compiler/rustc_codegen_ssa/src/back/link.rs
index a3fed88cc4b..d7c7037ce1a 100644
--- a/compiler/rustc_codegen_ssa/src/back/link.rs
+++ b/compiler/rustc_codegen_ssa/src/back/link.rs
@@ -44,7 +44,7 @@ use std::io::{BufWriter, Write};
 use std::ops::Deref;
 use std::path::{Path, PathBuf};
 use std::process::{ExitStatus, Output, Stdio};
-use std::{ascii, char, env, fmt, fs, io, mem, str};
+use std::{env, fmt, fs, io, mem, str};
 
 pub fn ensure_removed(diag_handler: &Handler, path: &Path) {
     if let Err(e) = fs::remove_file(path) {
@@ -552,14 +552,6 @@ fn link_staticlib<'a>(
     Ok(())
 }
 
-fn escape_stdout_stderr_string(s: &[u8]) -> String {
-    str::from_utf8(s).map(|s| s.to_owned()).unwrap_or_else(|_| {
-        let mut x = "Non-UTF-8 output: ".to_string();
-        x.extend(s.iter().flat_map(|&b| ascii::escape_default(b)).map(char::from));
-        x
-    })
-}
-
 /// Use `thorin` (rust implementation of a dwarf packaging utility) to link DWARF objects into a
 /// DWARF package.
 fn link_dwarf_object<'a>(
@@ -866,7 +858,7 @@ fn link_natively<'a>(
             if !prog.status.success() {
                 let mut output = prog.stderr.clone();
                 output.extend_from_slice(&prog.stdout);
-                let escaped_output = escape_stdout_stderr_string(&output);
+                let escaped_output = escape_string(&output);
                 let mut err = sess.struct_err(&format!(
                     "linking with `{}` failed: {}",
                     linker_path.display(),
@@ -934,8 +926,8 @@ fn link_natively<'a>(
 
                 sess.abort_if_errors();
             }
-            info!("linker stderr:\n{}", escape_stdout_stderr_string(&prog.stderr));
-            info!("linker stdout:\n{}", escape_stdout_stderr_string(&prog.stdout));
+            info!("linker stderr:\n{}", escape_string(&prog.stderr));
+            info!("linker stdout:\n{}", escape_string(&prog.stdout));
         }
         Err(e) => {
             let linker_not_found = e.kind() == io::ErrorKind::NotFound;
@@ -1065,11 +1057,10 @@ fn strip_symbols_in_osx<'a>(sess: &'a Session, out_filename: &Path, option: Opti
 }
 
 fn escape_string(s: &[u8]) -> String {
-    str::from_utf8(s).map(|s| s.to_owned()).unwrap_or_else(|_| {
-        let mut x = "Non-UTF-8 output: ".to_string();
-        x.extend(s.iter().flat_map(|&b| ascii::escape_default(b)).map(char::from));
-        x
-    })
+    match str::from_utf8(s) {
+        Ok(s) => s.to_owned(),
+        Err(_) => format!("Non-UTF-8 output: {}", s.escape_ascii()),
+    }
 }
 
 fn add_sanitizer_libraries(sess: &Session, crate_type: CrateType, linker: &mut dyn Linker) {
diff --git a/compiler/rustc_middle/src/mir/mod.rs b/compiler/rustc_middle/src/mir/mod.rs
index 753e1f4b9da..dd768c5358d 100644
--- a/compiler/rustc_middle/src/mir/mod.rs
+++ b/compiler/rustc_middle/src/mir/mod.rs
@@ -2633,15 +2633,7 @@ fn pretty_print_const<'tcx>(
 }
 
 fn pretty_print_byte_str(fmt: &mut Formatter<'_>, byte_str: &[u8]) -> fmt::Result {
-    fmt.write_str("b\"")?;
-    for &c in byte_str {
-        for e in std::ascii::escape_default(c) {
-            fmt.write_char(e as char)?;
-        }
-    }
-    fmt.write_str("\"")?;
-
-    Ok(())
+    write!(fmt, "b\"{}\"", byte_str.escape_ascii())
 }
 
 fn comma_sep<'tcx>(fmt: &mut Formatter<'_>, elems: Vec<ConstantKind<'tcx>>) -> fmt::Result {
diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs
index 301d1f5052e..e9eecfe78d3 100644
--- a/compiler/rustc_middle/src/ty/print/pretty.rs
+++ b/compiler/rustc_middle/src/ty/print/pretty.rs
@@ -1405,14 +1405,7 @@ pub trait PrettyPrinter<'tcx>:
     }
 
     fn pretty_print_byte_str(mut self, byte_str: &'tcx [u8]) -> Result<Self::Const, Self::Error> {
-        define_scoped_cx!(self);
-        p!("b\"");
-        for &c in byte_str {
-            for e in std::ascii::escape_default(c) {
-                self.write_char(e as char)?;
-            }
-        }
-        p!("\"");
+        write!(self, "b\"{}\"", byte_str.escape_ascii())?;
         Ok(self)
     }
 
diff --git a/library/core/src/ffi/c_str.rs b/library/core/src/ffi/c_str.rs
index d8b8ac4d871..970830045b8 100644
--- a/library/core/src/ffi/c_str.rs
+++ b/library/core/src/ffi/c_str.rs
@@ -1,7 +1,6 @@
-use crate::ascii;
 use crate::cmp::Ordering;
 use crate::ffi::c_char;
-use crate::fmt::{self, Write};
+use crate::fmt;
 use crate::intrinsics;
 use crate::ops;
 use crate::slice;
@@ -161,11 +160,7 @@ impl fmt::Display for FromBytesUntilNulError {
 #[stable(feature = "cstr_debug", since = "1.3.0")]
 impl fmt::Debug for CStr {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        write!(f, "\"")?;
-        for byte in self.to_bytes().iter().flat_map(|&b| ascii::escape_default(b)) {
-            f.write_char(byte as char)?;
-        }
-        write!(f, "\"")
+        write!(f, "\"{}\"", self.to_bytes().escape_ascii())
     }
 }
 
diff --git a/library/proc_macro/src/lib.rs b/library/proc_macro/src/lib.rs
index 8e478cd7bc8..495c1c5ae46 100644
--- a/library/proc_macro/src/lib.rs
+++ b/library/proc_macro/src/lib.rs
@@ -1353,12 +1353,7 @@ impl Literal {
     /// Byte string literal.
     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
     pub fn byte_string(bytes: &[u8]) -> Literal {
-        let string = bytes
-            .iter()
-            .cloned()
-            .flat_map(std::ascii::escape_default)
-            .map(Into::<char>::into)
-            .collect::<String>();
+        let string = bytes.escape_ascii().to_string();
         Literal::new(bridge::LitKind::ByteStr, &string, None)
     }
 
diff --git a/library/std/src/os/unix/net/addr.rs b/library/std/src/os/unix/net/addr.rs
index bb313c7597b..094085e1942 100644
--- a/library/std/src/os/unix/net/addr.rs
+++ b/library/std/src/os/unix/net/addr.rs
@@ -2,7 +2,7 @@ use crate::ffi::OsStr;
 use crate::os::unix::ffi::OsStrExt;
 use crate::path::Path;
 use crate::sys::cvt;
-use crate::{ascii, fmt, io, mem, ptr};
+use crate::{fmt, io, mem, ptr};
 
 // FIXME(#43348): Make libc adapt #[doc(cfg(...))] so we don't need these fake definitions here?
 #[cfg(not(unix))]
@@ -64,18 +64,6 @@ enum AddressKind<'a> {
     Abstract(&'a [u8]),
 }
 
-struct AsciiEscaped<'a>(&'a [u8]);
-
-impl<'a> fmt::Display for AsciiEscaped<'a> {
-    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
-        write!(fmt, "\"")?;
-        for byte in self.0.iter().cloned().flat_map(ascii::escape_default) {
-            write!(fmt, "{}", byte as char)?;
-        }
-        write!(fmt, "\"")
-    }
-}
-
 /// An address associated with a Unix socket.
 ///
 /// # Examples
@@ -343,7 +331,7 @@ impl fmt::Debug for SocketAddr {
     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
         match self.address() {
             AddressKind::Unnamed => write!(fmt, "(unnamed)"),
-            AddressKind::Abstract(name) => write!(fmt, "{} (abstract)", AsciiEscaped(name)),
+            AddressKind::Abstract(name) => write!(fmt, "\"{}\" (abstract)", name.escape_ascii()),
             AddressKind::Pathname(path) => write!(fmt, "{path:?} (pathname)"),
         }
     }