Skip to main content

aho_corasick/util/
error.rs

1use crate::util::{
2    primitives::{PatternID, SmallIndex},
3    search::MatchKind,
4};
5
6/// An error that occurred during the construction of an Aho-Corasick
7/// automaton.
8///
9/// Build errors occur when some kind of limit has been exceeded, either in the
10/// number of states, the number of patterns of the length of a pattern. These
11/// limits aren't part of the public API, but they should generally be large
12/// enough to handle most use cases.
13///
14/// When the `std` feature is enabled, this implements the `std::error::Error`
15/// trait.
16#[derive(#[automatically_derived]
impl ::core::clone::Clone for BuildError {
    #[inline]
    fn clone(&self) -> BuildError {
        BuildError { kind: ::core::clone::Clone::clone(&self.kind) }
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for BuildError {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f, "BuildError",
            "kind", &&self.kind)
    }
}Debug)]
17pub struct BuildError {
18    kind: ErrorKind,
19}
20
21/// The kind of error that occurred.
22#[derive(#[automatically_derived]
impl ::core::clone::Clone for ErrorKind {
    #[inline]
    fn clone(&self) -> ErrorKind {
        match self {
            ErrorKind::StateIDOverflow {
                max: __self_0, requested_max: __self_1 } =>
                ErrorKind::StateIDOverflow {
                    max: ::core::clone::Clone::clone(__self_0),
                    requested_max: ::core::clone::Clone::clone(__self_1),
                },
            ErrorKind::PatternIDOverflow {
                max: __self_0, requested_max: __self_1 } =>
                ErrorKind::PatternIDOverflow {
                    max: ::core::clone::Clone::clone(__self_0),
                    requested_max: ::core::clone::Clone::clone(__self_1),
                },
            ErrorKind::PatternTooLong { pattern: __self_0, len: __self_1 } =>
                ErrorKind::PatternTooLong {
                    pattern: ::core::clone::Clone::clone(__self_0),
                    len: ::core::clone::Clone::clone(__self_1),
                },
        }
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ErrorKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            ErrorKind::StateIDOverflow {
                max: __self_0, requested_max: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "StateIDOverflow", "max", __self_0, "requested_max",
                    &__self_1),
            ErrorKind::PatternIDOverflow {
                max: __self_0, requested_max: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "PatternIDOverflow", "max", __self_0, "requested_max",
                    &__self_1),
            ErrorKind::PatternTooLong { pattern: __self_0, len: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "PatternTooLong", "pattern", __self_0, "len", &__self_1),
        }
    }
}Debug)]
23enum ErrorKind {
24    /// An error that occurs when allocating a new state would result in an
25    /// identifier that exceeds the capacity of a `StateID`.
26    StateIDOverflow {
27        /// The maximum possible id.
28        max: u64,
29        /// The maximum ID requested.
30        requested_max: u64,
31    },
32    /// An error that occurs when adding a pattern to an Aho-Corasick
33    /// automaton would result in an identifier that exceeds the capacity of a
34    /// `PatternID`.
35    PatternIDOverflow {
36        /// The maximum possible id.
37        max: u64,
38        /// The maximum ID requested.
39        requested_max: u64,
40    },
41    /// Occurs when a pattern string is given to the Aho-Corasick constructor
42    /// that is too long.
43    PatternTooLong {
44        /// The ID of the pattern that was too long.
45        pattern: PatternID,
46        /// The length that was too long.
47        len: usize,
48    },
49}
50
51impl BuildError {
52    pub(crate) fn state_id_overflow(
53        max: u64,
54        requested_max: u64,
55    ) -> BuildError {
56        BuildError { kind: ErrorKind::StateIDOverflow { max, requested_max } }
57    }
58
59    pub(crate) fn pattern_id_overflow(
60        max: u64,
61        requested_max: u64,
62    ) -> BuildError {
63        BuildError {
64            kind: ErrorKind::PatternIDOverflow { max, requested_max },
65        }
66    }
67
68    pub(crate) fn pattern_too_long(
69        pattern: PatternID,
70        len: usize,
71    ) -> BuildError {
72        BuildError { kind: ErrorKind::PatternTooLong { pattern, len } }
73    }
74}
75
76#[cfg(feature = "std")]
77impl std::error::Error for BuildError {}
78
79impl core::fmt::Display for BuildError {
80    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
81        match self.kind {
82            ErrorKind::StateIDOverflow { max, requested_max } => {
83                f.write_fmt(format_args!("state identifier overflow: failed to create state ID from {0}, which exceeds the max of {1}",
        requested_max, max))write!(
84                    f,
85                    "state identifier overflow: failed to create state ID \
86                     from {}, which exceeds the max of {}",
87                    requested_max, max,
88                )
89            }
90            ErrorKind::PatternIDOverflow { max, requested_max } => {
91                f.write_fmt(format_args!("pattern identifier overflow: failed to create pattern ID from {0}, which exceeds the max of {1}",
        requested_max, max))write!(
92                    f,
93                    "pattern identifier overflow: failed to create pattern ID \
94                     from {}, which exceeds the max of {}",
95                    requested_max, max,
96                )
97            }
98            ErrorKind::PatternTooLong { pattern, len } => {
99                f.write_fmt(format_args!("pattern {0} with length {1} exceeds the maximum pattern length of {2}",
        pattern.as_usize(), len, SmallIndex::MAX.as_usize()))write!(
100                    f,
101                    "pattern {} with length {} exceeds \
102                     the maximum pattern length of {}",
103                    pattern.as_usize(),
104                    len,
105                    SmallIndex::MAX.as_usize(),
106                )
107            }
108        }
109    }
110}
111
112/// An error that occurred during an Aho-Corasick search.
113///
114/// An error that occurs during a search is limited to some kind of
115/// misconfiguration that resulted in an illegal call. Stated differently,
116/// whether an error occurs is not dependent on the specific bytes in the
117/// haystack.
118///
119/// Examples of misconfiguration:
120///
121/// * Executing a stream or overlapping search on a searcher that was built was
122/// something other than [`MatchKind::Standard`](crate::MatchKind::Standard)
123/// semantics.
124/// * Requested an anchored or an unanchored search on a searcher that doesn't
125/// support unanchored or anchored searches, respectively.
126///
127/// When the `std` feature is enabled, this implements the `std::error::Error`
128/// trait.
129#[derive(#[automatically_derived]
impl ::core::clone::Clone for MatchError {
    #[inline]
    fn clone(&self) -> MatchError {
        MatchError(::core::clone::Clone::clone(&self.0))
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for MatchError {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_tuple_field1_finish(f, "MatchError",
            &&self.0)
    }
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for MatchError {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _:
                ::core::cmp::AssertParamIsEq<alloc::boxed::Box<MatchErrorKind>>;
    }
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for MatchError {
    #[inline]
    fn eq(&self, other: &MatchError) -> bool { self.0 == other.0 }
}PartialEq)]
130pub struct MatchError(alloc::boxed::Box<MatchErrorKind>);
131
132impl MatchError {
133    /// Create a new error value with the given kind.
134    ///
135    /// This is a more verbose version of the kind-specific constructors, e.g.,
136    /// `MatchError::unsupported_stream`.
137    pub fn new(kind: MatchErrorKind) -> MatchError {
138        MatchError(alloc::boxed::Box::new(kind))
139    }
140
141    /// Returns a reference to the underlying error kind.
142    pub fn kind(&self) -> &MatchErrorKind {
143        &self.0
144    }
145
146    /// Create a new "invalid anchored search" error. This occurs when the
147    /// caller requests an anchored search but where anchored searches aren't
148    /// supported.
149    ///
150    /// This is the same as calling `MatchError::new` with a
151    /// [`MatchErrorKind::InvalidInputAnchored`] kind.
152    pub fn invalid_input_anchored() -> MatchError {
153        MatchError::new(MatchErrorKind::InvalidInputAnchored)
154    }
155
156    /// Create a new "invalid unanchored search" error. This occurs when the
157    /// caller requests an unanchored search but where unanchored searches
158    /// aren't supported.
159    ///
160    /// This is the same as calling `MatchError::new` with a
161    /// [`MatchErrorKind::InvalidInputUnanchored`] kind.
162    pub fn invalid_input_unanchored() -> MatchError {
163        MatchError::new(MatchErrorKind::InvalidInputUnanchored)
164    }
165
166    /// Create a new "unsupported stream search" error. This occurs when the
167    /// caller requests a stream search while using an Aho-Corasick automaton
168    /// with a match kind other than [`MatchKind::Standard`].
169    ///
170    /// The match kind given should be the match kind of the automaton. It
171    /// should never be `MatchKind::Standard`.
172    pub fn unsupported_stream(got: MatchKind) -> MatchError {
173        MatchError::new(MatchErrorKind::UnsupportedStream { got })
174    }
175
176    /// Create a new "unsupported overlapping search" error. This occurs when
177    /// the caller requests an overlapping search while using an Aho-Corasick
178    /// automaton with a match kind other than [`MatchKind::Standard`].
179    ///
180    /// The match kind given should be the match kind of the automaton. It
181    /// should never be `MatchKind::Standard`.
182    pub fn unsupported_overlapping(got: MatchKind) -> MatchError {
183        MatchError::new(MatchErrorKind::UnsupportedOverlapping { got })
184    }
185
186    /// Create a new "unsupported empty pattern" error. This occurs when the
187    /// caller requests a search for which matching an automaton that contains
188    /// an empty pattern string is not supported.
189    pub fn unsupported_empty() -> MatchError {
190        MatchError::new(MatchErrorKind::UnsupportedEmpty)
191    }
192}
193
194/// The underlying kind of a [`MatchError`].
195///
196/// This is a **non-exhaustive** enum. That means new variants may be added in
197/// a semver-compatible release.
198#[non_exhaustive]
199#[derive(#[automatically_derived]
impl ::core::clone::Clone for MatchErrorKind {
    #[inline]
    fn clone(&self) -> MatchErrorKind {
        match self {
            MatchErrorKind::InvalidInputAnchored =>
                MatchErrorKind::InvalidInputAnchored,
            MatchErrorKind::InvalidInputUnanchored =>
                MatchErrorKind::InvalidInputUnanchored,
            MatchErrorKind::UnsupportedStream { got: __self_0 } =>
                MatchErrorKind::UnsupportedStream {
                    got: ::core::clone::Clone::clone(__self_0),
                },
            MatchErrorKind::UnsupportedOverlapping { got: __self_0 } =>
                MatchErrorKind::UnsupportedOverlapping {
                    got: ::core::clone::Clone::clone(__self_0),
                },
            MatchErrorKind::UnsupportedEmpty =>
                MatchErrorKind::UnsupportedEmpty,
        }
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for MatchErrorKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            MatchErrorKind::InvalidInputAnchored =>
                ::core::fmt::Formatter::write_str(f, "InvalidInputAnchored"),
            MatchErrorKind::InvalidInputUnanchored =>
                ::core::fmt::Formatter::write_str(f,
                    "InvalidInputUnanchored"),
            MatchErrorKind::UnsupportedStream { got: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "UnsupportedStream", "got", &__self_0),
            MatchErrorKind::UnsupportedOverlapping { got: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "UnsupportedOverlapping", "got", &__self_0),
            MatchErrorKind::UnsupportedEmpty =>
                ::core::fmt::Formatter::write_str(f, "UnsupportedEmpty"),
        }
    }
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for MatchErrorKind {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<MatchKind>;
    }
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for MatchErrorKind {
    #[inline]
    fn eq(&self, other: &MatchErrorKind) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (MatchErrorKind::UnsupportedStream { got: __self_0 },
                    MatchErrorKind::UnsupportedStream { got: __arg1_0 }) =>
                    __self_0 == __arg1_0,
                (MatchErrorKind::UnsupportedOverlapping { got: __self_0 },
                    MatchErrorKind::UnsupportedOverlapping { got: __arg1_0 }) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq)]
