Skip to content

Commit 92c8a94

Browse files
committed
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.
1 parent 1b28ffa commit 92c8a94

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

src/libstd/ffi/c_str.rs

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,14 @@
88
// option. This file may not be copied, modified, or distributed
99
// except according to those terms.
1010

11+
use ascii;
1112
use borrow::{Cow, ToOwned, Borrow};
1213
use boxed::Box;
1314
use clone::Clone;
1415
use convert::{Into, From};
1516
use cmp::{PartialEq, Eq, PartialOrd, Ord, Ordering};
1617
use error::Error;
17-
use fmt;
18+
use fmt::{self, Write};
1819
use io;
1920
use iter::Iterator;
2021
use libc;
@@ -268,7 +269,18 @@ impl Deref for CString {
268269
#[stable(feature = "rust1", since = "1.0.0")]
269270
impl fmt::Debug for CString {
270271
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
271-
fmt::Debug::fmt(&String::from_utf8_lossy(self.as_bytes()), f)
272+
fmt::Debug::fmt(&**self, f)
273+
}
274+
}
275+
276+
#[stable(feature = "cstr_debug", since = "1.3.0")]
277+
impl fmt::Debug for CStr {
278+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
279+
try!(write!(f, "\""));
280+
for byte in self.to_bytes().iter().flat_map(|&b| ascii::escape_default(b)) {
281+
try!(f.write_char(byte as char));
282+
}
283+
write!(f, "\"")
272284
}
273285
}
274286

@@ -501,8 +513,8 @@ mod tests {
501513

502514
#[test]
503515
fn formatted() {
504-
let s = CString::new(&b"12"[..]).unwrap();
505-
assert_eq!(format!("{:?}", s), "\"12\"");
516+
let s = CString::new(&b"abc\x01\x02\n\xE2\x80\xA6\xFF"[..]).unwrap();
517+
assert_eq!(format!("{:?}", s), r#""abc\x01\x02\n\xe2\x80\xa6\xff""#);
506518
}
507519

508520
#[test]

0 commit comments

Comments
 (0)