Skip to content

Commit dbc292f

Browse files
Fix panic displaying binary data with invalid utf8 sequencies
Signed-off-by: Gabriel Araújo <[email protected]>
1 parent 2f57c3c commit dbc292f

File tree

1 file changed

+30
-1
lines changed

1 file changed

+30
-1
lines changed

src/event/data.rs

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,9 +82,38 @@ impl TryFrom<Data> for String {
8282
impl fmt::Display for Data {
8383
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
8484
match self {
85-
Data::Binary(vec) => write!(f, "Binary data: {:?}", str::from_utf8(vec).unwrap()),
85+
Data::Binary(vec) => {
86+
write!(f, "Binary data: ")?;
87+
let mut slice = &vec[..];
88+
loop {
89+
match str::from_utf8(slice) {
90+
Ok(s) => break f.write_str(s),
91+
Err(e) => {
92+
let (good, bad) = slice.split_at(e.valid_up_to());
93+
94+
f.write_str(str::from_utf8(good).unwrap())?;
95+
write!(f, "\\x{:02X}", bad[0])?;
96+
slice = &bad[1..];
97+
}
98+
}
99+
}
100+
}
86101
Data::String(s) => write!(f, "String data: {}", s),
87102
Data::Json(j) => write!(f, "Json data: {}", j),
88103
}
89104
}
90105
}
106+
107+
#[cfg(test)]
108+
mod tests {
109+
use crate::Data;
110+
111+
#[test]
112+
fn display_arbitrary_bytes() {
113+
let d = Data::Binary(b"E onde sou s\xC3\xB3 desejo, queres n\xC3\xA3o\xF0\x90".into());
114+
assert_eq!(
115+
format!("{}", d),
116+
r"Binary data: E onde sou só desejo, queres não\xF0\x90"
117+
);
118+
}
119+
}

0 commit comments

Comments
 (0)