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: escape invalid UTF-8 bytes in debug output for Match #1203

Merged
merged 3 commits into from
Jun 9, 2024
Merged
Changes from 1 commit
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
Prev Previous commit
Next Next commit
use DebugHaystack
  • Loading branch information
notJoon committed Jun 9, 2024
commit 88112b31c21fcd5cd6d57fdb6a056f0a96880166
38 changes: 19 additions & 19 deletions src/regex/bytes.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use alloc::{borrow::Cow, format, string::String, sync::Arc, vec::Vec};
use alloc::{borrow::Cow, string::String, sync::Arc, vec::Vec};

use regex_automata::{meta, util::captures, Input, PatternID};

Expand Down Expand Up @@ -1555,29 +1555,17 @@ impl<'h> Match<'h> {

impl<'h> core::fmt::Debug for Match<'h> {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
let mut fmt = f.debug_struct("Match");
fmt.field("start", &self.start).field("end", &self.end);
use regex_automata::util::escape::DebugHaystack;

let bytes = self.as_bytes();
let formatted = bytes_to_string_with_invalid_utf8_escaped(bytes);
fmt.field("bytes", &formatted);
let mut fmt = f.debug_struct("Match");
fmt.field("start", &self.start)
.field("end", &self.end)
.field("bytes", &DebugHaystack(&self.as_bytes()));

fmt.finish()
}
}

fn bytes_to_string_with_invalid_utf8_escaped(bytes: &[u8]) -> String {
let mut result = String::new();
for &byte in bytes {
if byte.is_ascii() {
result.push(byte as char);
} else {
result.push_str(&format!("\\x{:02X}", byte));
}
}
result
}

impl<'h> From<Match<'h>> for &'h [u8] {
fn from(m: Match<'h>) -> &'h [u8] {
m.as_bytes()
Expand Down Expand Up @@ -2674,7 +2662,19 @@ mod tests {

assert_eq!(
debug_str,
r#"Match { start: 7, end: 13, bytes: "\\xFFworld" }"#
r#"Match { start: 7, end: 13, bytes: "\xffworld" }"#
);
}

#[test]
fn test_non_ascii_utf8() {
let haystack = "아스키문자는 아닌데 UTF-8 문자열".as_bytes();
let m = Match::new(haystack, 0, haystack.len());
let debug_str = format!("{:?}", m);

assert_eq!(
debug_str,
r#"Match { start: 0, end: 44, bytes: "아스키문자는 아닌데 UTF-8 문자열" }"#
);
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add some tests with non-ASCII UTF-8.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added along with other tests.
d18841e

}