Skip to main content

fancy_regex/bytes/
mod.rs

1//! Byte-level matching types for `fancy_regex`.
2//!
3//! This module provides types for working with regex matches on raw byte
4//! sequences (`&[u8]`) that may not be valid UTF-8.
5
6use core::ops::Range;
7
8/// A single match of a regex in a byte slice.
9///
10/// Similar to [`crate::Match`] but operates on `&[u8]` instead of `&str`.
11#[derive(Copy, Clone, Debug, Eq, PartialEq)]
12pub struct MatchBytes<'t> {
13    pub(crate) bytes: &'t [u8],
14    pub(crate) match_start: usize,
15    pub(crate) match_end: usize,
16}
17
18impl<'t> MatchBytes<'t> {
19    /// Returns the starting byte offset of the match.
20    #[inline]
21    pub fn start(&self) -> usize {
22        self.match_start
23    }
24
25    /// Returns the ending byte offset of the match.
26    #[inline]
27    pub fn end(&self) -> usize {
28        self.match_end
29    }
30
31    /// Returns the range over the starting and ending byte offsets.
32    #[inline]
33    pub fn range(&self) -> Range<usize> {
34        self.match_start..self.match_end
35    }
36
37    /// Returns the matched bytes.
38    #[inline]
39    pub fn as_bytes(&self) -> &'t [u8] {
40        &self.bytes[self.match_start..self.match_end]
41    }
42
43    /// Creates a new match from the given bytes and byte offsets.
44    pub(crate) fn new(bytes: &'t [u8], start: usize, end: usize) -> MatchBytes<'t> {
45        MatchBytes {
46            bytes,
47            match_start: start,
48            match_end: end,
49        }
50    }
51}
52
53impl<'t> From<MatchBytes<'t>> for &'t [u8] {
54    fn from(m: MatchBytes<'t>) -> &'t [u8] {
55        m.as_bytes()
56    }
57}
58
59impl<'t> From<MatchBytes<'t>> for Range<usize> {
60    fn from(m: MatchBytes<'t>) -> Range<usize> {
61        m.range()
62    }
63}