Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix panic displaying binary data with invalid UTF-8 sequencies #230

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
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"
);
}
}