Skip to content

Commit

Permalink
api: improve Debug impl for Match
Browse files Browse the repository at this point in the history
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
  • Loading branch information
BurntSushi committed Mar 15, 2023
1 parent 414ad74 commit e4bac0e
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
20 changes: 19 additions & 1 deletion src/re_bytes.rs
Expand Up @@ -17,7 +17,7 @@ use crate::re_trait::{self, RegularExpression, SubCapturesPosIter};
/// Match represents a single match of a regex in a haystack.
///
/// The lifetime parameter `'t` refers to the lifetime of the matched text.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[derive(Copy, Clone, Eq, PartialEq)]
pub struct Match<'t> {
text: &'t [u8],
start: usize,
Expand Down Expand Up @@ -69,6 +69,24 @@ impl<'t> Match<'t> {
}
}

impl<'t> std::fmt::Debug for Match<'t> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let mut fmt = f.debug_struct("Match");
fmt.field("start", &self.start).field("end", &self.end);
if let Ok(s) = std::str::from_utf8(self.as_bytes()) {
fmt.field("bytes", &s);
} else {
// FIXME: It would be nice if this could be printed as a string
// with invalid UTF-8 replaced with hex escapes. A alloc would
// probably okay if that makes it easier, but regex-automata does
// (at time of writing) have internal routines that do this. So
// maybe we should expose them.
fmt.field("bytes", &self.as_bytes());
}
fmt.finish()
}
}

impl<'t> From<Match<'t>> for Range<usize> {
fn from(m: Match<'t>) -> Range<usize> {
m.range()
Expand Down
12 changes: 11 additions & 1 deletion src/re_unicode.rs
Expand Up @@ -25,7 +25,7 @@ pub fn escape(text: &str) -> String {
/// Match represents a single match of a regex in a haystack.
///
/// The lifetime parameter `'t` refers to the lifetime of the matched text.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[derive(Copy, Clone, Eq, PartialEq)]
pub struct Match<'t> {
text: &'t str,
start: usize,
Expand Down Expand Up @@ -77,6 +77,16 @@ impl<'t> Match<'t> {
}
}

impl<'t> std::fmt::Debug for Match<'t> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.debug_struct("Match")
.field("start", &self.start)
.field("end", &self.end)
.field("string", &self.as_str())
.finish()
}
}

impl<'t> From<Match<'t>> for &'t str {
fn from(m: Match<'t>) -> &'t str {
m.as_str()
Expand Down

0 comments on commit e4bac0e

Please sign in to comment.