Skip to content

Commit

Permalink
Fix panic displaying binary data with invalid utf8 sequencies
Browse files Browse the repository at this point in the history
Signed-off-by: Gabriel Araújo <[email protected]>
  • Loading branch information
gabriel-araujjo committed Jun 2, 2024
1 parent 2f57c3c commit 668b97d
Showing 1 changed file with 32 additions and 1 deletion.
33 changes: 32 additions & 1 deletion src/event/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,40 @@ impl TryFrom<Data> for String {
impl fmt::Display for Data {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Data::Binary(vec) => write!(f, "Binary data: {:?}", str::from_utf8(vec).unwrap()),
Data::Binary(vec) => {
write!(f, "Binary data: ")?;
let mut slice = &vec[..];
loop {
match str::from_utf8(slice) {
Ok(s) => break f.write_str(s),
Err(e) => {
let (good, bad) = slice.split_at(e.valid_up_to());

// SAFETY: good is a valid utf8 sequency because
f.write_str(unsafe { str::from_utf8_unchecked(good) })?;

write!(f, "\\x{:02X}", bad[0])?;
slice = &bad[1..];
}
}
}
}
Data::String(s) => write!(f, "String data: {}", s),
Data::Json(j) => write!(f, "Json data: {}", j),
}
}
}

#[cfg(test)]
mod tests {
use crate::Data;

#[test]
fn display_arbitrary_bytes() {
let d = Data::Binary(b"E onde sou s\xC3\xB3 desejo, queres n\xC3\xA3o\xF0\x90".into());
assert_eq!(
format!("{}", d),
r"Binary data: E onde sou só desejo, queres não\xF0\x90"
);
}
}

0 comments on commit 668b97d

Please sign in to comment.