ct_regex_internal/haystack/
item.rs

1use std::fmt::Debug;
2
3mod haystack_item {
4    pub trait Sealed {}
5}
6
7use haystack_item::Sealed;
8
9/// A trait that represents an individual item that can be matched against a
10/// [`Regex`](crate::expr::Regex). The primary (and only) two implementors are [`char`] and [`u8`].
11///
12/// # Sealed
13///
14/// This trait is sealed, preventing implementations because the `regex!` macro can't produce
15/// `Regex` types that match against any `HaystackItem` other than the default. If you need to match
16/// against another item type and want to use this crate, you may as well fork it so that you don't
17/// have to write manual `Matcher` expressions.
18pub trait HaystackItem: Debug + Default + Copy + Eq + Ord + Sealed {
19    /// Creates a `Vec` of this item from the provided `&str`, used to convert string literals from
20    /// parsed regular expressions into individual `HaystackItem`s that can be matched in a
21    /// haystack.
22    fn vec_from_str(value: &str) -> Vec<Self>;
23}
24
25/// A trait representing a slice of the underlying haystack for various
26/// [`Haystack`](crate::haystack::Haystack) types.
27///
28/// The implementor of this trait is usually but not always, the only implementor of
29/// [`IntoHaystack`](crate::haystack::IntoHaystack) for a haystack type.
30///
31/// It should be noted that this trait is often implemented of a reference to the type in question,
32/// e.g. `&str` or `&[u8]` rather than `str` or `[u8]` themselves, so that the implementing type can
33/// be cloned as required.
34pub trait HaystackSlice<'a>: Debug + Clone + Sized {
35    /// The `HaystackItem` contained within this slice.
36    type Item: HaystackItem;
37}
38
39impl Sealed for char {}
40
41impl HaystackItem for char {
42    fn vec_from_str(value: &str) -> Vec<Self> {
43        value.chars().collect()
44    }
45}
46
47impl<'a> HaystackSlice<'a> for &'a str {
48    type Item = char;
49}
50
51impl Sealed for u8 {}
52
53impl HaystackItem for u8 {
54    fn vec_from_str(s: &str) -> Vec<Self> {
55        s.as_bytes().to_vec()
56    }
57}
58
59impl<'a> HaystackSlice<'a> for &'a [u8] {
60    type Item = u8;
61}