about summary refs log tree commit diff
path: root/src/libstd
diff options
context:
space:
mode:
authorbors <bors@rust-lang.org>2015-07-12 11:45:23 +0000
committerbors <bors@rust-lang.org>2015-07-12 11:45:23 +0000
commit2999003be809fc09119243fa348ae771f51cbf1e (patch)
tree8b00ec691bf160550182b4e03e681025689916d7 /src/libstd
parentaff208033b5cf0ce8d4e7710ba868d2221c30839 (diff)
parent92c8a9439b82f56aabb2f42e485e8683e663aaff (diff)
downloadrust-2999003be809fc09119243fa348ae771f51cbf1e.tar.gz
rust-2999003be809fc09119243fa348ae771f51cbf1e.zip
Auto merge of #26965 - bluss:cstring-debug, r=alexcrichton
Use escaped byte string representation for CString Debug

Faithfully represent the contents of the CString and CStr in their Debug
impl, by treating them as byte strings with our default escaping to
ascii representation.

Add impl Debug for CStr.

Fixes #26964.
Diffstat (limited to 'src/libstd')
-rw-r--r--src/libstd/ffi/c_str.rs20
1 files changed, 16 insertions, 4 deletions
diff --git a/src/libstd/ffi/c_str.rs b/src/libstd/ffi/c_str.rs
index f13c10156f5..c9fe6e7e0b1 100644
--- a/src/libstd/ffi/c_str.rs
+++ b/src/libstd/ffi/c_str.rs
@@ -8,13 +8,14 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
+use ascii;
 use borrow::{Cow, ToOwned, Borrow};
 use boxed::Box;
 use clone::Clone;
 use convert::{Into, From};
 use cmp::{PartialEq, Eq, PartialOrd, Ord, Ordering};
 use error::Error;
-use fmt;
+use fmt::{self, Write};
 use io;
 use iter::Iterator;
 use libc;
@@ -268,7 +269,18 @@ impl Deref for CString {
 #[stable(feature = "rust1", since = "1.0.0")]
 impl fmt::Debug for CString {
     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
-        fmt::Debug::fmt(&String::from_utf8_lossy(self.as_bytes()), f)
+        fmt::Debug::fmt(&**self, f)
+    }
+}
+
+#[stable(feature = "cstr_debug", since = "1.3.0")]
+impl fmt::Debug for CStr {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        try!(write!(f, "\""));
+        for byte in self.to_bytes().iter().flat_map(|&b| ascii::escape_default(b)) {
+            try!(f.write_char(byte as char));
+        }
+        write!(f, "\"")
     }
 }
 
@@ -501,8 +513,8 @@ mod tests {
 
     #[test]
     fn formatted() {
-        let s = CString::new(&b"12"[..]).unwrap();
-        assert_eq!(format!("{:?}", s), "\"12\"");
+        let s = CString::new(&b"abc\x01\x02\n\xE2\x80\xA6\xFF"[..]).unwrap();
+        assert_eq!(format!("{:?}", s), r#""abc\x01\x02\n\xe2\x80\xa6\xff""#);
     }
 
     #[test]