• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*!
2 A 128-bit vector implementation of the "packed pair" SIMD algorithm.
3 
4 The "packed pair" algorithm is based on the [generic SIMD] algorithm. The main
5 difference is that it (by default) uses a background distribution of byte
6 frequencies to heuristically select the pair of bytes to search for.
7 
8 [generic SIMD]: http://0x80.pl/articles/simd-strfind.html#first-and-last
9 */
10 
11 use core::arch::wasm32::v128;
12 
13 use crate::arch::{all::packedpair::Pair, generic::packedpair};
14 
15 /// A "packed pair" finder that uses 128-bit vector operations.
16 ///
17 /// This finder picks two bytes that it believes have high predictive power
18 /// for indicating an overall match of a needle. Depending on whether
19 /// `Finder::find` or `Finder::find_prefilter` is used, it reports offsets
20 /// where the needle matches or could match. In the prefilter case, candidates
21 /// are reported whenever the [`Pair`] of bytes given matches.
22 #[derive(Clone, Copy, Debug)]
23 pub struct Finder(packedpair::Finder<v128>);
24 
25 impl Finder {
26     /// Create a new pair searcher. The searcher returned can either report
27     /// exact matches of `needle` or act as a prefilter and report candidate
28     /// positions of `needle`.
29     ///
30     /// If simd128 is unavailable in the current environment or if a [`Pair`]
31     /// could not be constructed from the needle given, then `None` is
32     /// returned.
33     #[inline]
new(needle: &[u8]) -> Option<Finder>34     pub fn new(needle: &[u8]) -> Option<Finder> {
35         Finder::with_pair(needle, Pair::new(needle)?)
36     }
37 
38     /// Create a new "packed pair" finder using the pair of bytes given.
39     ///
40     /// This constructor permits callers to control precisely which pair of
41     /// bytes is used as a predicate.
42     ///
43     /// If simd128 is unavailable in the current environment, then `None` is
44     /// returned.
45     #[inline]
with_pair(needle: &[u8], pair: Pair) -> Option<Finder>46     pub fn with_pair(needle: &[u8], pair: Pair) -> Option<Finder> {
47         if Finder::is_available() {
48             // SAFETY: we check that simd128 is available above. We are also
49             // guaranteed to have needle.len() > 1 because we have a valid
50             // Pair.
51             unsafe { Some(Finder::with_pair_impl(needle, pair)) }
52         } else {
53             None
54         }
55     }
56 
57     /// Create a new `Finder` specific to simd128 vectors and routines.
58     ///
59     /// # Safety
60     ///
61     /// Same as the safety for `packedpair::Finder::new`, and callers must also
62     /// ensure that simd128 is available.
63     #[target_feature(enable = "simd128")]
64     #[inline]
with_pair_impl(needle: &[u8], pair: Pair) -> Finder65     unsafe fn with_pair_impl(needle: &[u8], pair: Pair) -> Finder {
66         let finder = packedpair::Finder::<v128>::new(needle, pair);
67         Finder(finder)
68     }
69 
70     /// Returns true when this implementation is available in the current
71     /// environment.
72     ///
73     /// When this is true, it is guaranteed that [`Finder::with_pair`] will
74     /// return a `Some` value. Similarly, when it is false, it is guaranteed
75     /// that `Finder::with_pair` will return a `None` value. Notice that this
76     /// does not guarantee that [`Finder::new`] will return a `Finder`. Namely,
77     /// even when `Finder::is_available` is true, it is not guaranteed that a
78     /// valid [`Pair`] can be found from the needle given.
79     ///
80     /// Note also that for the lifetime of a single program, if this returns
81     /// true then it will always return true.
82     #[inline]
is_available() -> bool83     pub fn is_available() -> bool {
84         #[cfg(target_feature = "simd128")]
85         {
86             true
87         }
88         #[cfg(not(target_feature = "simd128"))]
89         {
90             false
91         }
92     }
93 
94     /// Execute a search using wasm32 v128 vectors and routines.
95     ///
96     /// # Panics
97     ///
98     /// When `haystack.len()` is less than [`Finder::min_haystack_len`].
99     #[inline]
find(&self, haystack: &[u8], needle: &[u8]) -> Option<usize>100     pub fn find(&self, haystack: &[u8], needle: &[u8]) -> Option<usize> {
101         self.find_impl(haystack, needle)
102     }
103 
104     /// Execute a search using wasm32 v128 vectors and routines.
105     ///
106     /// # Panics
107     ///
108     /// When `haystack.len()` is less than [`Finder::min_haystack_len`].
109     #[inline]
find_prefilter(&self, haystack: &[u8]) -> Option<usize>110     pub fn find_prefilter(&self, haystack: &[u8]) -> Option<usize> {
111         self.find_prefilter_impl(haystack)
112     }
113 
114     /// Execute a search using wasm32 v128 vectors and routines.
115     ///
116     /// # Panics
117     ///
118     /// When `haystack.len()` is less than [`Finder::min_haystack_len`].
119     ///
120     /// # Safety
121     ///
122     /// (The target feature safety obligation is automatically fulfilled by
123     /// virtue of being a method on `Finder`, which can only be constructed
124     /// when it is safe to call `simd128` routines.)
125     #[target_feature(enable = "simd128")]
126     #[inline]
find_impl(&self, haystack: &[u8], needle: &[u8]) -> Option<usize>127     fn find_impl(&self, haystack: &[u8], needle: &[u8]) -> Option<usize> {
128         // SAFETY: The target feature safety obligation is automatically
129         // fulfilled by virtue of being a method on `Finder`, which can only be
130         // constructed when it is safe to call `simd128` routines.
131         unsafe { self.0.find(haystack, needle) }
132     }
133 
134     /// Execute a prefilter search using wasm32 v128 vectors and routines.
135     ///
136     /// # Panics
137     ///
138     /// When `haystack.len()` is less than [`Finder::min_haystack_len`].
139     ///
140     /// # Safety
141     ///
142     /// (The target feature safety obligation is automatically fulfilled by
143     /// virtue of being a method on `Finder`, which can only be constructed
144     /// when it is safe to call `simd128` routines.)
145     #[target_feature(enable = "simd128")]
146     #[inline]
find_prefilter_impl(&self, haystack: &[u8]) -> Option<usize>147     fn find_prefilter_impl(&self, haystack: &[u8]) -> Option<usize> {
148         // SAFETY: The target feature safety obligation is automatically
149         // fulfilled by virtue of being a method on `Finder`, which can only be
150         // constructed when it is safe to call `simd128` routines.
151         unsafe { self.0.find_prefilter(haystack) }
152     }
153 
154     /// Returns the pair of offsets (into the needle) used to check as a
155     /// predicate before confirming whether a needle exists at a particular
156     /// position.
157     #[inline]
pair(&self) -> &Pair158     pub fn pair(&self) -> &Pair {
159         self.0.pair()
160     }
161 
162     /// Returns the minimum haystack length that this `Finder` can search.
163     ///
164     /// Using a haystack with length smaller than this in a search will result
165     /// in a panic. The reason for this restriction is that this finder is
166     /// meant to be a low-level component that is part of a larger substring
167     /// strategy. In that sense, it avoids trying to handle all cases and
168     /// instead only handles the cases that it can handle very well.
169     #[inline]
min_haystack_len(&self) -> usize170     pub fn min_haystack_len(&self) -> usize {
171         self.0.min_haystack_len()
172     }
173 }
174 
175 #[cfg(test)]
176 mod tests {
177     use super::*;
178 
find(haystack: &[u8], needle: &[u8]) -> Option<Option<usize>>179     fn find(haystack: &[u8], needle: &[u8]) -> Option<Option<usize>> {
180         let f = Finder::new(needle)?;
181         if haystack.len() < f.min_haystack_len() {
182             return None;
183         }
184         Some(f.find(haystack, needle))
185     }
186 
187     define_substring_forward_quickcheck!(find);
188 
189     #[test]
forward_substring()190     fn forward_substring() {
191         crate::tests::substring::Runner::new().fwd(find).run()
192     }
193 
194     #[test]
forward_packedpair()195     fn forward_packedpair() {
196         fn find(
197             haystack: &[u8],
198             needle: &[u8],
199             index1: u8,
200             index2: u8,
201         ) -> Option<Option<usize>> {
202             let pair = Pair::with_indices(needle, index1, index2)?;
203             let f = Finder::with_pair(needle, pair)?;
204             if haystack.len() < f.min_haystack_len() {
205                 return None;
206             }
207             Some(f.find(haystack, needle))
208         }
209         crate::tests::packedpair::Runner::new().fwd(find).run()
210     }
211 
212     #[test]
forward_packedpair_prefilter()213     fn forward_packedpair_prefilter() {
214         fn find(
215             haystack: &[u8],
216             needle: &[u8],
217             index1: u8,
218             index2: u8,
219         ) -> Option<Option<usize>> {
220             let pair = Pair::with_indices(needle, index1, index2)?;
221             let f = Finder::with_pair(needle, pair)?;
222             if haystack.len() < f.min_haystack_len() {
223                 return None;
224             }
225             Some(f.find_prefilter(haystack))
226         }
227         crate::tests::packedpair::Runner::new().fwd(find).run()
228     }
229 }
230