200pub enum MatchErrorKind {
201    /// An error indicating that an anchored search was requested, but from a
202    /// searcher that was built without anchored support.
203    InvalidInputAnchored,
204    /// An error indicating that an unanchored search was requested, but from a
205    /// searcher that was built without unanchored support.
206    InvalidInputUnanchored,
207    /// An error indicating that a stream search was attempted on an
208    /// Aho-Corasick automaton with an unsupported `MatchKind`.
209    UnsupportedStream {
210        /// The match semantics for the automaton that was used.
211        got: MatchKind,
212    },
213    /// An error indicating that an overlapping search was attempted on an
214    /// Aho-Corasick automaton with an unsupported `MatchKind`.
215    UnsupportedOverlapping {
216        /// The match semantics for the automaton that was used.
217        got: MatchKind,
218    },
219    /// An error indicating that the operation requested doesn't support
220    /// automatons that contain an empty pattern string.
221    UnsupportedEmpty,
222}
223
224#[cfg(feature = "std")]
225impl std::error::Error for MatchError {}
226
227impl core::fmt::Display for MatchError {
228    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
229        match *self.kind() {
230            MatchErrorKind::InvalidInputAnchored => {
231                f.write_fmt(format_args!("anchored searches are not supported or enabled"))write!(f, "anchored searches are not supported or enabled")
232            }
233            MatchErrorKind::InvalidInputUnanchored => {
234                f.write_fmt(format_args!("unanchored searches are not supported or enabled"))write!(f, "unanchored searches are not supported or enabled")
235            }
236            MatchErrorKind::UnsupportedStream { got } => {
237                f.write_fmt(format_args!("match kind {0:?} does not support stream searching",
        got))write!(
238                    f,
239                    "match kind {:?} does not support stream searching",
240                    got,
241                )
242            }
243            MatchErrorKind::UnsupportedOverlapping { got } => {
244                f.write_fmt(format_args!("match kind {0:?} does not support overlapping searches",
        got))write!(
245                    f,
246                    "match kind {:?} does not support overlapping searches",
247                    got,
248                )
249            }
250            MatchErrorKind::UnsupportedEmpty => {
251                f.write_fmt(format_args!("matching with an empty pattern string is not supported for this operation"))write!(
252                    f,
253                    "matching with an empty pattern string is not \
254                     supported for this operation",
255                )
256            }
257        }
258    }
259}