Skip to content

Commit 37d36b9

Browse files
committed
api: improve Debug impl for Match
This makes it so the Debug impl for Match only shows the actual matched text. Otherwise, the Match shows the entire haystack, which is likely to be misleading. Fixes #514
1 parent 47582ce commit 37d36b9

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

src/re_bytes.rs

+19-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ use crate::re_trait::{self, RegularExpression, SubCapturesPosIter};
1717
/// Match represents a single match of a regex in a haystack.
1818
///
1919
/// The lifetime parameter `'t` refers to the lifetime of the matched text.
20-
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
20+
#[derive(Copy, Clone, Eq, PartialEq)]
2121
pub struct Match<'t> {
2222
text: &'t [u8],
2323
start: usize,
@@ -69,6 +69,24 @@ impl<'t> Match<'t> {
6969
}
7070
}
7171

72+
impl<'t> std::fmt::Debug for Match<'t> {
73+
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
74+
let mut fmt = f.debug_struct("Match");
75+
fmt.field("start", &self.start).field("end", &self.end);
76+
if let Ok(s) = std::str::from_utf8(self.as_bytes()) {
77+
fmt.field("bytes", &s);
78+
} else {
79+
// FIXME: It would be nice if this could be printed as a string
80+
// with invalid UTF-8 replaced with hex escapes. A alloc would
81+
// probably okay if that makes it easier, but regex-automata does
82+
// (at time of writing) have internal routines that do this. So
83+
// maybe we should expose them.
84+
fmt.field("bytes", &self.as_bytes());
85+
}
86+
fmt.finish()
87+
}
88+
}
89+
7290
impl<'t> From<Match<'t>> for Range<usize> {
7391
fn from(m: Match<'t>) -> Range<usize> {
7492
m.range()

src/re_unicode.rs

+11-1
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ pub fn escape(text: &str) -> String {
2525
/// Match represents a single match of a regex in a haystack.
2626
///
2727
/// The lifetime parameter `'t` refers to the lifetime of the matched text.
28-
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
28+
#[derive(Copy, Clone, Eq, PartialEq)]
2929
pub struct Match<'t> {
3030
text: &'t str,
3131
start: usize,
@@ -77,6 +77,16 @@ impl<'t> Match<'t> {
7777
}
7878
}
7979

80+
impl<'t> std::fmt::Debug for Match<'t> {
81+
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
82+
f.debug_struct("Match")
83+
.field("start", &self.start)
84+
.field("end", &self.end)
85+
.field("string", &self.as_str())
86+
.finish()
87+
}
88+
}
89+
8090
impl<'t> From<Match<'t>> for &'t str {
8191
fn from(m: Match<'t>) -> &'t str {
8292
m.as_str()

0 commit comments

Comments
 (0)