Skip to content

Commit 8a68456

Browse files
author
mbartlett21
committed
Implement Display and Debug for CStr
Signed-off-by: Morgan Bartlett <mjmouse9999@gmail.com>
1 parent 4946eec commit 8a68456

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

rust/kernel/str.rs

+30
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
//! String representations.
44
5+
use core::fmt::{self, Write};
56
use core::ops::{self, Deref, Index};
67

78
use crate::bindings;
@@ -209,6 +210,35 @@ impl CStr {
209210
}
210211
}
211212

213+
impl fmt::Display for CStr {
214+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
215+
for &c in self.as_bytes() {
216+
if (0x20..0x7f).contains(&c) {
217+
// Printable character
218+
f.write_char(c as char)?;
219+
} else {
220+
write!(f, "\\x{:02x}", c)?;
221+
}
222+
}
223+
Ok(())
224+
}
225+
}
226+
227+
impl fmt::Debug for CStr {
228+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229+
f.write_str("\"")?;
230+
for &c in self.as_bytes() {
231+
if (0x20..0x7f).contains(&c) {
232+
// Printable character
233+
f.write_char(c as char)?;
234+
} else {
235+
write!(f, "\\x{:02x}", c)?;
236+
}
237+
}
238+
f.write_str("\"")
239+
}
240+
}
241+
212242
impl AsRef<BStr> for CStr {
213243
#[inline]
214244
fn as_ref(&self) -> &BStr {

0 commit comments

Comments
 (0)