├── .gitignore ├── .travis.yml ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.rst ├── benches └── pathology.rs ├── fuzz ├── .gitignore ├── Cargo.toml ├── fuzz_targets │ ├── fuzz_target_1.rs │ └── substring.rs ├── nightly-version ├── run1.sh ├── run1_pcmp.sh ├── run_substring.sh └── run_substring_pcmp.sh ├── src ├── bmh.rs ├── lib.rs ├── pcmp.rs └── tw.rs └── tests └── quick.rs /.gitignore: -------------------------------------------------------------------------------- 1 | Cargo.lock 2 | /target 3 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | sudo: false 3 | 4 | matrix: 5 | include: 6 | - rust: 1.27.0 7 | env: 8 | TARGET=x86_64-unknown-linux-gnu 9 | - rust: stable 10 | env: 11 | TARGET=x86_64-unknown-linux-gnu 12 | - rust: stable 13 | env: 14 | TARGET=i686-unknown-linux-gnu 15 | - rust: beta 16 | env: 17 | TARGET=x86_64-unknown-linux-gnu 18 | - rust: nightly 19 | env: 20 | TARGET=x86_64-unknown-linux-gnu 21 | FEATURES='all benchmarks' 22 | BENCH=1 23 | - rust: nightly 24 | env: 25 | TARGET=x86_64-unknown-linux-gnu 26 | FEATURES='pattern' 27 | - rust: nightly 28 | env: 29 | TARGET=x86_64-unknown-linux-gnu 30 | FEATURES='pattern' 31 | TWOWAY_TEST_DISABLE_PCMP=1 32 | - rust: nightly 33 | env: 34 | TARGET=i686-unknown-linux-gnu 35 | FEATURES='pattern' 36 | - rust: nightly 37 | env: 38 | TARGET=aarch64-unknown-linux-gnu 39 | BUILD_ONLY=1 40 | env: 41 | global: 42 | - HOST=x86_64-unknown-linux-gnu 43 | 44 | addons: 45 | apt: 46 | packages: 47 | # needed for i686-unknown-linux-gnu target 48 | - gcc-multilib 49 | install: 50 | # "rustup error: cannot re-add" without this conditional check 51 | - if [[ $HOST != $TARGET ]]; then rustup target add $TARGET; fi 52 | 53 | branches: 54 | only: 55 | - master 56 | script: 57 | - | 58 | cargo build --verbose --no-default-features --features "$FEATURES" && 59 | cargo build --verbose --features "$FEATURES" && 60 | ([ -n "$BUILD_ONLY" ] || ( 61 | cargo test --verbose --lib && 62 | ([ -z "$FEATURES" ] || cargo test --verbose --features "$FEATURES" ) && 63 | ([ "$BENCH" != 1 ] || cargo bench --verbose --features "$FEATURES") && 64 | cargo doc --verbose --features "$FEATURES" 65 | )) 66 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "twoway" 3 | version = "0.2.2" 4 | authors = ["bluss"] 5 | 6 | description = "(Deprecated - use crate memchr instead.) Fast substring search for strings and byte strings. Optional SSE4.2 acceleration (if detected at runtime) using pcmpestri. Memchr is the only mandatory dependency. The two way algorithm is also used by rust's libstd itself, but here it is exposed both for byte strings, using memchr, and optionally using a SSE4.2 accelerated version." 7 | 8 | license = "MIT/Apache-2.0" 9 | repository = "https://github.com/bluss/twoway" 10 | documentation = "https://docs.rs/twoway/" 11 | 12 | keywords = ["substring-search", "string", "pcmpestri", "find", "memmem"] 13 | categories = ["algorithms", "no-std"] 14 | 15 | [dependencies] 16 | memchr = { version = "2.0", default-features = false } 17 | unchecked-index = { version = "0.2.2" } 18 | jetscii = {version = "0.3", features= ["unstable"], optional = true } 19 | galil-seiferas = { version = "0.1.1", optional = true } 20 | 21 | [dev-dependencies] 22 | itertools = "0.8.0" 23 | odds = { version = "0.3", features=["std-string"] } 24 | macro-attr = "0.2" 25 | newtype_derive = "0.1" 26 | rand = "0.6" 27 | quickcheck = { version = "0.8", default-features = false } 28 | 29 | [features] 30 | # stable and pcmp support: opting out of using std, becoming no_std 31 | default = ["use_std"] 32 | use_std = ["memchr/use_std"] 33 | 34 | # Internal features for testing & benchmarking & development 35 | pattern = [] 36 | benchmarks = ["galil-seiferas", "pattern"] 37 | all = ["jetscii", "pattern"] 38 | 39 | 40 | [package.metadata.release] 41 | no-dev-version = true 42 | tag-name = "{{version}}" 43 | 44 | [badges] 45 | maintenance = { status = "deprecated" } 46 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | 2 | This is my substring search workspace. 3 | 4 | Please read the `API documentation here`__ 5 | 6 | __ https://docs.rs/twoway/ 7 | 8 | |build_status|_ |crates|_ 9 | 10 | .. |build_status| image:: https://travis-ci.org/bluss/twoway.svg?branch=master 11 | .. _build_status: https://travis-ci.org/bluss/twoway 12 | 13 | .. |crates| image:: http://meritbadge.herokuapp.com/twoway 14 | .. _crates: https://crates.io/crates/twoway 15 | 16 | Documentation 17 | ------------- 18 | 19 | Fast substring search for strings and byte strings, using the `two-way algorithm`_. 20 | 21 | This is the same code as is included in Rust's libstd to “power” ``str::find(&str)``, 22 | but here it is exposed with some improvements: 23 | 24 | - Available for byte string searches using ``&[u8]`` 25 | - Having an optional SSE4.2 accelerated version (if detected at runtime) which is even faster. 26 | - Using ``memchr`` for the single byte case, which is ultra fast. 27 | 28 | - ``twoway::find_bytes(text: &[u8], pattern: &[u8]) -> Option`` 29 | - ``twoway::rfind_bytes(text: &[u8], pattern: &[u8]) -> Option`` 30 | - ``twoway::find_str(text: &str, pattern: &str) -> Option`` 31 | - ``twoway::rfind_str(text: &str, pattern: &str) -> Option`` 32 | 33 | Recent Changes 34 | -------------- 35 | 36 | - 0.2.1 37 | 38 | - Update dev-deps 39 | 40 | - 0.2.0 41 | 42 | - Use `std::arch` and transparently support SSE4.2 when possible (x86 and 43 | x86-64 only) to enable an accelerated implementation of the algorithm. 44 | Forward search only. By @RReverser and @bluss 45 | - Fix a bug in the SSE4.2 algorithm that made it much slower than it should have been, 46 | so performance increases as well. 47 | - Requires Rust 1.27 48 | 49 | - 0.1.8 50 | 51 | - Tweak crate keywords by @tari 52 | - Only testing and benchmarking changes otherwise (no changes to the crate itself) 53 | 54 | - 0.1.7 55 | 56 | - The crate is optionally ``no_std``. Regular and ``pcmp`` both support this 57 | mode. 58 | 59 | - 0.1.6 60 | 61 | - The hidden and internal test module set, technically pub, was removed from 62 | standard compilation. 63 | 64 | - 0.1.5 65 | 66 | - Update from an odds dependency to using ``unchecked-index`` instead 67 | (only used by the pcmp feature). 68 | - The hidden and internal test module tw, technically pub, was removed from 69 | standard compilation. 70 | 71 | - 0.1.4 72 | 73 | - Update memchr dependency to 2.0 74 | 75 | - 0.1.3 76 | 77 | - Link to docs.rs docs 78 | - Drop ``pcmp``'s itertools dependency 79 | - Update nightly code for recent changes 80 | 81 | - 0.1.2 82 | 83 | - Internal improvements to the ``pcmp`` module. 84 | 85 | - 0.1.1 86 | 87 | - Add ``rfind_bytes``, ``rfind_str`` 88 | 89 | - 0.1.0 90 | 91 | - Initial release 92 | - Add ``find_bytes``, ``find_str`` 93 | 94 | License 95 | ------- 96 | 97 | MIT / APACHE-2.0 98 | 99 | 100 | Interesting Links 101 | ----------------- 102 | 103 | .. _`two-way algorithm`: http://www-igm.univ-mlv.fr/~lecroq/string/node26.html 104 | 105 | - Two Way: http://www-igm.univ-mlv.fr/~lecroq/string/node26.html 106 | - Matters Computational: http://www.jjj.de/fxt/#fxtbook 107 | 108 | 109 | Notes 110 | ----- 111 | 112 | Consider denying 0/n factorizations, see 113 | http://lists.gnu.org/archive/html/bug-gnulib/2010-06/msg00184.html 114 | -------------------------------------------------------------------------------- /benches/pathology.rs: -------------------------------------------------------------------------------- 1 | #![feature(test)] 2 | #![feature( 3 | pattern, )] 4 | 5 | #![allow(unused_imports)] 6 | extern crate test; 7 | #[cfg(feature = "jetscii")] 8 | extern crate jetscii; 9 | extern crate itertools; 10 | extern crate odds; 11 | #[cfg(feature = "benchmarks")] 12 | extern crate galil_seiferas; 13 | extern crate unchecked_index; 14 | 15 | extern crate twoway; 16 | 17 | #[cfg(unused)] 18 | macro_rules! regex { 19 | ($e:expr) => (::regex::Regex::new($e).unwrap()); 20 | } 21 | 22 | pub use twoway::{Str}; 23 | 24 | use std::str::pattern::{Pattern, Searcher, ReverseSearcher}; 25 | use test::{Bencher, black_box}; 26 | 27 | use twoway::find_str as tw_find; 28 | use twoway::rfind_str as tw_rfind; 29 | 30 | /* 31 | pub fn is_prefix(text: &str, pattern: &str) -> bool { 32 | Str(pattern).is_prefix_of(text) 33 | } 34 | */ 35 | 36 | pub fn memmem(text: &str, pattern: &str) -> bool { 37 | #[allow(improper_ctypes)] 38 | extern { fn memmem(s1: *const u8, m: usize, s2: *const u8, pattern: usize) -> *const u8; } 39 | unsafe { 40 | memmem(text.as_ptr(), 41 | text.len(), 42 | pattern.as_ptr(), 43 | pattern.len()) != 0 as *mut u8 44 | } 45 | 46 | } 47 | 48 | macro_rules! get { 49 | ($slice:expr, $index:expr) => { 50 | unsafe { ::unchecked_index::get_unchecked(&$slice, $index) } 51 | } 52 | } 53 | 54 | fn brute_force(text: &[T], pattern: &[T]) -> Option { 55 | let n = text.len(); 56 | let m = pattern.len(); 57 | if n < m { 58 | return None; 59 | } 60 | 'outer: for i in 0..n - m + 1 { 61 | 62 | /* to use memcmp: 63 | * it's a tradeoff; memcmp is faster with more pathological-y inputs! 64 | * for relistic inputs where we quickly find a mismatch at most 65 | * postions, it's faster using just single element get. 66 | if get!(text, i .. i + m) == pattern { 67 | return Some(i); 68 | } 69 | */ 70 | 71 | for j in 0..m { 72 | if get!(text, i + j) != get!(pattern, j) { 73 | continue 'outer; 74 | } 75 | } 76 | return Some(i); 77 | } 78 | None 79 | } 80 | 81 | 82 | macro_rules! bench_contains_vs_tw { 83 | ($name: ident, $hay: expr, $n: expr) => { 84 | pub mod $name { 85 | use super::{test, tw_find, tw_rfind, 86 | LONG, 87 | LONG_CY, 88 | }; 89 | use itertools::Itertools; 90 | use twoway::TwoWaySearcher; 91 | use test::{Bencher, black_box}; 92 | #[cfg(feature = "jetscii")] 93 | use jetscii::Substring; 94 | use odds::string::StrExt; 95 | 96 | #[bench] 97 | pub fn find(b: &mut Bencher) { 98 | let haystack = black_box($hay); 99 | let needle = black_box($n); 100 | b.iter(|| { 101 | test::black_box(haystack.find(&needle)); 102 | }); 103 | b.bytes = haystack.len() as u64; 104 | } 105 | 106 | #[bench] 107 | pub fn rfind(b: &mut Bencher) { 108 | let haystack = black_box($hay); 109 | let needle = black_box($n); 110 | b.iter(|| { 111 | test::black_box(haystack.rfind(&needle)); 112 | }); 113 | b.bytes = haystack.len() as u64; 114 | } 115 | 116 | /* 117 | #[bench] 118 | pub fn regex_find(b: &mut Bencher) { 119 | let haystack = black_box($hay); 120 | let needle = black_box($n); 121 | let reg = regex!(&needle); 122 | b.iter(|| { 123 | reg.find(&haystack) 124 | }); 125 | b.bytes = haystack.len() as u64; 126 | } 127 | */ 128 | 129 | #[cfg(feature = "jetscii")] 130 | #[bench] 131 | pub fn jetscii_find(b: &mut Bencher) { 132 | let haystack = black_box($hay); 133 | let needle = black_box($n); 134 | b.iter(|| { 135 | haystack.find(Substring::new(&needle)) 136 | }); 137 | b.bytes = haystack.len() as u64; 138 | } 139 | 140 | /* 141 | #[bench] 142 | pub fn str_is_prefix(b: &mut Bencher) { 143 | let haystack = $hay; 144 | let needle = $n; 145 | b.iter(|| { 146 | let needle = test::black_box(&needle); 147 | let haystack = test::black_box(&haystack); 148 | test::black_box(needle.is_prefix_of(haystack)); 149 | }); 150 | b.bytes = needle.len() as u64; 151 | } 152 | */ 153 | 154 | /* 155 | #[bench] 156 | pub fn str_first_reject(b: &mut Bencher) { 157 | let haystack = $hay; 158 | let needle = $n; 159 | b.iter(|| { 160 | let needle = test::black_box(&needle); 161 | let haystack = test::black_box(&haystack); 162 | test::black_box(needle.into_searcher(haystack).next_reject()) 163 | }); 164 | } 165 | */ 166 | 167 | #[bench] 168 | pub fn pcmp_find(b: &mut Bencher) { 169 | let haystack = black_box($hay); 170 | let needle = black_box($n); 171 | b.iter(|| { 172 | test::black_box(::twoway::pcmp::find(haystack.as_bytes(), needle.as_bytes())); 173 | }); 174 | b.bytes = haystack.len() as u64; 175 | } 176 | 177 | #[bench] 178 | pub fn bmh_find(b: &mut Bencher) { 179 | let haystack = black_box($hay); 180 | let needle = black_box($n); 181 | b.iter(|| { 182 | test::black_box(::twoway::bmh::find(haystack.as_bytes(), needle.as_bytes())); 183 | }); 184 | b.bytes = haystack.len() as u64; 185 | } 186 | 187 | #[bench] 188 | pub fn memmem(b: &mut Bencher) { 189 | let haystack = black_box($hay); 190 | let needle = black_box($n); 191 | b.iter(|| { 192 | test::black_box(::memmem(&haystack, &needle)); 193 | }); 194 | b.bytes = haystack.len() as u64; 195 | } 196 | 197 | #[bench] 198 | pub fn twoway_find(b: &mut Bencher) { 199 | let haystack = $hay; 200 | let needle = $n; 201 | b.iter(|| { 202 | let needle = test::black_box(&needle); 203 | let haystack = test::black_box(&haystack); 204 | test::black_box(tw_find(haystack, needle)); 205 | }); 206 | b.bytes = haystack.len() as u64; 207 | } 208 | 209 | 210 | #[cfg(feature = "benchmarks")] 211 | #[bench] 212 | pub fn gs_find(b: &mut Bencher) { 213 | let haystack = $hay; 214 | let needle = $n; 215 | b.iter(|| { 216 | let needle = test::black_box(&needle); 217 | let haystack = test::black_box(&haystack); 218 | ::galil_seiferas::gs_find(haystack.as_bytes(), needle.as_bytes()) 219 | }); 220 | b.bytes = haystack.len() as u64; 221 | } 222 | 223 | #[bench] 224 | pub fn brute_force(b: &mut Bencher) { 225 | let haystack = $hay; 226 | let needle = $n; 227 | b.iter(|| { 228 | let needle = test::black_box(&needle); 229 | let haystack = test::black_box(&haystack); 230 | ::brute_force(haystack.as_bytes(), needle.as_bytes()) 231 | }); 232 | b.bytes = haystack.len() as u64; 233 | } 234 | 235 | #[bench] 236 | pub fn twoway_rfind(b: &mut Bencher) { 237 | let haystack = $hay; 238 | let needle = $n; 239 | b.iter(|| { 240 | let needle = test::black_box(&needle); 241 | let haystack = test::black_box(&haystack); 242 | test::black_box(tw_rfind(haystack, needle)); 243 | }); 244 | b.bytes = haystack.len() as u64; 245 | } 246 | 247 | /* 248 | #[bench] 249 | pub fn tw_is_prefix(b: &mut Bencher) { 250 | let haystack = $hay; 251 | let needle = $n; 252 | b.iter(|| { 253 | let needle = test::black_box(&needle); 254 | let haystack = test::black_box(&haystack); 255 | test::black_box(is_prefix(haystack, needle)); 256 | }); 257 | b.bytes = needle.len() as u64; 258 | } 259 | */ 260 | 261 | #[bench] 262 | pub fn twoway_new(b: &mut Bencher) { 263 | let needle = black_box($n); 264 | b.iter(|| { 265 | let needle = needle.as_bytes(); 266 | let t = TwoWaySearcher::new(needle, 1); 267 | t 268 | }); 269 | b.bytes = needle.len() as u64; 270 | } 271 | 272 | /* 273 | #[bench] 274 | pub fn pcmp_is_prefix(b: &mut Bencher) { 275 | let haystack = $hay; 276 | let needle = $n; 277 | b.iter(|| { 278 | let needle = test::black_box(&needle); 279 | let haystack = test::black_box(&haystack); 280 | let l = ::std::cmp::min(needle.len(), haystack.len()); 281 | l == ::twoway::pcmp::shared_prefix(haystack.as_bytes(), needle.as_bytes()) 282 | }); 283 | b.bytes = needle.len() as u64; 284 | } 285 | */ 286 | 287 | /* 288 | #[bench] 289 | pub fn tw_first_reject(b: &mut Bencher) { 290 | let haystack = $hay; 291 | let needle = $n; 292 | b.iter(|| { 293 | let needle = test::black_box(&needle); 294 | let haystack = test::black_box(&haystack); 295 | test::black_box(Str(needle).into_searcher(haystack).next_reject()) 296 | }); 297 | } 298 | */ 299 | 300 | /* 301 | #[bench] 302 | pub fn tw_paper(b: &mut Bencher) { 303 | use twoway::tw::{find_first, Str}; 304 | let haystack = $hay; 305 | let needle = $n; 306 | b.iter(|| { 307 | let needle = test::black_box(Str(needle.as_bytes())); 308 | let haystack = test::black_box(Str(haystack.as_bytes())); 309 | test::black_box(find_first(haystack, needle)); 310 | }); 311 | b.bytes = haystack.len() as u64; 312 | } 313 | */ 314 | } 315 | } 316 | } 317 | 318 | 319 | static LONG: &'static str = "\ 320 | Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse quis lorem sit amet dolor \ 321 | ultricies condimentum. Praesent iaculis purus elit, ac malesuada quam malesuada in. Duis sed orci \ 322 | eros. Suspendisse sit amet magna mollis, mollis nunc luctus, imperdiet mi. Integer fringilla non \ 323 | sem ut lacinia. Fusce varius tortor a risus porttitor hendrerit. Morbi mauris dui, ultricies nec \ 324 | tempus vel, gravida nec quam. 325 | 326 | In est dui, tincidunt sed tempus interdum, adipiscing laoreet ante. Etiam tempor, tellus quis \ 327 | sagittis interdum, nulla purus mattis sem, quis auctor erat odio ac tellus. In nec nunc sit amet \ 328 | diam volutpat molestie at sed ipsum. Vestibulum laoreet consequat vulputate. Integer accumsan \ 329 | lorem ac dignissim placerat. Suspendisse convallis faucibus lorem. Aliquam erat volutpat. In vel \ 330 | eleifend felis. Sed suscipit nulla lorem, sed mollis est sollicitudin et. Nam fermentum egestas \ 331 | interdum. Curabitur ut nisi justo. 332 | 333 | Sed sollicitudin ipsum tellus, ut condimentum leo eleifend nec. Cras ut velit ante. Phasellus nec \ 334 | mollis odio. Mauris molestie erat in arcu mattis, at aliquet dolor vehicula. Quisque malesuada \ 335 | lectus sit amet nisi pretium, a condimentum ipsum porta. Morbi at dapibus diam. Praesent egestas \ 336 | est sed risus elementum, eu rutrum metus ultrices. Etiam fermentum consectetur magna, id rutrum \ 337 | felis accumsan a. Aliquam ut pellentesque libero. Sed mi nulla, lobortis eu tortor id, suscipit \ 338 | ultricies neque. Morbi iaculis sit amet risus at iaculis. Praesent eget ligula quis turpis \ 339 | feugiat suscipit vel non arcu. Interdum et malesuada fames ac ante ipsum primis in faucibus. \ 340 | Aliquam sit amet placerat lorem. 341 | 342 | Cras a lacus vel ante posuere elementum. Nunc est leo, bibendum ut facilisis vel, bibendum at \ 343 | mauris. Nullam adipiscing diam vel odio ornare, luctus adipiscing mi luctus. Nulla facilisi. \ 344 | Mauris adipiscing bibendum neque, quis adipiscing lectus tempus et. Sed feugiat erat et nisl \ 345 | lobortis pharetra. Donec vitae erat enim. Nullam sit amet felis et quam lacinia tincidunt. Aliquam \ 346 | suscipit dapibus urna. Sed volutpat urna in magna pulvinar volutpat. Phasellus nec tellus ac diam \ 347 | cursus accumsan. 348 | 349 | Nam lectus enim, dapibus non nisi tempor, consectetur convallis massa. Maecenas eleifend dictum \ 350 | feugiat. Etiam quis mauris vel risus luctus mattis a a nunc. Nullam orci quam, imperdiet id \ 351 | vehicula in, porttitor ut nibh. Duis sagittis adipiscing nisl vitae congue. Donec mollis risus eu \ 352 | leo suscipit, varius porttitor nulla porta. Pellentesque ut sem nec nisi euismod vehicula. Nulla \ 353 | malesuada sollicitudin quam eu fermentum."; 354 | 355 | static LONG_CY: &'static str = "\ 356 | Брутэ дольорэ компрэхэнжам йн эжт, ючю коммюны дылыктуч эа, квюо льаорыыт вёвындо мэнандря экз. Ед ыюм емпыдит аккюсам, нык дйкит ютенам ад. Хаж аппэтырэ хонэзтатёз нэ. Ад мовэт путант юрбанйтаж вяш. 357 | 358 | Коммодо квюальизквюэ абхоррэант нэ ыюм, праэчынт еракюндйа ылаборарэт эю мыа. Нэ квуым жюмо вольуптатибюж вяш, про ыт бонорюм вёвындо, мэя юллюм новум ку. Пропрёаы такематыш атоморюм зыд ан. Эи омнэжквюы оффекйяж компрэхэнжам жят, апыирёан конкыптам ёнкорруптэ ючю ыт. 359 | 360 | Жят алёа лэгыры ед, эи мацим оффэндйт вим. Нык хёнк льаборэж йн, зыд прима тимэам ан. Векж нужквюам инимёкюж ты, ыам эа омнеж ырант рэформйданч. Эрож оффекйяж эю вэл. 361 | 362 | Ад нам ножтрюд долорюм, еюж ут вэрыар эюрйпйдяч. Квюач аффэрт тинкидюнт про экз, дёкант вольуптатибюж ат зыд. Ыт зыд экшырки констятюам. Квюо квюиж юрбанйтаж ометтантур экз, хёз экз мютат граэкы рыкючабо, нэ прё пюрто элитр пэрпэтюа. Но квюандо минемум ыам. 363 | 364 | Амэт лыгимуз ометтантур кюм ан. Витюпырата котёдиэквюэ нам эю, эю вокынт алёквюам льебэравичсы жят. Экз пыртенакж янтэрэсщэт инзтруктеор нам, еюж ад дйкит каючаэ, шэа витаэ конжтетуто ут. Квюач мандамюч кюм ат, но ёнкорруптэ рэформйданч ючю, незл либриз аюдирэ зыд эи. Ты эож аугюэ иреуры льюкяльиюч, мэль алььтыра докэндё омнэжквюы ат. Анёмал жямиляквюы аккоммодары ыам нэ, экз пэрчёус дэфянятйоныс квюо. Эи дуо фюгит маиорюм. 365 | 366 | Эвэртё партйэндо пытынтёюм ыюм ан, шэа ку промпта квюаырэндум. Агам дикунт вим ку. Мюкиуж аюдиам тамквюам про ут, ку мыа квюод квюот эррэм, вяш ад номинави зючкёпит янжольэнж. Нык эи пожжёт путант эффякиантур. Ку еюж нощтыр контынтёонэж. Кюм йужто харюм ёужто ад, ыюм оратио квюоджё экз. 367 | 368 | Чонэт факэтэ кюм ан, вэре факэр зальютатуж мэя но. Ыюм ут зальы эффикеэнди, экз про алиё конжыквуюнтюр. Квуй ыльит хабымуч ты, алёа омнэжквюы мандамюч шэа ыт, пльакырат аккюжамюз нэ мэль. Хаж нэ партым нюмквуам прёнкипыз, ат импэрдеэт форынчйбюж кончэктэтюыр шэа. Пльакырат рэформйданч эи векж, ючю дюиж фюйзчыт эи. 369 | 370 | Экз квюо ажжюм аугюэ, ат нык мёнём анёмал кытэрож. Кюм выльёт эрюдитя эа. Йн порро малйж кончэктэтюыр хёз, жят кашы эрюдитя ат. Эа вяш мацим пыртенакж, но порро утамюр дяшзынтиыт кюм. Ыт мютат зючкёпит эож, нэ про еракюндйа котёдиэквюэ. Квуй лаудым плььатонэм ед, ку вим ножтрюм лаборамюз. 371 | 372 | Вёжи янвыняры хаж ед, ты нолюёжжэ индоктум квуй. Квюач тебиквюэ ут жят, тальэ адхюк убяквюэ йн эож. Ыррор бландит вяш ан, ютроквюы нолюёжжэ констятюам йн ыюм, жят эи прима нобёз тхэопхражтуз. Ты дёкант дэльэнйт нолюёжжэ пэр, молыжтйаы модыратиюз интыллыгам ку мэль. 373 | 374 | Ад ылаборарэт конжыквуюнтюр ентырпрытаряш прё, факэтэ лыгэндоч окюррырэт вим ад, элитр рэформйданч квуй ед. Жюмо зальы либриз мэя ты. Незл зюаз видишчы ан ыюм, но пожжэ молыжтйаы мэль. Фиэрэнт адипижкй ометтантур квюо экз. Ут мольлиз пырикюлёз квуй. Ыт квюиж граэко рыпудяары жят, вим магна обльйквюэ контынтёонэж эю, ты шэа эним компльыктётюр. 375 | "; 376 | 377 | bench_contains_vs_tw!(short_short, 378 | "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", 379 | "tis"); 380 | 381 | // a word with some uncommon letters 382 | bench_contains_vs_tw!(short_word1_long, 383 | LONG, 384 | "english"); 385 | 386 | // a word of only common letters (but does not appear) 387 | bench_contains_vs_tw!(short_word2_long, 388 | LONG, 389 | "lite"); 390 | 391 | bench_contains_vs_tw!(short_1let_long, 392 | LONG, 393 | "z"); 394 | 395 | bench_contains_vs_tw!(short_2let_rare, 396 | LONG, 397 | "qq"); 398 | 399 | bench_contains_vs_tw!(short_2let_common, 400 | LONG, 401 | "uu"); 402 | 403 | bench_contains_vs_tw!(short_3let_long, 404 | LONG, 405 | "aga"); 406 | 407 | bench_contains_vs_tw!(short_1let_cy, 408 | LONG_CY, 409 | "Ѯ"); 410 | 411 | bench_contains_vs_tw!(short_2let_cy, 412 | LONG_CY, 413 | "оо"); 414 | 415 | bench_contains_vs_tw!(short_3let_cy, 416 | LONG_CY, 417 | "коэ"); 418 | 419 | bench_contains_vs_tw!(naive, 420 | "a".repeat(250), 421 | "aaaaaaaab"); 422 | 423 | bench_contains_vs_tw!(naive_rev, 424 | "a".repeat(250), 425 | "baaaaaaaa"); 426 | 427 | bench_contains_vs_tw!(naive_longpat, 428 | "a".repeat(100_000), 429 | "a".repeat(24).append("b")); 430 | 431 | bench_contains_vs_tw!(naive_longpat_reversed, 432 | "a".repeat(100_000), 433 | "b".append(&"a".repeat(24))); 434 | 435 | bench_contains_vs_tw!(bb_in_aa, 436 | "a".repeat(100_000), 437 | "b".repeat(100)); 438 | 439 | bench_contains_vs_tw!(aaab_in_aab, 440 | "aab".repeat(100_000), 441 | "aaab".repeat(100)); 442 | 443 | bench_contains_vs_tw!(periodic2, 444 | "bb".append(&"ab".repeat(99)).repeat(100), 445 | "ab".repeat(100)); 446 | 447 | bench_contains_vs_tw!(periodic5, 448 | "bacba".repeat(39).append("bbbbb").repeat(40), 449 | "bacba".repeat(40)); 450 | 451 | // This one is two-way specific 452 | bench_contains_vs_tw!(pathological_two_way, 453 | "dac".repeat(20_000), 454 | "bac"); 455 | 456 | // This one is two-way specific 457 | bench_contains_vs_tw!(pathological_two_way_rev, 458 | "cad".repeat(20_000), 459 | "cab"); 460 | 461 | bench_contains_vs_tw!(bbbaaa, 462 | "aab".repeat(100_000), 463 | "b".repeat(100) + &"a".repeat(100)); 464 | 465 | bench_contains_vs_tw!(aaabbb, 466 | "aab".repeat(100_000), 467 | "a".repeat(100) + &"b".repeat(100)); 468 | 469 | bench_contains_vs_tw!(allright, 470 | "allrightagtogether".repeat(10_000), 471 | "allrightaltogether"); 472 | 473 | bench_contains_vs_tw!(gllright, 474 | "gllrightaltogether".repeat(10_000), 475 | "allrightaltogether"); 476 | 477 | 478 | /* 479 | bench_contains_vs_tw!(long_prefix, 480 | (0..20_000).map(|_| "cad").collect::(), 481 | (0..100).map(|_| "cad").collect::()); 482 | */ 483 | 484 | /* 485 | bench_contains_vs_tw!(pathological_test1, 486 | (0..10_000).map(|_| "daaaaaaaaacc").collect::(), 487 | (0..100).map(|_| "eaaaaaaaaacc").collect::()); 488 | */ 489 | 490 | /* 491 | // This one is two-way specific 492 | bench_contains_vs_tw!(long_trim, 493 | (0..20_000).map(|_| "abcd").collect::(), 494 | "abc"); 495 | */ 496 | 497 | #[bench] 498 | pub fn find_char_1(b: &mut Bencher) { 499 | let haystack = black_box(LONG); 500 | let needle = black_box('z'); 501 | b.iter(|| { 502 | let t = haystack.find(needle); 503 | t 504 | }); 505 | b.bytes = haystack.len() as u64; 506 | } 507 | 508 | #[bench] 509 | pub fn find_char_2(b: &mut Bencher) { 510 | let haystack = black_box(LONG); 511 | let needle = black_box('ö'); 512 | b.iter(|| { 513 | let t = haystack.find(needle); 514 | t 515 | }); 516 | b.bytes = haystack.len() as u64; 517 | } 518 | 519 | #[bench] 520 | pub fn find_char_3(b: &mut Bencher) { 521 | let haystack = black_box(LONG); 522 | let needle = black_box('α'); 523 | b.iter(|| { 524 | let t = haystack.find(needle); 525 | t 526 | }); 527 | b.bytes = haystack.len() as u64; 528 | } 529 | 530 | #[bench] 531 | pub fn rfind_char_1(b: &mut Bencher) { 532 | let haystack = black_box(LONG); 533 | let needle = black_box('z'); 534 | b.iter(|| { 535 | let t = haystack.rfind(needle); 536 | t 537 | }); 538 | b.bytes = haystack.len() as u64; 539 | } 540 | -------------------------------------------------------------------------------- /fuzz/.gitignore: -------------------------------------------------------------------------------- 1 | 2 | /target 3 | /corpus 4 | /artifacts 5 | -------------------------------------------------------------------------------- /fuzz/Cargo.toml: -------------------------------------------------------------------------------- 1 | 2 | [package] 3 | name = "twoway-fuzz" 4 | version = "0.0.1" 5 | authors = ["Automatically generated"] 6 | publish = false 7 | 8 | [package.metadata] 9 | cargo-fuzz = true 10 | 11 | [dependencies.twoway] 12 | path = ".." 13 | [dependencies.libfuzzer-sys] 14 | git = "https://github.com/rust-fuzz/libfuzzer-sys.git" 15 | 16 | # Prevent this from interfering with workspaces 17 | [workspace] 18 | members = ["."] 19 | 20 | [[bin]] 21 | name = "fuzz_target_1" 22 | path = "fuzz_targets/fuzz_target_1.rs" 23 | 24 | [[bin]] 25 | name = "substring" 26 | path = "fuzz_targets/substring.rs" 27 | -------------------------------------------------------------------------------- /fuzz/fuzz_targets/fuzz_target_1.rs: -------------------------------------------------------------------------------- 1 | #![no_main] 2 | #[macro_use] extern crate libfuzzer_sys; 3 | extern crate twoway; 4 | 5 | use std::mem::transmute; 6 | 7 | // This fuzzing target splits data into two parts, and asserts that 8 | // the result of str::find and twoway::find_str agree when passed 9 | // the two &str parts as their parameters. 10 | // 11 | // A precondition is that the data is valid utf-8 (fuzzer is configured to use 12 | // ascii only). 13 | 14 | fuzz_target!(|data: &[u8]| { 15 | if data.len() > 2 { 16 | // use first 2 bytes as split point 17 | let (a, b) = (data[0] as usize, data[1] as usize); 18 | let (_, data) = data.split_at(2); 19 | 20 | // data is ascii only. We use a transmute to not put extra 21 | // code into the fuzzing, we don't want to fuzz utf-8 checking etc. 22 | let data: &str = unsafe { transmute(data) }; 23 | let needle_split = ((a << 7) | b).min(data.len()); 24 | let (needle, hay) = data.split_at(needle_split); 25 | assert_eq!(str::find(hay, needle), twoway::find_str(hay, needle)); 26 | } 27 | }); 28 | -------------------------------------------------------------------------------- /fuzz/fuzz_targets/substring.rs: -------------------------------------------------------------------------------- 1 | #![no_main] 2 | #[macro_use] extern crate libfuzzer_sys; 3 | 4 | use std::cmp::{min, max}; 5 | extern crate twoway; 6 | 7 | // This fuzzer tests that given a slice data, pick a subslice out of it 8 | // and check that the find_bytes function can find the correct position 9 | // of the subslice inside the whole data. 10 | // 11 | // The first 4 bytes are only used for picking the boundaries of the 12 | // subslice (so nothing is random, it's driven by the contents of data). 13 | 14 | fuzz_target!(|data: &[u8]| { 15 | if data.len() > 4 { 16 | let len = data.len() - 4; 17 | // use first 4 bytes as delimiters 18 | let (a, b) = (data[0] as usize, data[1] as usize); 19 | let first = ((a << 8) | b) % len; 20 | let (a, b) = (data[2] as usize, data[3] as usize); 21 | let second = ((a << 8) | b) % len; 22 | let (first, second) = (min(first, second), max(first, second)); 23 | let (_, data) = data.split_at(4); 24 | let needle = &data[first..second]; 25 | 26 | let find_result = twoway::find_bytes(data, needle); 27 | if let Some(i) = find_result { 28 | assert!(i <= first, "i={} must be leq first={}", i, first); 29 | } else { 30 | panic!("Expected match at first={}\ndata={:?}, needle={:?}", first, data, needle); 31 | } 32 | } 33 | }); 34 | -------------------------------------------------------------------------------- /fuzz/nightly-version: -------------------------------------------------------------------------------- 1 | nightly 2 | -------------------------------------------------------------------------------- /fuzz/run1.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | DIR=$(dirname "$0") 4 | V=$(cat "$DIR"/nightly-version) 5 | cargo +$V fuzz run -O fuzz_target_1 -- -only_ascii=1 -max_len=512 "$@" 6 | -------------------------------------------------------------------------------- /fuzz/run1_pcmp.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | DIR=$(dirname "$0") 4 | V=$(cat "$DIR"/nightly-version) 5 | cargo +$V fuzz run -O -a fuzz_target_1 -- -only_ascii=1 -max_len=5000 "$@" 6 | -------------------------------------------------------------------------------- /fuzz/run_substring.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | DIR=$(dirname "$0") 4 | V=$(cat "$DIR"/nightly-version) 5 | cargo +$V fuzz run -O substring -- -only_ascii=1 -max_len=256 "$@" 6 | -------------------------------------------------------------------------------- /fuzz/run_substring_pcmp.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | DIR=$(dirname "$0") 4 | V=$(cat "$DIR"/nightly-version) 5 | cargo +$V fuzz run -O substring -- -only_ascii=1 -max_len=256 "$@" 6 | -------------------------------------------------------------------------------- /src/bmh.rs: -------------------------------------------------------------------------------- 1 | //! Boyer-Moore-Horspool 2 | //! 3 | 4 | extern crate memchr; 5 | use std::cmp; 6 | 7 | fn bmh_skip(pat: &[u8], skip: &mut [u16; 256]) { 8 | let pat_skip = cmp::min(pat.len(), u16::max_value() as usize) as u16; 9 | for entry in skip.iter_mut() { 10 | *entry = pat_skip; 11 | } 12 | 13 | for (index, &byte) in pat[..pat.len() - 1].iter().enumerate() { 14 | skip[byte as usize] = cmp::min(pat.len() - index - 1, u16::max_value() as usize) as u16; 15 | } 16 | } 17 | 18 | /// Boyer-Moore-Horspool substring search 19 | pub fn find(text: &[u8], pat: &[u8]) -> Option { 20 | let mut skip = [0; 256]; 21 | bmh_skip(pat, &mut skip); 22 | 23 | let pat_len = pat.len(); 24 | 25 | if pat_len == 0 { 26 | return Some(0); 27 | } 28 | 29 | let pat_len_m1 = pat_len - 1; 30 | let pat_last = pat[pat_len - 1]; 31 | 32 | // initial search by memchr 33 | let mut j = match memchr::memchr(pat[0], text) { 34 | Some(x) => x, 35 | None => return None, 36 | }; 37 | 38 | while let Some(&c) = text.get(j + pat_len_m1) { 39 | // check the back character of the pattern 40 | if c == pat_last && &text[j..j + pat_len] == pat { 41 | return Some(j); 42 | } 43 | j += skip[c as usize] as usize; 44 | } 45 | None 46 | } 47 | 48 | #[test] 49 | fn bmh_preprocess() { 50 | let mut skip = [0; 256]; 51 | let needle = b"gcagagag"; 52 | bmh_skip(needle, &mut skip); 53 | assert_eq!(skip[b'g' as usize], 2); 54 | assert_eq!(skip[b'c' as usize], 6); 55 | assert_eq!(skip[b'a' as usize], 1); 56 | assert_eq!(skip[b't' as usize], 8); 57 | } 58 | 59 | #[test] 60 | fn bmh_find() { 61 | let text = b"abc"; 62 | assert_eq!(find(text, b"d"), None); 63 | assert_eq!(find(text, b"c"), Some(2)); 64 | 65 | let longer = "longer text and so on"; 66 | 67 | // test all windows 68 | for wsz in 1..17 { 69 | for window in longer.as_bytes().windows(wsz) { 70 | let str_find = longer.find(::std::str::from_utf8(window).unwrap()); 71 | assert!(str_find.is_some()); 72 | assert_eq!(find(longer.as_bytes(), window), str_find); 73 | } 74 | } 75 | 76 | let pat = b"ger text and so on"; 77 | assert!(pat.len() > 16); 78 | assert_eq!(Some(3), find(longer.as_bytes(), pat)); 79 | } 80 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![cfg_attr(not(feature = "use_std"), no_std)] 2 | #![cfg_attr(feature = "pattern", feature(pattern))] 3 | 4 | //! **This crate is deprecated. Use crate `memchr` instead.** 5 | //! 6 | //! Fast substring search for strings and byte strings, using the [two-way algorithm][tw]. 7 | //! 8 | //! This is the same code as is included in Rust's libstd that powers 9 | //! `str::find(&str)`, but here it is exposed with some improvements: 10 | //! 11 | //! - Available for byte string searches using ``&[u8]`` 12 | //! - Having an optional SSE4.2 accelerated version (if detected at runtime) which is even faster. 13 | //! Runtime detection requires the default std feature. 14 | //! - Using `memchr` for the single byte case, which is ultra fast. 15 | //! 16 | //! [tw]: http://www-igm.univ-mlv.fr/~lecroq/string/node26.html 17 | 18 | #[cfg(not(feature = "use_std"))] 19 | extern crate core as std; 20 | 21 | use std::cmp; 22 | use std::usize; 23 | 24 | extern crate memchr; 25 | 26 | mod tw; 27 | #[cfg(all(feature="benchmarks", any(target_arch = "x86", target_arch = "x86_64")))] 28 | pub mod pcmp; 29 | #[cfg(all(not(feature="benchmarks"), any(target_arch = "x86", target_arch = "x86_64")))] 30 | mod pcmp; 31 | 32 | #[cfg(feature="benchmarks")] 33 | pub mod bmh; 34 | 35 | #[cfg(feature = "pattern")] 36 | use std::str::pattern::{ 37 | Pattern, 38 | Searcher, 39 | ReverseSearcher, 40 | SearchStep, 41 | }; 42 | 43 | /// `find_str` finds the first ocurrence of `pattern` in the `text`. 44 | /// 45 | /// Uses the SSE42 version if it is available at runtime. 46 | #[inline] 47 | pub fn find_str(text: &str, pattern: &str) -> Option { 48 | find_bytes(text.as_bytes(), pattern.as_bytes()) 49 | } 50 | 51 | /// `find_bytes` finds the first ocurrence of `pattern` in the `text`. 52 | /// 53 | /// Uses the SSE42 version if it is available at runtime. 54 | pub fn find_bytes(text: &[u8], pattern: &[u8]) -> Option { 55 | if pattern.is_empty() { 56 | Some(0) 57 | } else if text.len() < pattern.len() { 58 | return None; 59 | } else if pattern.len() == 1 { 60 | memchr::memchr(pattern[0], text) 61 | } else { 62 | #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] { 63 | let compile_time_disable = option_env!("TWOWAY_TEST_DISABLE_PCMP") 64 | .map(|s| !s.is_empty()) 65 | .unwrap_or(false); 66 | if !compile_time_disable && pcmp::is_supported() { 67 | return unsafe { pcmp::find_inner(text, pattern) }; 68 | } 69 | } 70 | let mut searcher = TwoWaySearcher::new(pattern, text.len()); 71 | let is_long = searcher.memory == usize::MAX; 72 | // write out `true` and `false` cases to encourage the compiler 73 | // to specialize the two cases separately. 74 | if is_long { 75 | searcher.next::(text, pattern, true).map(|t| t.0) 76 | } else { 77 | searcher.next::(text, pattern, false).map(|t| t.0) 78 | } 79 | } 80 | } 81 | 82 | /// `rfind_str` finds the last ocurrence of `pattern` in the `text` 83 | /// and returns the index of the start of the match. 84 | /// 85 | /// As of this writing, this function uses the two way algorithm 86 | /// in pure rust (with no SSE4.2 support). 87 | #[inline] 88 | pub fn rfind_str(text: &str, pattern: &str) -> Option { 89 | rfind_bytes(text.as_bytes(), pattern.as_bytes()) 90 | } 91 | 92 | /// `rfind_bytes` finds the last ocurrence of `pattern` in the `text`, 93 | /// and returns the index of the start of the match. 94 | /// 95 | /// As of this writing, this function uses the two way algorithm 96 | /// in pure rust (with no SSE4.2 support). 97 | pub fn rfind_bytes(text: &[u8], pattern: &[u8]) -> Option { 98 | if pattern.is_empty() { 99 | Some(text.len()) 100 | } else if pattern.len() == 1 { 101 | memchr::memrchr(pattern[0], text) 102 | } else { 103 | let mut searcher = TwoWaySearcher::new(pattern, text.len()); 104 | let is_long = searcher.memory == usize::MAX; 105 | // write out `true` and `false` cases to encourage the compiler 106 | // to specialize the two cases separately. 107 | if is_long { 108 | searcher.next_back::(text, pattern, true).map(|t| t.0) 109 | } else { 110 | searcher.next_back::(text, pattern, false).map(|t| t.0) 111 | } 112 | } 113 | } 114 | 115 | 116 | /// Dummy wrapper for &str 117 | #[doc(hidden)] 118 | pub struct Str<'a>(pub &'a str); 119 | 120 | #[cfg(feature = "pattern")] 121 | /// Non-allocating substring search. 122 | /// 123 | /// Will handle the pattern `""` as returning empty matches at each character 124 | /// boundary. 125 | impl<'a, 'b> Pattern<'a> for Str<'b> { 126 | type Searcher = StrSearcher<'a, 'b>; 127 | 128 | #[inline] 129 | fn into_searcher(self, haystack: &'a str) -> StrSearcher<'a, 'b> { 130 | StrSearcher::new(haystack, self.0) 131 | } 132 | 133 | /// Checks whether the pattern matches at the front of the haystack 134 | #[inline] 135 | fn is_prefix_of(self, haystack: &'a str) -> bool { 136 | let self_ = self.0; 137 | haystack.is_char_boundary(self_.len()) && 138 | self_ == &haystack[..self_.len()] 139 | } 140 | 141 | /// Checks whether the pattern matches at the back of the haystack 142 | #[inline] 143 | fn is_suffix_of(self, haystack: &'a str) -> bool { 144 | let self_ = self.0; 145 | self_.len() <= haystack.len() && 146 | haystack.is_char_boundary(haystack.len() - self_.len()) && 147 | self_ == &haystack[haystack.len() - self_.len()..] 148 | } 149 | 150 | } 151 | 152 | #[derive(Clone, Debug)] 153 | #[doc(hidden)] 154 | /// Associated type for `<&str as Pattern<'a>>::Searcher`. 155 | pub struct StrSearcher<'a, 'b> { 156 | haystack: &'a str, 157 | needle: &'b str, 158 | 159 | searcher: StrSearcherImpl, 160 | } 161 | 162 | #[derive(Clone, Debug)] 163 | enum StrSearcherImpl { 164 | Empty(EmptyNeedle), 165 | TwoWay(TwoWaySearcher), 166 | } 167 | 168 | #[derive(Clone, Debug)] 169 | struct EmptyNeedle { 170 | position: usize, 171 | end: usize, 172 | is_match_fw: bool, 173 | is_match_bw: bool, 174 | } 175 | 176 | impl<'a, 'b> StrSearcher<'a, 'b> { 177 | pub fn new(haystack: &'a str, needle: &'b str) -> StrSearcher<'a, 'b> { 178 | if needle.is_empty() { 179 | StrSearcher { 180 | haystack: haystack, 181 | needle: needle, 182 | searcher: StrSearcherImpl::Empty(EmptyNeedle { 183 | position: 0, 184 | end: haystack.len(), 185 | is_match_fw: true, 186 | is_match_bw: true, 187 | }), 188 | } 189 | } else { 190 | StrSearcher { 191 | haystack: haystack, 192 | needle: needle, 193 | searcher: StrSearcherImpl::TwoWay( 194 | TwoWaySearcher::new(needle.as_bytes(), haystack.len()) 195 | ), 196 | } 197 | } 198 | } 199 | } 200 | 201 | #[cfg(feature = "pattern")] 202 | unsafe impl<'a, 'b> Searcher<'a> for StrSearcher<'a, 'b> { 203 | fn haystack(&self) -> &'a str { self.haystack } 204 | 205 | #[inline] 206 | fn next(&mut self) -> SearchStep { 207 | match self.searcher { 208 | StrSearcherImpl::Empty(ref mut searcher) => { 209 | // empty needle rejects every char and matches every empty string between them 210 | let is_match = searcher.is_match_fw; 211 | searcher.is_match_fw = !searcher.is_match_fw; 212 | let pos = searcher.position; 213 | match self.haystack[pos..].chars().next() { 214 | _ if is_match => SearchStep::Match(pos, pos), 215 | None => SearchStep::Done, 216 | Some(ch) => { 217 | searcher.position += ch.len_utf8(); 218 | SearchStep::Reject(pos, searcher.position) 219 | } 220 | } 221 | } 222 | StrSearcherImpl::TwoWay(ref mut searcher) => { 223 | // TwoWaySearcher produces valid *Match* indices that split at char boundaries 224 | // as long as it does correct matching and that haystack and needle are 225 | // valid UTF-8 226 | // *Rejects* from the algorithm can fall on any indices, but we will walk them 227 | // manually to the next character boundary, so that they are utf-8 safe. 228 | if searcher.position == self.haystack.len() { 229 | return SearchStep::Done; 230 | } 231 | let is_long = searcher.memory == usize::MAX; 232 | match searcher.next::(self.haystack.as_bytes(), 233 | self.needle.as_bytes(), 234 | is_long) 235 | { 236 | SearchStep::Reject(a, mut b) => { 237 | // skip to next char boundary 238 | while !self.haystack.is_char_boundary(b) { 239 | b += 1; 240 | } 241 | searcher.position = cmp::max(b, searcher.position); 242 | SearchStep::Reject(a, b) 243 | } 244 | otherwise => otherwise, 245 | } 246 | } 247 | } 248 | } 249 | 250 | #[inline(always)] 251 | fn next_match(&mut self) -> Option<(usize, usize)> { 252 | match self.searcher { 253 | StrSearcherImpl::Empty(..) => { 254 | loop { 255 | match self.next() { 256 | SearchStep::Match(a, b) => return Some((a, b)), 257 | SearchStep::Done => return None, 258 | SearchStep::Reject(..) => { } 259 | } 260 | } 261 | } 262 | 263 | StrSearcherImpl::TwoWay(ref mut searcher) => { 264 | let is_long = searcher.memory == usize::MAX; 265 | // write out `true` and `false` cases to encourage the compiler 266 | // to specialize the two cases separately. 267 | if is_long { 268 | searcher.next::(self.haystack.as_bytes(), 269 | self.needle.as_bytes(), 270 | true) 271 | } else { 272 | searcher.next::(self.haystack.as_bytes(), 273 | self.needle.as_bytes(), 274 | false) 275 | } 276 | } 277 | } 278 | } 279 | } 280 | 281 | #[cfg(feature = "pattern")] 282 | unsafe impl<'a, 'b> ReverseSearcher<'a> for StrSearcher<'a, 'b> { 283 | #[inline] 284 | fn next_back(&mut self) -> SearchStep { 285 | match self.searcher { 286 | StrSearcherImpl::Empty(ref mut searcher) => { 287 | let is_match = searcher.is_match_bw; 288 | searcher.is_match_bw = !searcher.is_match_bw; 289 | let end = searcher.end; 290 | match self.haystack[..end].chars().next_back() { 291 | _ if is_match => SearchStep::Match(end, end), 292 | None => SearchStep::Done, 293 | Some(ch) => { 294 | searcher.end -= ch.len_utf8(); 295 | SearchStep::Reject(searcher.end, end) 296 | } 297 | } 298 | } 299 | StrSearcherImpl::TwoWay(ref mut searcher) => { 300 | if searcher.end == 0 { 301 | return SearchStep::Done; 302 | } 303 | let is_long = searcher.memory == usize::MAX; 304 | match searcher.next_back::(self.haystack.as_bytes(), 305 | self.needle.as_bytes(), 306 | is_long) 307 | { 308 | SearchStep::Reject(mut a, b) => { 309 | // skip to next char boundary 310 | while !self.haystack.is_char_boundary(a) { 311 | a -= 1; 312 | } 313 | searcher.end = cmp::min(a, searcher.end); 314 | SearchStep::Reject(a, b) 315 | } 316 | otherwise => otherwise, 317 | } 318 | } 319 | } 320 | } 321 | 322 | #[inline] 323 | fn next_match_back(&mut self) -> Option<(usize, usize)> { 324 | match self.searcher { 325 | StrSearcherImpl::Empty(..) => { 326 | loop { 327 | match self.next_back() { 328 | SearchStep::Match(a, b) => return Some((a, b)), 329 | SearchStep::Done => return None, 330 | SearchStep::Reject(..) => { } 331 | } 332 | } 333 | } 334 | StrSearcherImpl::TwoWay(ref mut searcher) => { 335 | let is_long = searcher.memory == usize::MAX; 336 | // write out `true` and `false`, like `next_match` 337 | if is_long { 338 | searcher.next_back::(self.haystack.as_bytes(), 339 | self.needle.as_bytes(), 340 | true) 341 | } else { 342 | searcher.next_back::(self.haystack.as_bytes(), 343 | self.needle.as_bytes(), 344 | false) 345 | } 346 | } 347 | } 348 | } 349 | } 350 | 351 | /// The internal state of the two-way substring search algorithm. 352 | #[derive(Clone, Debug)] 353 | #[doc(hidden)] 354 | pub struct TwoWaySearcher { 355 | // constants 356 | /// critical factorization index 357 | crit_pos: usize, 358 | /// critical factorization index for reversed needle 359 | crit_pos_back: usize, 360 | period: usize, 361 | /// `byteset` is an extension (not part of the two way algorithm); 362 | /// it's a 64-bit "fingerprint" where each set bit `j` corresponds 363 | /// to a (byte & 63) == j present in the needle. 364 | byteset: u64, 365 | 366 | // variables 367 | position: usize, 368 | end: usize, 369 | /// index into needle before which we have already matched 370 | memory: usize, 371 | /// index into needle after which we have already matched 372 | memory_back: usize, 373 | } 374 | 375 | /* 376 | This is the Two-Way search algorithm, which was introduced in the paper: 377 | Crochemore, M., Perrin, D., 1991, Two-way string-matching, Journal of the ACM 38(3):651-675. 378 | 379 | Here's some background information. 380 | 381 | A *word* is a string of symbols. The *length* of a word should be a familiar 382 | notion, and here we denote it for any word x by |x|. 383 | (We also allow for the possibility of the *empty word*, a word of length zero). 384 | 385 | If x is any non-empty word, then an integer p with 0 < p <= |x| is said to be a 386 | *period* for x iff for all i with 0 <= i <= |x| - p - 1, we have x[i] == x[i+p]. 387 | For example, both 1 and 2 are periods for the string "aa". As another example, 388 | the only period of the string "abcd" is 4. 389 | 390 | We denote by period(x) the *smallest* period of x (provided that x is non-empty). 391 | This is always well-defined since every non-empty word x has at least one period, 392 | |x|. We sometimes call this *the period* of x. 393 | 394 | If u, v and x are words such that x = uv, where uv is the concatenation of u and 395 | v, then we say that (u, v) is a *factorization* of x. 396 | 397 | Let (u, v) be a factorization for a word x. Then if w is a non-empty word such 398 | that both of the following hold 399 | 400 | - either w is a suffix of u or u is a suffix of w 401 | - either w is a prefix of v or v is a prefix of w 402 | 403 | then w is said to be a *repetition* for the factorization (u, v). 404 | 405 | Just to unpack this, there are four possibilities here. Let w = "abc". Then we 406 | might have: 407 | 408 | - w is a suffix of u and w is a prefix of v. ex: ("lolabc", "abcde") 409 | - w is a suffix of u and v is a prefix of w. ex: ("lolabc", "ab") 410 | - u is a suffix of w and w is a prefix of v. ex: ("bc", "abchi") 411 | - u is a suffix of w and v is a prefix of w. ex: ("bc", "a") 412 | 413 | Note that the word vu is a repetition for any factorization (u,v) of x = uv, 414 | so every factorization has at least one repetition. 415 | 416 | If x is a string and (u, v) is a factorization for x, then a *local period* for 417 | (u, v) is an integer r such that there is some word w such that |w| = r and w is 418 | a repetition for (u, v). 419 | 420 | We denote by local_period(u, v) the smallest local period of (u, v). We sometimes 421 | call this *the local period* of (u, v). Provided that x = uv is non-empty, this 422 | is well-defined (because each non-empty word has at least one factorization, as 423 | noted above). 424 | 425 | It can be proven that the following is an equivalent definition of a local period 426 | for a factorization (u, v): any positive integer r such that x[i] == x[i+r] for 427 | all i such that |u| - r <= i <= |u| - 1 and such that both x[i] and x[i+r] are 428 | defined. (i.e. i > 0 and i + r < |x|). 429 | 430 | Using the above reformulation, it is easy to prove that 431 | 432 | 1 <= local_period(u, v) <= period(uv) 433 | 434 | A factorization (u, v) of x such that local_period(u,v) = period(x) is called a 435 | *critical factorization*. 436 | 437 | The algorithm hinges on the following theorem, which is stated without proof: 438 | 439 | **Critical Factorization Theorem** Any word x has at least one critical 440 | factorization (u, v) such that |u| < period(x). 441 | 442 | The purpose of maximal_suffix is to find such a critical factorization. 443 | 444 | If the period is short, compute another factorization x = u' v' to use 445 | for reverse search, chosen instead so that |v'| < period(x). 446 | 447 | */ 448 | impl TwoWaySearcher { 449 | pub fn new(needle: &[u8], end: usize) -> TwoWaySearcher { 450 | let (crit_pos, period) = TwoWaySearcher::crit_params(needle); 451 | 452 | // A particularly readable explanation of what's going on here can be found 453 | // in Crochemore and Rytter's book "Text Algorithms", ch 13. Specifically 454 | // see the code for "Algorithm CP" on p. 323. 455 | // 456 | // What's going on is we have some critical factorization (u, v) of the 457 | // needle, and we want to determine whether u is a suffix of 458 | // &v[..period]. If it is, we use "Algorithm CP1". Otherwise we use 459 | // "Algorithm CP2", which is optimized for when the period of the needle 460 | // is large. 461 | if &needle[..crit_pos] == &needle[period.. period + crit_pos] { 462 | // short period case -- the period is exact 463 | // compute a separate critical factorization for the reversed needle 464 | // x = u' v' where |v'| < period(x). 465 | // 466 | // This is sped up by the period being known already. 467 | // Note that a case like x = "acba" may be factored exactly forwards 468 | // (crit_pos = 1, period = 3) while being factored with approximate 469 | // period in reverse (crit_pos = 2, period = 2). We use the given 470 | // reverse factorization but keep the exact period. 471 | let crit_pos_back = needle.len() - cmp::max( 472 | TwoWaySearcher::reverse_maximal_suffix(needle, period, false), 473 | TwoWaySearcher::reverse_maximal_suffix(needle, period, true)); 474 | 475 | TwoWaySearcher { 476 | crit_pos: crit_pos, 477 | crit_pos_back: crit_pos_back, 478 | period: period, 479 | byteset: Self::byteset_create(&needle[..period]), 480 | 481 | position: 0, 482 | end: end, 483 | memory: 0, 484 | memory_back: needle.len(), 485 | } 486 | } else { 487 | // long period case -- we have an approximation to the actual period, 488 | // and don't use memorization. 489 | // 490 | // Approximate the period by lower bound max(|u|, |v|) + 1. 491 | // The critical factorization is efficient to use for both forward and 492 | // reverse search. 493 | 494 | TwoWaySearcher { 495 | crit_pos: crit_pos, 496 | crit_pos_back: crit_pos, 497 | period: cmp::max(crit_pos, needle.len() - crit_pos) + 1, 498 | byteset: Self::byteset_create(needle), 499 | 500 | position: 0, 501 | end: end, 502 | memory: usize::MAX, // Dummy value to signify that the period is long 503 | memory_back: usize::MAX, 504 | } 505 | } 506 | } 507 | 508 | /// Return the zero-based critical position and period of the provided needle. 509 | /// 510 | /// The returned period is incorrect when the actual period is "long." In 511 | /// that case the approximation must be computed separately. 512 | #[inline(always)] 513 | fn crit_params(needle: &[u8]) -> (usize, usize) { 514 | let (crit_pos_false, period_false) = TwoWaySearcher::maximal_suffix(needle, false); 515 | let (crit_pos_true, period_true) = TwoWaySearcher::maximal_suffix(needle, true); 516 | 517 | if crit_pos_false > crit_pos_true { 518 | (crit_pos_false, period_false) 519 | } else { 520 | (crit_pos_true, period_true) 521 | } 522 | } 523 | 524 | #[inline] 525 | fn byteset_create(bytes: &[u8]) -> u64 { 526 | bytes.iter().fold(0, |a, &b| (1 << (b & 0x3f)) | a) 527 | } 528 | 529 | #[inline(always)] 530 | fn byteset_contains(&self, byte: u8) -> bool { 531 | (self.byteset >> ((byte & 0x3f) as usize)) & 1 != 0 532 | } 533 | 534 | // One of the main ideas of Two-Way is that we factorize the needle into 535 | // two halves, (u, v), and begin trying to find v in the haystack by scanning 536 | // left to right. If v matches, we try to match u by scanning right to left. 537 | // How far we can jump when we encounter a mismatch is all based on the fact 538 | // that (u, v) is a critical factorization for the needle. 539 | #[inline(always)] 540 | fn next(&mut self, haystack: &[u8], needle: &[u8], long_period: bool) 541 | -> S::Output 542 | where S: TwoWayStrategy 543 | { 544 | // `next()` uses `self.position` as its cursor 545 | let old_pos = self.position; 546 | let needle_last = needle.len() - 1; 547 | 'search: loop { 548 | // Check that we have room to search in 549 | // position + needle_last can not overflow if we assume slices 550 | // are bounded by isize's range. 551 | let tail_byte = match haystack.get(self.position + needle_last) { 552 | Some(&b) => b, 553 | None => { 554 | self.position = haystack.len(); 555 | return S::rejecting(old_pos, self.position); 556 | } 557 | }; 558 | 559 | if S::use_early_reject() && old_pos != self.position { 560 | return S::rejecting(old_pos, self.position); 561 | } 562 | 563 | // Quickly skip by large portions unrelated to our substring 564 | if !self.byteset_contains(tail_byte) { 565 | self.position += needle.len(); 566 | if !long_period { 567 | self.memory = 0; 568 | } 569 | continue 'search; 570 | } 571 | 572 | // See if the right part of the needle matches 573 | let start = if long_period { self.crit_pos } 574 | else { cmp::max(self.crit_pos, self.memory) }; 575 | for i in start..needle.len() { 576 | if needle[i] != haystack[self.position + i] { 577 | self.position += i - self.crit_pos + 1; 578 | if !long_period { 579 | self.memory = 0; 580 | } 581 | continue 'search; 582 | } 583 | } 584 | 585 | // See if the left part of the needle matches 586 | let start = if long_period { 0 } else { self.memory }; 587 | for i in (start..self.crit_pos).rev() { 588 | if needle[i] != haystack[self.position + i] { 589 | self.position += self.period; 590 | if !long_period { 591 | self.memory = needle.len() - self.period; 592 | } 593 | continue 'search; 594 | } 595 | } 596 | 597 | // We have found a match! 598 | let match_pos = self.position; 599 | 600 | // Note: add self.period instead of needle.len() to have overlapping matches 601 | self.position += needle.len(); 602 | if !long_period { 603 | self.memory = 0; // set to needle.len() - self.period for overlapping matches 604 | } 605 | 606 | return S::matching(match_pos, match_pos + needle.len()); 607 | } 608 | } 609 | 610 | // Follows the ideas in `next()`. 611 | // 612 | // The definitions are symmetrical, with period(x) = period(reverse(x)) 613 | // and local_period(u, v) = local_period(reverse(v), reverse(u)), so if (u, v) 614 | // is a critical factorization, so is (reverse(v), reverse(u)). 615 | // 616 | // For the reverse case we have computed a critical factorization x = u' v' 617 | // (field `crit_pos_back`). We need |u| < period(x) for the forward case and 618 | // thus |v'| < period(x) for the reverse. 619 | // 620 | // To search in reverse through the haystack, we search forward through 621 | // a reversed haystack with a reversed needle, matching first u' and then v'. 622 | #[inline] 623 | fn next_back(&mut self, haystack: &[u8], needle: &[u8], long_period: bool) 624 | -> S::Output 625 | where S: TwoWayStrategy 626 | { 627 | // `next_back()` uses `self.end` as its cursor -- so that `next()` and `next_back()` 628 | // are independent. 629 | let old_end = self.end; 630 | 'search: loop { 631 | // Check that we have room to search in 632 | // end - needle.len() will wrap around when there is no more room, 633 | // but due to slice length limits it can never wrap all the way back 634 | // into the length of haystack. 635 | let front_byte = match haystack.get(self.end.wrapping_sub(needle.len())) { 636 | Some(&b) => b, 637 | None => { 638 | self.end = 0; 639 | return S::rejecting(0, old_end); 640 | } 641 | }; 642 | 643 | if S::use_early_reject() && old_end != self.end { 644 | return S::rejecting(self.end, old_end); 645 | } 646 | 647 | // Quickly skip by large portions unrelated to our substring 648 | if !self.byteset_contains(front_byte) { 649 | self.end -= needle.len(); 650 | if !long_period { 651 | self.memory_back = needle.len(); 652 | } 653 | continue 'search; 654 | } 655 | 656 | // See if the left part of the needle matches 657 | let crit = if long_period { self.crit_pos_back } 658 | else { cmp::min(self.crit_pos_back, self.memory_back) }; 659 | for i in (0..crit).rev() { 660 | if needle[i] != haystack[self.end - needle.len() + i] { 661 | self.end -= self.crit_pos_back - i; 662 | if !long_period { 663 | self.memory_back = needle.len(); 664 | } 665 | continue 'search; 666 | } 667 | } 668 | 669 | // See if the right part of the needle matches 670 | let needle_end = if long_period { needle.len() } 671 | else { self.memory_back }; 672 | for i in self.crit_pos_back..needle_end { 673 | if needle[i] != haystack[self.end - needle.len() + i] { 674 | self.end -= self.period; 675 | if !long_period { 676 | self.memory_back = self.period; 677 | } 678 | continue 'search; 679 | } 680 | } 681 | 682 | // We have found a match! 683 | let match_pos = self.end - needle.len(); 684 | // Note: sub self.period instead of needle.len() to have overlapping matches 685 | self.end -= needle.len(); 686 | if !long_period { 687 | self.memory_back = needle.len(); 688 | } 689 | 690 | return S::matching(match_pos, match_pos + needle.len()); 691 | } 692 | } 693 | 694 | // Compute the maximal suffix of `arr`. 695 | // 696 | // The maximal suffix is a possible critical factorization (u, v) of `arr`. 697 | // 698 | // Returns (`i`, `p`) where `i` is the starting index of v and `p` is the 699 | // period of v. 700 | // 701 | // `order_greater` determines if lexical order is `<` or `>`. Both 702 | // orders must be computed -- the ordering with the largest `i` gives 703 | // a critical factorization. 704 | // 705 | // For long period cases, the resulting period is not exact (it is too short). 706 | #[inline] 707 | pub fn maximal_suffix(arr: &[u8], order_greater: bool) -> (usize, usize) { 708 | let mut left = 0; // Corresponds to i in the paper 709 | let mut right = 1; // Corresponds to j in the paper 710 | let mut offset = 0; // Corresponds to k in the paper, but starting at 0 711 | // to match 0-based indexing. 712 | let mut period = 1; // Corresponds to p in the paper 713 | 714 | while let Some(&a) = arr.get(right + offset) { 715 | // `left` will be inbounds when `right` is. 716 | let b = arr[left + offset]; 717 | if (a < b && !order_greater) || (a > b && order_greater) { 718 | // Suffix is smaller, period is entire prefix so far. 719 | right += offset + 1; 720 | offset = 0; 721 | period = right - left; 722 | } else if a == b { 723 | // Advance through repetition of the current period. 724 | if offset + 1 == period { 725 | right += offset + 1; 726 | offset = 0; 727 | } else { 728 | offset += 1; 729 | } 730 | } else { 731 | // Suffix is larger, start over from current location. 732 | left = right; 733 | right += 1; 734 | offset = 0; 735 | period = 1; 736 | } 737 | } 738 | (left, period) 739 | } 740 | 741 | // Compute the maximal suffix of the reverse of `arr`. 742 | // 743 | // The maximal suffix is a possible critical factorization (u', v') of `arr`. 744 | // 745 | // Returns `i` where `i` is the starting index of v', from the back; 746 | // returns immedately when a period of `known_period` is reached. 747 | // 748 | // `order_greater` determines if lexical order is `<` or `>`. Both 749 | // orders must be computed -- the ordering with the largest `i` gives 750 | // a critical factorization. 751 | // 752 | // For long period cases, the resulting period is not exact (it is too short). 753 | pub fn reverse_maximal_suffix(arr: &[u8], known_period: usize, 754 | order_greater: bool) -> usize 755 | { 756 | let mut left = 0; // Corresponds to i in the paper 757 | let mut right = 1; // Corresponds to j in the paper 758 | let mut offset = 0; // Corresponds to k in the paper, but starting at 0 759 | // to match 0-based indexing. 760 | let mut period = 1; // Corresponds to p in the paper 761 | let n = arr.len(); 762 | 763 | while right + offset < n { 764 | let a = arr[n - (1 + right + offset)]; 765 | let b = arr[n - (1 + left + offset)]; 766 | if (a < b && !order_greater) || (a > b && order_greater) { 767 | // Suffix is smaller, period is entire prefix so far. 768 | right += offset + 1; 769 | offset = 0; 770 | period = right - left; 771 | } else if a == b { 772 | // Advance through repetition of the current period. 773 | if offset + 1 == period { 774 | right += offset + 1; 775 | offset = 0; 776 | } else { 777 | offset += 1; 778 | } 779 | } else { 780 | // Suffix is larger, start over from current location. 781 | left = right; 782 | right += 1; 783 | offset = 0; 784 | period = 1; 785 | } 786 | if period == known_period { 787 | break; 788 | } 789 | } 790 | debug_assert!(period <= known_period); 791 | left 792 | } 793 | } 794 | 795 | // TwoWayStrategy allows the algorithm to either skip non-matches as quickly 796 | // as possible, or to work in a mode where it emits Rejects relatively quickly. 797 | trait TwoWayStrategy { 798 | type Output; 799 | fn use_early_reject() -> bool; 800 | fn rejecting(usize, usize) -> Self::Output; 801 | fn matching(usize, usize) -> Self::Output; 802 | } 803 | 804 | /// Skip to match intervals as quickly as possible 805 | enum MatchOnly { } 806 | 807 | impl TwoWayStrategy for MatchOnly { 808 | type Output = Option<(usize, usize)>; 809 | 810 | #[inline] 811 | fn use_early_reject() -> bool { false } 812 | #[inline] 813 | fn rejecting(_a: usize, _b: usize) -> Self::Output { None } 814 | #[inline] 815 | fn matching(a: usize, b: usize) -> Self::Output { Some((a, b)) } 816 | } 817 | 818 | #[cfg(feature = "pattern")] 819 | /// Emit Rejects regularly 820 | enum RejectAndMatch { } 821 | 822 | #[cfg(feature = "pattern")] 823 | impl TwoWayStrategy for RejectAndMatch { 824 | type Output = SearchStep; 825 | 826 | #[inline] 827 | fn use_early_reject() -> bool { true } 828 | #[inline] 829 | fn rejecting(a: usize, b: usize) -> Self::Output { SearchStep::Reject(a, b) } 830 | #[inline] 831 | fn matching(a: usize, b: usize) -> Self::Output { SearchStep::Match(a, b) } 832 | } 833 | 834 | 835 | #[cfg(feature = "pattern")] 836 | #[cfg(test)] 837 | impl<'a, 'b> StrSearcher<'a, 'b> { 838 | fn twoway(&self) -> &TwoWaySearcher { 839 | match self.searcher { 840 | StrSearcherImpl::TwoWay(ref inner) => inner, 841 | _ => panic!("Not a TwoWaySearcher"), 842 | } 843 | } 844 | } 845 | 846 | #[cfg(feature = "pattern")] 847 | #[test] 848 | fn test_basic() { 849 | let t = StrSearcher::new("", "aab"); 850 | println!("{:?}", t); 851 | let t = StrSearcher::new("", "abaaaba"); 852 | println!("{:?}", t); 853 | let mut t = StrSearcher::new("GCATCGCAGAGAGTATACAGTACG", "GCAGAGAG"); 854 | println!("{:?}", t); 855 | 856 | loop { 857 | match t.next() { 858 | SearchStep::Done => break, 859 | m => println!("{:?}", m), 860 | } 861 | } 862 | 863 | let mut t = StrSearcher::new("GCATCGCAGAGAGTATACAGTACG", "GCAGAGAG"); 864 | println!("{:?}", t); 865 | 866 | loop { 867 | match t.next_back() { 868 | SearchStep::Done => break, 869 | m => println!("{:?}", m), 870 | } 871 | } 872 | 873 | let mut t = StrSearcher::new("banana", "nana"); 874 | println!("{:?}", t); 875 | 876 | loop { 877 | match t.next() { 878 | SearchStep::Done => break, 879 | m => println!("{:?}", m), 880 | } 881 | } 882 | } 883 | 884 | #[cfg(feature = "pattern")] 885 | #[cfg(test)] 886 | fn contains(hay: &str, n: &str) -> bool { 887 | let mut tws = StrSearcher::new(hay, n); 888 | loop { 889 | match tws.next() { 890 | SearchStep::Done => return false, 891 | SearchStep::Match(..) => return true, 892 | _ => { } 893 | } 894 | } 895 | } 896 | 897 | #[cfg(feature = "pattern")] 898 | #[cfg(test)] 899 | fn contains_rev(hay: &str, n: &str) -> bool { 900 | let mut tws = StrSearcher::new(hay, n); 901 | loop { 902 | match tws.next_back() { 903 | SearchStep::Done => return false, 904 | SearchStep::Match(..) => return true, 905 | rej => { println!("{:?}", rej); } 906 | } 907 | } 908 | } 909 | 910 | 911 | #[cfg(feature = "pattern")] 912 | #[test] 913 | fn test_contains() { 914 | let h = ""; 915 | let n = ""; 916 | assert!(contains(h, n)); 917 | assert!(contains_rev(h, n)); 918 | 919 | let h = "BDC\0\0\0"; 920 | let n = "BDC\u{0}"; 921 | assert!(contains(h, n)); 922 | assert!(contains_rev(h, n)); 923 | 924 | 925 | let h = "ADA\0"; 926 | let n = "ADA"; 927 | assert!(contains(h, n)); 928 | assert!(contains_rev(h, n)); 929 | 930 | let h = "\u{0}\u{0}\u{0}\u{0}"; 931 | let n = "\u{0}"; 932 | assert!(contains(h, n)); 933 | assert!(contains_rev(h, n)); 934 | } 935 | 936 | #[cfg(feature = "pattern")] 937 | #[test] 938 | fn test_rev_2() { 939 | let h = "BDC\0\0\0"; 940 | let n = "BDC\u{0}"; 941 | let mut t = StrSearcher::new(h, n); 942 | println!("{:?}", t); 943 | println!("{:?}", h.contains(&n)); 944 | 945 | loop { 946 | match t.next_back() { 947 | SearchStep::Done => break, 948 | m => println!("{:?}", m), 949 | } 950 | } 951 | 952 | let h = "aabaabx"; 953 | let n = "aabaab"; 954 | let mut t = StrSearcher::new(h, n); 955 | println!("{:?}", t); 956 | assert_eq!(t.twoway().crit_pos, 2); 957 | assert_eq!(t.twoway().crit_pos_back, 5); 958 | 959 | loop { 960 | match t.next_back() { 961 | SearchStep::Done => break, 962 | m => println!("{:?}", m), 963 | } 964 | } 965 | 966 | let h = "abababac"; 967 | let n = "ababab"; 968 | let mut t = StrSearcher::new(h, n); 969 | println!("{:?}", t); 970 | assert_eq!(t.twoway().crit_pos, 1); 971 | assert_eq!(t.twoway().crit_pos_back, 5); 972 | 973 | loop { 974 | match t.next_back() { 975 | SearchStep::Done => break, 976 | m => println!("{:?}", m), 977 | } 978 | } 979 | 980 | let h = "abababac"; 981 | let n = "abab"; 982 | let mut t = StrSearcher::new(h, n); 983 | println!("{:?}", t); 984 | 985 | loop { 986 | match t.next_back() { 987 | SearchStep::Done => break, 988 | m => println!("{:?}", m), 989 | } 990 | } 991 | 992 | let h = "baabbbaabc"; 993 | let n = "baabb"; 994 | let t = StrSearcher::new(h, n); 995 | println!("{:?}", t); 996 | assert_eq!(t.twoway().crit_pos, 3); 997 | assert_eq!(t.twoway().crit_pos_back, 3); 998 | 999 | let h = "aabaaaabaabxx"; 1000 | let n = "aabaaaabaa"; 1001 | let mut t = StrSearcher::new(h, n); 1002 | println!("{:?}", t); 1003 | 1004 | loop { 1005 | match t.next_back() { 1006 | SearchStep::Done => break, 1007 | m => println!("{:?}", m), 1008 | } 1009 | } 1010 | 1011 | let h = "babbabax"; 1012 | let n = "babbab"; 1013 | let mut t = StrSearcher::new(h, n); 1014 | println!("{:?}", t); 1015 | assert_eq!(t.twoway().crit_pos, 2); 1016 | assert_eq!(t.twoway().crit_pos_back, 4); 1017 | 1018 | loop { 1019 | match t.next_back() { 1020 | SearchStep::Done => break, 1021 | m => println!("{:?}", m), 1022 | } 1023 | } 1024 | 1025 | let h = "xacbaabcax"; 1026 | let n = "abca"; 1027 | let mut t = StrSearcher::new(h, n); 1028 | assert_eq!(t.next_match_back(), Some((5, 9))); 1029 | 1030 | let h = "xacbaacbxxcba"; 1031 | let m = "acba"; 1032 | let mut s = StrSearcher::new(h, m); 1033 | assert_eq!(s.next_match_back(), Some((1, 5))); 1034 | assert_eq!(s.twoway().crit_pos, 1); 1035 | assert_eq!(s.twoway().crit_pos_back, 2); 1036 | } 1037 | 1038 | #[cfg(feature = "pattern")] 1039 | #[test] 1040 | fn test_rev_unicode() { 1041 | let h = "ααααααβ"; 1042 | let n = "αβ"; 1043 | let mut t = StrSearcher::new(h, n); 1044 | println!("{:?}", t); 1045 | 1046 | loop { 1047 | match t.next() { 1048 | SearchStep::Done => break, 1049 | m => println!("{:?}", m), 1050 | } 1051 | } 1052 | 1053 | let mut t = StrSearcher::new(h, n); 1054 | loop { 1055 | match t.next_back() { 1056 | SearchStep::Done => break, 1057 | m => println!("{:?}", m), 1058 | } 1059 | } 1060 | } 1061 | 1062 | #[test] 1063 | fn maximal_suffix() { 1064 | assert_eq!((2, 1), TwoWaySearcher::maximal_suffix(b"aab", false)); 1065 | assert_eq!((0, 3), TwoWaySearcher::maximal_suffix(b"aab", true)); 1066 | 1067 | assert_eq!((0, 3), TwoWaySearcher::maximal_suffix(b"aabaa", true)); 1068 | assert_eq!((2, 3), TwoWaySearcher::maximal_suffix(b"aabaa", false)); 1069 | 1070 | assert_eq!((0, 7), TwoWaySearcher::maximal_suffix(b"gcagagag", false)); 1071 | assert_eq!((2, 2), TwoWaySearcher::maximal_suffix(b"gcagagag", true)); 1072 | 1073 | // both of these factorizations are critial factorizations 1074 | assert_eq!((2, 2), TwoWaySearcher::maximal_suffix(b"banana", false)); 1075 | assert_eq!((1, 2), TwoWaySearcher::maximal_suffix(b"banana", true)); 1076 | assert_eq!((0, 6), TwoWaySearcher::maximal_suffix(b"zanana", false)); 1077 | assert_eq!((1, 2), TwoWaySearcher::maximal_suffix(b"zanana", true)); 1078 | } 1079 | 1080 | #[test] 1081 | fn maximal_suffix_verbose() { 1082 | fn maximal_suffix(arr: &[u8], order_greater: bool) -> (usize, usize) { 1083 | let mut left: usize = 0; // Corresponds to i in the paper 1084 | let mut right = 1; // Corresponds to j in the paper 1085 | let mut offset = 0; // Corresponds to k in the paper 1086 | let mut period = 1; // Corresponds to p in the paper 1087 | 1088 | macro_rules! asstr { 1089 | ($e:expr) => (::std::str::from_utf8($e).unwrap()) 1090 | } 1091 | 1092 | while let Some(&a) = arr.get(right + offset) { 1093 | // `left` will be inbounds when `right` is. 1094 | debug_assert!(left <= right); 1095 | let b = unsafe { *arr.get_unchecked(left + offset) }; 1096 | println!("str={}, l={}, r={}, offset={}, p={}", asstr!(arr), left, right, offset, period); 1097 | if (a < b && !order_greater) || (a > b && order_greater) { 1098 | // Suffix is smaller, period is entire prefix so far. 1099 | right += offset + 1; 1100 | offset = 0; 1101 | period = right - left; 1102 | } else if a == b { 1103 | // Advance through repetition of the current period. 1104 | if offset + 1 == period { 1105 | right += offset + 1; 1106 | offset = 0; 1107 | } else { 1108 | offset += 1; 1109 | } 1110 | } else { 1111 | // Suffix is larger, start over from current location. 1112 | left = right; 1113 | right += 1; 1114 | offset = 0; 1115 | period = 1; 1116 | } 1117 | } 1118 | println!("str={}, l={}, r={}, offset={}, p={} ==END==", asstr!(arr), left, right, offset, period); 1119 | (left, period) 1120 | } 1121 | 1122 | fn reverse_maximal_suffix(arr: &[u8], known_period: usize, order_greater: bool) -> usize { 1123 | let n = arr.len(); 1124 | let mut left: usize = 0; // Corresponds to i in the paper 1125 | let mut right = 1; // Corresponds to j in the paper 1126 | let mut offset = 0; // Corresponds to k in the paper 1127 | let mut period = 1; // Corresponds to p in the paper 1128 | 1129 | macro_rules! asstr { 1130 | ($e:expr) => (::std::str::from_utf8($e).unwrap()) 1131 | } 1132 | 1133 | while right + offset < n { 1134 | // `left` will be inbounds when `right` is. 1135 | debug_assert!(left <= right); 1136 | let a = unsafe { *arr.get_unchecked(n - (1 + right + offset)) }; 1137 | let b = unsafe { *arr.get_unchecked(n - (1 + left + offset)) }; 1138 | println!("str={}, l={}, r={}, offset={}, p={}", asstr!(arr), left, right, offset, period); 1139 | if (a < b && !order_greater) || (a > b && order_greater) { 1140 | // Suffix is smaller, period is entire prefix so far. 1141 | right += offset + 1; 1142 | offset = 0; 1143 | period = right - left; 1144 | if period == known_period { 1145 | break; 1146 | } 1147 | } else if a == b { 1148 | // Advance through repetition of the current period. 1149 | if offset + 1 == period { 1150 | right += offset + 1; 1151 | offset = 0; 1152 | } else { 1153 | offset += 1; 1154 | } 1155 | } else { 1156 | // Suffix is larger, start over from current location. 1157 | left = right; 1158 | right += 1; 1159 | offset = 0; 1160 | period = 1; 1161 | } 1162 | } 1163 | println!("str={}, l={}, r={}, offset={}, p={} ==END==", asstr!(arr), left, right, offset, period); 1164 | debug_assert!(period == known_period); 1165 | left 1166 | } 1167 | 1168 | assert_eq!((2, 2), maximal_suffix(b"banana", false)); 1169 | assert_eq!((1, 2), maximal_suffix(b"banana", true)); 1170 | assert_eq!((0, 7), maximal_suffix(b"gcagagag", false)); 1171 | assert_eq!((2, 2), maximal_suffix(b"gcagagag", true)); 1172 | assert_eq!((2, 1), maximal_suffix(b"bac", false)); 1173 | assert_eq!((1, 2), maximal_suffix(b"bac", true)); 1174 | assert_eq!((0, 9), maximal_suffix(b"baaaaaaaa", false)); 1175 | assert_eq!((1, 1), maximal_suffix(b"baaaaaaaa", true)); 1176 | 1177 | assert_eq!((2, 3), maximal_suffix(b"babbabbab", false)); 1178 | assert_eq!((1, 3), maximal_suffix(b"babbabbab", true)); 1179 | 1180 | assert_eq!(2, reverse_maximal_suffix(b"babbabbab", 3, false)); 1181 | assert_eq!(1, reverse_maximal_suffix(b"babbabbab", 3, true)); 1182 | 1183 | assert_eq!((0, 2), maximal_suffix(b"bababa", false)); 1184 | assert_eq!((1, 2), maximal_suffix(b"bababa", true)); 1185 | 1186 | assert_eq!(1, reverse_maximal_suffix(b"bababa", 2, false)); 1187 | assert_eq!(0, reverse_maximal_suffix(b"bababa", 2, true)); 1188 | 1189 | // NOTE: returns "long period" case per = 2, which is an approximation 1190 | assert_eq!((2, 2), maximal_suffix(b"abca", false)); 1191 | assert_eq!((0, 3), maximal_suffix(b"abca", true)); 1192 | 1193 | assert_eq!((3, 2), maximal_suffix(b"abcda", false)); 1194 | assert_eq!((0, 4), maximal_suffix(b"abcda", true)); 1195 | 1196 | // "aöa" 1197 | assert_eq!((1, 3), maximal_suffix(b"acba", false)); 1198 | assert_eq!((0, 3), maximal_suffix(b"acba", true)); 1199 | //assert_eq!(2, reverse_maximal_suffix(b"acba", 3, false)); 1200 | //assert_eq!(0, reverse_maximal_suffix(b"acba", 3, true)); 1201 | } 1202 | 1203 | #[cfg(feature = "pattern")] 1204 | #[test] 1205 | fn test_find_rfind() { 1206 | fn find(hay: &str, pat: &str) -> Option { 1207 | let mut t = pat.into_searcher(hay); 1208 | t.next_match().map(|(x, _)| x) 1209 | } 1210 | 1211 | fn rfind(hay: &str, pat: &str) -> Option { 1212 | let mut t = pat.into_searcher(hay); 1213 | t.next_match_back().map(|(x, _)| x) 1214 | } 1215 | 1216 | // find every substring -- assert that it finds it, or an earlier occurence. 1217 | let string = "Việt Namacbaabcaabaaba"; 1218 | for (i, ci) in string.char_indices() { 1219 | let ip = i + ci.len_utf8(); 1220 | for j in string[ip..].char_indices() 1221 | .map(|(i, _)| i) 1222 | .chain(Some(string.len() - ip)) 1223 | { 1224 | let pat = &string[i..ip + j]; 1225 | assert!(match find(string, pat) { 1226 | None => false, 1227 | Some(x) => x <= i, 1228 | }); 1229 | assert!(match rfind(string, pat) { 1230 | None => false, 1231 | Some(x) => x >= i, 1232 | }); 1233 | } 1234 | } 1235 | } 1236 | -------------------------------------------------------------------------------- /src/pcmp.rs: -------------------------------------------------------------------------------- 1 | //! SSE4.2 (pcmpestri) accelerated substring search 2 | //! 3 | //! Using the two way substring search algorithm. 4 | // wssm word size string matching
5 | // wslm word size lexicographical maximum suffix 6 | // 7 | 8 | #![allow(dead_code)] 9 | 10 | extern crate unchecked_index; 11 | extern crate memchr; 12 | 13 | use std::cmp; 14 | use std::mem; 15 | use std::iter::Zip; 16 | 17 | use self::unchecked_index::get_unchecked; 18 | 19 | use TwoWaySearcher; 20 | 21 | fn zip(i: I, j: J) -> Zip 22 | where I: IntoIterator, 23 | J: IntoIterator 24 | { 25 | i.into_iter().zip(j) 26 | } 27 | 28 | #[cfg(target_arch = "x86")] 29 | use std::arch::x86::*; 30 | 31 | #[cfg(target_arch = "x86_64")] 32 | use std::arch::x86_64::*; 33 | 34 | /// `pcmpestri` 35 | /// 36 | /// “Packed compare explicit length strings (return index)” 37 | /// 38 | /// PCMPESTRI xmm1, xmm2/m128, imm8 39 | /// 40 | /// Return value: least index for start of (partial) match, (16 if no match). 41 | /// 42 | /// Mask: `text` can be at at any point in valid memory, as long as `text_len` 43 | /// bytes are readable. 44 | #[target_feature(enable = "sse4.2")] 45 | unsafe fn pcmpestri_16_mask(text: *const u8, offset: usize, text_len: usize, 46 | needle: __m128i, needle_len: usize) -> u32 { 47 | //debug_assert!(text_len + offset <= text.len()); // saturates at 16 48 | //debug_assert!(needle_len <= 16); // saturates at 16 49 | let text = mask_load(text.offset(offset as _) as *const _, text_len); 50 | _mm_cmpestri(needle, needle_len as _, text, text_len as _, _SIDD_CMP_EQUAL_ORDERED) as _ 51 | } 52 | 53 | /// `pcmpestri` 54 | /// 55 | /// “Packed compare explicit length strings (return index)” 56 | /// 57 | /// PCMPESTRI xmm1, xmm2/m128, imm8 58 | /// 59 | /// Return value: least index for start of (partial) match, (16 if no match). 60 | /// 61 | /// No mask: `text` must be at least 16 bytes from the end of a memory region. 62 | #[target_feature(enable = "sse4.2")] 63 | unsafe fn pcmpestri_16_nomask(text: *const u8, offset: usize, text_len: usize, 64 | needle: __m128i, needle_len: usize) -> u32 { 65 | //debug_assert!(text_len + offset <= text.len()); // saturates at 16 66 | //debug_assert!(needle_len <= 16); // saturates at 16 67 | let text = _mm_loadu_si128(text.offset(offset as _) as *const _); 68 | _mm_cmpestri(needle, needle_len as _, text, text_len as _, _SIDD_CMP_EQUAL_ORDERED) as _ 69 | } 70 | 71 | /// `pcmpestrm` 72 | /// 73 | /// “Packed compare explicit length strings (return mask)” 74 | /// 75 | /// PCMPESTRM xmm1, xmm2/m128, imm8 76 | /// 77 | /// Return value: bitmask in the 16 lsb of the return value. 78 | #[target_feature(enable = "sse4.2")] 79 | unsafe fn pcmpestrm_eq_each(text: *const u8, offset: usize, text_len: usize, 80 | needle: *const u8, noffset: usize, needle_len: usize) -> u64 { 81 | // NOTE: text *must* be readable for 16 bytes 82 | // NOTE: needle *must* be readable for 16 bytes 83 | //debug_assert!(text_len + offset <= text.len()); // saturates at 16 84 | //debug_assert!(needle_len <= 16); // saturates at 16 85 | let needle = _mm_loadu_si128(needle.offset(noffset as _) as *const _); 86 | let text = _mm_loadu_si128(text.offset(offset as _) as *const _); 87 | let mask = _mm_cmpestrm(needle, needle_len as _, text, text_len as _, _SIDD_CMP_EQUAL_EACH); 88 | 89 | #[cfg(target_arch = "x86")] { 90 | _mm_extract_epi32(mask, 0) as u64 | (_mm_extract_epi32(mask, 1) as (u64) << 32) 91 | } 92 | 93 | #[cfg(target_arch = "x86_64")] { 94 | _mm_extract_epi64(mask, 0) as _ 95 | } 96 | } 97 | 98 | 99 | /// Search for first possible match of `pat` -- might be just a byte 100 | /// Return `(pos, length)` length of match 101 | #[cfg(test)] 102 | fn first_start_of_match(text: &[u8], pat: &[u8]) -> Option<(usize, usize)> { 103 | // not safe for text that is non aligned and ends at page boundary 104 | let patl = pat.len(); 105 | assert!(patl <= 16); 106 | unsafe { first_start_of_match_mask(text, pat.len(), pat128(pat)) } 107 | } 108 | 109 | /// Safe wrapper around pcmpestri to find first match of `p` in `text`. 110 | /// safe to search unaligned for first start of match 111 | /// 112 | /// the end of text an be close (within 16 bytes) of a page boundary 113 | #[target_feature(enable = "sse4.2")] 114 | unsafe fn first_start_of_match_mask(text: &[u8], pat_len: usize, p: __m128i) -> Option<(usize, usize)> { 115 | let tp = text.as_ptr(); 116 | debug_assert!(pat_len <= 16); 117 | 118 | let mut offset = 0; 119 | 120 | while text.len() >= offset + pat_len { 121 | let tlen = text.len() - offset; 122 | let ret = pcmpestri_16_mask(tp, offset, tlen, p, pat_len) as usize; 123 | if ret == 16 { 124 | offset += 16; 125 | } else { 126 | let match_len = cmp::min(pat_len, 16 - ret); 127 | return Some((offset + ret, match_len)); 128 | } 129 | } 130 | 131 | None 132 | } 133 | 134 | 135 | /// Safe wrapper around pcmpestri to find first match of `p` in `text`. 136 | /// safe to search unaligned for first start of match 137 | /// 138 | /// unsafe because the end of text must not be close (within 16 bytes) of a page boundary 139 | #[target_feature(enable = "sse4.2")] 140 | unsafe fn first_start_of_match_nomask(text: &[u8], pat_len: usize, p: __m128i) -> Option<(usize, usize)> { 141 | let tp = text.as_ptr(); 142 | debug_assert!(pat_len <= 16); 143 | debug_assert!(pat_len <= text.len()); 144 | 145 | let mut offset = 0; 146 | 147 | while text.len() - pat_len >= offset { 148 | let tlen = text.len() - offset; 149 | let ret = pcmpestri_16_nomask(tp, offset, tlen, p, pat_len) as usize; 150 | if ret == 16 { 151 | offset += 16; 152 | } else { 153 | let match_len = cmp::min(pat_len, 16 - ret); 154 | return Some((offset + ret, match_len)); 155 | } 156 | } 157 | 158 | None 159 | } 160 | 161 | #[test] 162 | fn test_first_start_of_match() { 163 | let text = b"abc"; 164 | let longer = "longer text and so on"; 165 | assert_eq!(first_start_of_match(text, b"d"), None); 166 | assert_eq!(first_start_of_match(text, b"c"), Some((2, 1))); 167 | assert_eq!(first_start_of_match(text, b"abc"), Some((0, 3))); 168 | assert_eq!(first_start_of_match(text, b"T"), None); 169 | assert_eq!(first_start_of_match(text, b"\0text"), None); 170 | assert_eq!(first_start_of_match(text, b"\0"), None); 171 | 172 | // test all windows 173 | for wsz in 1..17 { 174 | for window in longer.as_bytes().windows(wsz) { 175 | let str_find = longer.find(::std::str::from_utf8(window).unwrap()); 176 | assert!(str_find.is_some()); 177 | let first_start = first_start_of_match(longer.as_bytes(), window); 178 | assert!(first_start.is_some()); 179 | let (pos, len) = first_start.unwrap(); 180 | assert!(len <= wsz); 181 | assert!(len == wsz && Some(pos) == str_find 182 | || pos <= str_find.unwrap()); 183 | } 184 | } 185 | } 186 | 187 | fn find_2byte_pat(text: &[u8], pat: &[u8]) -> Option<(usize, usize)> { 188 | debug_assert!(text.len() >= pat.len()); 189 | debug_assert!(pat.len() == 2); 190 | // Search for the second byte of the pattern, not the first, better for 191 | // scripts where we have two-byte encoded codepoints (the first byte will 192 | // repeat much more often than the second). 193 | let mut off = 1; 194 | while let Some(i) = memchr::memchr(pat[1], &text[off..]) { 195 | match text.get(off + i - 1) { 196 | None => break, 197 | Some(&c) if c == pat[0] => return Some((off + i - 1, off + i + 1)), 198 | _ => off += i + 1, 199 | } 200 | 201 | } 202 | None 203 | } 204 | 205 | /// Simd text search optimized for short patterns (<= 8 bytes) 206 | #[target_feature(enable = "sse4.2")] 207 | unsafe fn find_short_pat(text: &[u8], pat: &[u8]) -> Option { 208 | debug_assert!(pat.len() <= 8); 209 | /* 210 | if pat.len() == 2 { 211 | return find_2byte_pat(text, pat); 212 | } 213 | */ 214 | let r = pat128(pat); 215 | 216 | // safe part of text -- everything but the last 16 bytes 217 | let safetext = &text[..cmp::max(text.len(), 16) - 16]; 218 | 219 | let mut pos = 0; 220 | 'search: loop { 221 | if pos + pat.len() > safetext.len() { 222 | break; 223 | } 224 | // find the next occurence 225 | match first_start_of_match_nomask(&safetext[pos..], pat.len(), r) { 226 | None => { 227 | pos = cmp::max(pos, safetext.len() - pat.len()); 228 | break // no matches 229 | } 230 | Some((mpos, mlen)) => { 231 | pos += mpos; 232 | if mlen < pat.len() { 233 | if pos > text.len() - pat.len() { 234 | return None; 235 | } 236 | for (&a, &b) in zip(&text[pos + mlen..], &pat[mlen..]) { 237 | if a != b { 238 | pos += 1; 239 | continue 'search; 240 | } 241 | } 242 | } 243 | 244 | return Some(pos); 245 | } 246 | } 247 | } 248 | 249 | 'tail: loop { 250 | if pos > text.len() - pat.len() { 251 | return None; 252 | } 253 | // find the next occurence 254 | match first_start_of_match_mask(&text[pos..], pat.len(), r) { 255 | None => return None, // no matches 256 | Some((mpos, mlen)) => { 257 | pos += mpos; 258 | if mlen < pat.len() { 259 | if pos > text.len() - pat.len() { 260 | return None; 261 | } 262 | for (&a, &b) in zip(&text[pos + mlen..], &pat[mlen..]) { 263 | if a != b { 264 | pos += 1; 265 | continue 'tail; 266 | } 267 | } 268 | } 269 | 270 | return Some(pos); 271 | } 272 | } 273 | } 274 | } 275 | 276 | /// `is_supported` checks whether necessary SSE 4.2 feature is supported on current CPU. 277 | pub fn is_supported() -> bool { 278 | #[cfg(feature = "use_std")] 279 | return is_x86_feature_detected!("sse4.2"); 280 | #[cfg(not(feature = "use_std"))] 281 | return cfg!(target_feature = "sse4.2"); 282 | } 283 | 284 | /// `find` finds the first ocurrence of `pattern` in the `text`. 285 | /// 286 | /// This is the SSE42 accelerated version. 287 | pub fn find(text: &[u8], pattern: &[u8]) -> Option { 288 | assert!(is_supported()); 289 | 290 | if pattern.is_empty() { 291 | return Some(0); 292 | } else if text.len() < pattern.len() { 293 | return None; 294 | } else if pattern.len() == 1 { 295 | return memchr::memchr(pattern[0], text); 296 | } else { 297 | unsafe { find_inner(text, pattern) } 298 | } 299 | } 300 | 301 | #[target_feature(enable = "sse4.2")] 302 | pub(crate) unsafe fn find_inner(text: &[u8], pat: &[u8]) -> Option { 303 | if pat.len() <= 6 { 304 | return find_short_pat(text, pat); 305 | } 306 | 307 | // real two way algorithm 308 | // 309 | 310 | // `memory` is the number of bytes of the left half that we already know 311 | let (crit_pos, mut period) = TwoWaySearcher::crit_params(pat); 312 | let mut memory; 313 | 314 | if &pat[..crit_pos] == &pat[period.. period + crit_pos] { 315 | memory = 0; // use memory 316 | } else { 317 | memory = !0; // !0 means memory is unused 318 | // approximation to the true period 319 | period = cmp::max(crit_pos, pat.len() - crit_pos) + 1; 320 | } 321 | 322 | //println!("pat: {:?}, crit={}, period={}", pat, crit_pos, period); 323 | let (left, right) = pat.split_at(crit_pos); 324 | let (right16, _right17) = right.split_at(cmp::min(16, right.len())); 325 | assert!(right.len() != 0); 326 | 327 | let r = pat128(right); 328 | 329 | // safe part of text -- everything but the last 16 bytes 330 | let safetext = &text[..cmp::max(text.len(), 16) - 16]; 331 | 332 | let mut pos = 0; 333 | if memory == !0 { 334 | // Long period case -- no memory, period is an approximation 335 | 'search: loop { 336 | if pos + pat.len() > safetext.len() { 337 | break; 338 | } 339 | // find the next occurence of the right half 340 | let start = crit_pos; 341 | match first_start_of_match_nomask(&safetext[pos + start..], right16.len(), r) { 342 | None => { 343 | pos = cmp::max(pos, safetext.len() - pat.len()); 344 | break // no matches 345 | } 346 | Some((mpos, mlen)) => { 347 | pos += mpos; 348 | let mut pfxlen = mlen; 349 | if pfxlen < right.len() { 350 | pfxlen += shared_prefix_inner(&text[pos + start + mlen..], &right[mlen..]); 351 | } 352 | if pfxlen != right.len() { 353 | // partial match 354 | // skip by the number of bytes matched 355 | pos += pfxlen + 1; 356 | continue 'search; 357 | } else { 358 | // matches right part 359 | } 360 | } 361 | } 362 | 363 | // See if the left part of the needle matches 364 | // XXX: Original algorithm compares from right to left here 365 | if left != &text[pos..pos + left.len()] { 366 | pos += period; 367 | continue 'search; 368 | } 369 | 370 | return Some(pos); 371 | } 372 | } else { 373 | // Short period case -- use memory, true period 374 | 'search_memory: loop { 375 | if pos + pat.len() > safetext.len() { 376 | break; 377 | } 378 | // find the next occurence of the right half 379 | //println!("memory trace pos={}, memory={}", pos, memory); 380 | let mut pfxlen = if memory == 0 { 381 | let start = crit_pos; 382 | match first_start_of_match_nomask(&safetext[pos + start..], right16.len(), r) { 383 | None => { 384 | pos = cmp::max(pos, safetext.len() - pat.len()); 385 | break // no matches 386 | } 387 | Some((mpos, mlen)) => { 388 | pos += mpos; 389 | mlen 390 | } 391 | } 392 | } else { 393 | memory - crit_pos 394 | }; 395 | if pfxlen < right.len() { 396 | pfxlen += shared_prefix_inner(&text[pos + crit_pos + pfxlen..], &right[pfxlen..]); 397 | } 398 | if pfxlen != right.len() { 399 | // partial match 400 | // skip by the number of bytes matched 401 | pos += pfxlen + 1; 402 | memory = 0; 403 | continue 'search_memory; 404 | } else { 405 | // matches right part 406 | } 407 | 408 | // See if the left part of the needle matches 409 | // XXX: Original algorithm compares from right to left here 410 | if memory <= left.len() && &left[memory..] != &text[pos + memory..pos + left.len()] { 411 | pos += period; 412 | memory = pat.len() - period; 413 | continue 'search_memory; 414 | } 415 | 416 | return Some(pos); 417 | } 418 | } 419 | 420 | // no memory used for final part 421 | 'tail: loop { 422 | if pos > text.len() - pat.len() { 423 | return None; 424 | } 425 | // find the next occurence of the right half 426 | let start = crit_pos; 427 | match first_start_of_match_mask(&text[pos + start..], right16.len(), r) { 428 | None => return None, 429 | Some((mpos, mlen)) => { 430 | pos += mpos; 431 | let mut pfxlen = mlen; 432 | if pfxlen < right.len() { 433 | pfxlen += shared_prefix_inner(&text[pos + start + mlen..], &right[mlen..]); 434 | } 435 | if pfxlen != right.len() { 436 | // partial match 437 | // skip by the number of bytes matched 438 | pos += pfxlen + 1; 439 | continue 'tail; 440 | 441 | } else { 442 | // matches right part 443 | } 444 | } 445 | } 446 | 447 | // See if the left part of the needle matches 448 | // XXX: Original algorithm compares from right to left here 449 | if left != &text[pos..pos + left.len()] { 450 | pos += period; 451 | continue 'tail; 452 | } 453 | 454 | return Some(pos); 455 | } 456 | } 457 | 458 | #[test] 459 | fn test_find() { 460 | let text = b"abc"; 461 | assert_eq!(find(text, b"d"), None); 462 | assert_eq!(find(text, b"c"), Some(2)); 463 | 464 | let longer = "longer text and so on, a bit more"; 465 | 466 | // test all windows 467 | for wsz in 1..longer.len() { 468 | for window in longer.as_bytes().windows(wsz) { 469 | let str_find = longer.find(::std::str::from_utf8(window).unwrap()); 470 | assert!(str_find.is_some()); 471 | assert_eq!(find(longer.as_bytes(), window), str_find, "{:?} {:?}", 472 | longer, ::std::str::from_utf8(window)); 473 | } 474 | } 475 | 476 | let pat = b"ger text and so on"; 477 | assert!(pat.len() > 16); 478 | assert_eq!(Some(3), find(longer.as_bytes(), pat)); 479 | 480 | // test short period case 481 | 482 | let text = "cbabababcbabababab"; 483 | let n = "abababab"; 484 | assert_eq!(text.find(n), find(text.as_bytes(), n.as_bytes())); 485 | 486 | // memoized case -- this is tricky 487 | let text = "cbababababababababababababababab"; 488 | let n = "abababab"; 489 | assert_eq!(text.find(n), find(text.as_bytes(), n.as_bytes())); 490 | 491 | } 492 | 493 | /// Load the first 16 bytes of `pat` into a SIMD vector. 494 | #[inline(always)] 495 | fn pat128(pat: &[u8]) -> __m128i { 496 | unsafe { 497 | mask_load(pat.as_ptr() as *const _, pat.len()) 498 | } 499 | } 500 | 501 | /// Load the first len bytes (maximum 16) from ptr into a vector, safely 502 | #[inline(always)] 503 | unsafe fn mask_load(ptr: *const u8, mut len: usize) -> __m128i { 504 | let mut data: __m128i = _mm_setzero_si128(); 505 | len = cmp::min(len, mem::size_of_val(&data)); 506 | 507 | ::std::ptr::copy_nonoverlapping(ptr, &mut data as *mut _ as _, len); 508 | return data; 509 | } 510 | 511 | /// Find longest shared prefix, return its length 512 | /// 513 | /// Alignment safe: works for any text, pat. 514 | pub fn shared_prefix(text: &[u8], pat: &[u8]) -> usize { 515 | assert!(is_supported()); 516 | 517 | unsafe { shared_prefix_inner(text, pat) } 518 | } 519 | 520 | #[target_feature(enable = "sse4.2")] 521 | unsafe fn shared_prefix_inner(text: &[u8], pat: &[u8]) -> usize { 522 | let tp = text.as_ptr(); 523 | let tlen = text.len(); 524 | let pp = pat.as_ptr(); 525 | let plen = pat.len(); 526 | let len = cmp::min(tlen, plen); 527 | 528 | // TODO: do non-aligned prefix manually too(?) aligned text or pat.. 529 | // all but the end we can process with pcmpestrm 530 | let initial_part = len.saturating_sub(16); 531 | let mut prefix_len = 0; 532 | let mut offset = 0; 533 | while offset < initial_part { 534 | let initial_tail = initial_part - offset; 535 | let mask = pcmpestrm_eq_each(tp, offset, initial_tail, pp, offset, initial_tail); 536 | // find zero in the first 16 bits 537 | if mask != 0xffff { 538 | let first_bit_set = (mask ^ 0xffff).trailing_zeros() as usize; 539 | prefix_len += first_bit_set; 540 | return prefix_len; 541 | } else { 542 | prefix_len += cmp::min(initial_tail, 16); 543 | } 544 | offset += 16; 545 | } 546 | // so one block left, the last (up to) 16 bytes 547 | // unchecked slicing .. we don't want panics in this function 548 | let text_suffix = get_unchecked(text, prefix_len..len); 549 | let pat_suffix = get_unchecked(pat, prefix_len..len); 550 | for (&a, &b) in zip(text_suffix, pat_suffix) { 551 | if a != b { 552 | break; 553 | } 554 | prefix_len += 1; 555 | } 556 | 557 | prefix_len 558 | } 559 | 560 | #[test] 561 | fn test_prefixlen() { 562 | let text_long = b"0123456789abcdefeffect"; 563 | let text_long2 = b"9123456789abcdefeffect"; 564 | let text_long3 = b"0123456789abcdefgffect"; 565 | let plen = shared_prefix(text_long, text_long); 566 | assert_eq!(plen, text_long.len()); 567 | let plen = shared_prefix(b"abcd", b"abc"); 568 | assert_eq!(plen, 3); 569 | let plen = shared_prefix(b"abcd", b"abcf"); 570 | assert_eq!(plen, 3); 571 | assert_eq!(0, shared_prefix(text_long, text_long2)); 572 | assert_eq!(0, shared_prefix(text_long, &text_long[1..])); 573 | assert_eq!(16, shared_prefix(text_long, text_long3)); 574 | 575 | for i in 0..text_long.len() + 1 { 576 | assert_eq!(text_long.len() - i, shared_prefix(&text_long[i..], &text_long[i..])); 577 | } 578 | 579 | let l1 = [7u8; 1024]; 580 | let mut l2 = [7u8; 1024]; 581 | let off = 1000; 582 | l2[off] = 0; 583 | for i in 0..off { 584 | let plen = shared_prefix(&l1[i..], &l2[i..]); 585 | assert_eq!(plen, off - i); 586 | } 587 | } 588 | -------------------------------------------------------------------------------- /src/tw.rs: -------------------------------------------------------------------------------- 1 | //! 2 | //! 3 | //! Two-way string matching 4 | //! 5 | //! http://monge.univ-mlv.fr/~mac/Articles-PDF/CP-1991-jacm.pdf 6 | #![allow(dead_code)] 7 | #![cfg(test)] 8 | 9 | use std::str; 10 | use std::cmp::max; 11 | use std::ops::Index; 12 | 13 | #[derive(Copy, Clone, Debug, PartialEq, PartialOrd)] 14 | pub struct Str<'a>(pub &'a [u8]); 15 | 16 | impl<'a> Str<'a> { 17 | fn len(&self) -> usize { self.0.len() } 18 | fn as_str(&self) -> &str { str::from_utf8(self.0).unwrap() } 19 | } 20 | 21 | impl<'a> Index for Str<'a> { 22 | type Output = u8; 23 | fn index(&self, ix: usize) -> &u8 { 24 | &self.0[ix - 1] 25 | } 26 | } 27 | 28 | // A note on a simple computation of the maximal suffix of a string 29 | // simpler, slower version of duval's algorithm 30 | fn compute_max_suf_pos(w: &[u8]) -> usize { 31 | // using 0-based indexing throughout 32 | let n = w.len(); 33 | let mut i = 0; 34 | let mut j = 1; 35 | while j < n { 36 | let mut k = 0; 37 | while j + k < n - 1 && w[i + k] == w[j + k] { 38 | k += 1; 39 | } 40 | if w[i + k] < w[j + k] { 41 | i += k + 1; 42 | } else { 43 | j += k + 1; 44 | } 45 | if i == j { 46 | j += 1; 47 | } 48 | } 49 | i 50 | } 51 | 52 | /// Jewels of Stringology: Text Algorithms 53 | /// Maxsuf-and-Period(x) 54 | fn maxsuf_and_period(x: &[u8]) -> (usize, usize) { 55 | let n = x.len(); 56 | 57 | let mut s = 1; 58 | let mut i = 2; 59 | let mut p = 1; 60 | 61 | while i <= n { 62 | let r = (i - s) % p; 63 | if x[i - 1] == x[s + r - 1] { 64 | i += 1; 65 | } else if x[i - 1] < x[s + r - 1] { 66 | i += 1; 67 | p = i - s; 68 | } else { 69 | s = i - r; 70 | i = s; 71 | p = 1; 72 | } 73 | } 74 | (s - 1, p) 75 | } 76 | 77 | /// From paper on Two-way string matching 78 | /// Return index, period 79 | /// The returned index is zero-based! 80 | fn maximal_suffix(x: Str, rev: bool) -> (usize, usize) { 81 | let n = x.len(); 82 | 83 | let mut i = 0; 84 | let mut j = 1; 85 | let mut k = 1; 86 | let mut p = 1; 87 | 88 | while j + k <= n { 89 | let ap = x[i + k]; 90 | let a = x[j + k]; 91 | /* 92 | println!("trace: x={}, i={}, j={}, k={}, ap={}/{}, a={}/{}", 93 | x.as_str(), i, j, k, ap as char, ap, a as char, a); 94 | */ 95 | if (a < ap && !rev) || (a > ap && rev) { 96 | j += k; 97 | k = 1; 98 | p = j - i; 99 | } else if a == ap { 100 | if k == p { 101 | j += p; 102 | k = 1; 103 | } else { 104 | k += 1; 105 | } 106 | } else { 107 | i = j; 108 | j = i + 1; 109 | k = 1; 110 | p = 1; 111 | } 112 | } 113 | //println!("trace: x={}, i={}, p={}", x.as_str(), i, p); 114 | 115 | (i, p) 116 | } 117 | 118 | /// Return critical position, period. 119 | /// critical position is zero-based 120 | pub fn crit_period(x: Str) -> (usize, usize) { 121 | let (i, p) = maximal_suffix(x, false); 122 | let (j, q) = maximal_suffix(x, true); 123 | if i >= j { 124 | (i, p) 125 | } else { 126 | (j, q) 127 | } 128 | } 129 | 130 | /// From paper on Two-way string matching 131 | /// 132 | /// **x**: pattern, 133 | /// **t**: text, 134 | pub fn find(x: Str, t: Str) { 135 | let n = x.len(); 136 | // `l` critical position, zero-based 137 | // `p` period 138 | let (l, p) = crit_period(x); 139 | println!("crit, period = {:?}", (l, p)); 140 | // x[1..l] is a suffix of x[l + 1..l + p] 141 | if l < n / 2 && x.0[..l] == x.0[p..p + l] { 142 | println!("short period case"); 143 | let mut pos = 0; 144 | let mut s = 0; // `s` is the memory 145 | while pos + n <= t.len() { 146 | let mut i = max(l, s) + 1; 147 | while i <= n && x[i] == t[pos + i] { 148 | i += 1; 149 | } 150 | if i <= n { 151 | println!("vars i={}, l={}, s={}, p={}", i, l, s, p); 152 | pos += max(i - l, 1 + max(s, p) - p); 153 | s = 0; 154 | } else { 155 | let mut j = l; 156 | while j > s && x[j] == t[pos + j] { 157 | j -= 1; 158 | } 159 | if j <= s { 160 | println!("pos={} is a match!", pos); 161 | } 162 | pos += p; 163 | s = n - p; 164 | } 165 | } 166 | } else { 167 | println!("long period case"); 168 | let q = max(l, n - l) + 1; 169 | let mut pos = 0; 170 | while pos + n <= t.len() { 171 | let mut i = l + 1; 172 | println!("vars i={}, l={}, p={}, pos={}", i, l, p, pos); 173 | while i <= n && x[i] == t[pos + i] { 174 | i += 1; 175 | } 176 | if i <= n { 177 | pos += i - l; 178 | } else { 179 | let mut j = l; 180 | while j > 0 && x[j] == t[pos + j] { 181 | j -= 1; 182 | } 183 | if j == 0 { 184 | // pos is a zero-based index.. 185 | println!("pos={} is a match", pos); 186 | } 187 | pos += q; 188 | } 189 | } 190 | } 191 | } 192 | 193 | pub fn find_(x: &str, y: &str) { 194 | find(Str(x.as_bytes()), 195 | Str(y.as_bytes())) 196 | } 197 | 198 | /// **x**: pattern, 199 | /// **t**: text, 200 | /// 201 | /// return the index of the first match (0-based index) 202 | pub fn find_first(x: Str, t: Str) -> Option { 203 | let n = x.len(); 204 | let (l, p) = crit_period(x); 205 | // x[1..l] is a suffix of x[l + 1..l + p] 206 | if l < n / 2 && x.0[..l] == x.0[p..p + l] { 207 | // short period case 208 | let mut pos = 0; 209 | let mut s = 0; // `s` is the memory 210 | while pos + n <= t.len() { 211 | let mut i = max(l, s) + 1; 212 | while i <= n && x[i] == t[pos + i] { 213 | i += 1; 214 | } 215 | if i <= n { 216 | pos += max(i - l, 1 + max(s, p) - p); 217 | s = 0; 218 | } else { 219 | let mut j = l; 220 | while j > s && x[j] == t[pos + j] { 221 | j -= 1; 222 | } 223 | if j <= s { 224 | return Some(pos); 225 | } 226 | pos += p; 227 | s = n - p; 228 | } 229 | } 230 | } else { 231 | // long period case 232 | let q = max(l, n - l) + 1; 233 | let mut pos = 0; 234 | while pos + n <= t.len() { 235 | let mut i = l + 1; 236 | while i <= n && x[i] == t[pos + i] { 237 | i += 1; 238 | } 239 | if i <= n { 240 | pos += i - l; 241 | } else { 242 | let mut j = l; 243 | while j > 0 && x[j] == t[pos + j] { 244 | j -= 1; 245 | } 246 | if j == 0 { 247 | return Some(pos); 248 | } 249 | pos += q; 250 | } 251 | } 252 | } 253 | None 254 | } 255 | 256 | #[test] 257 | fn test_max() { 258 | assert_eq!((2, 1), maximal_suffix(Str(b"aab"), false)); 259 | assert_eq!((0, 3), maximal_suffix(Str(b"aab"), true)); 260 | 261 | assert_eq!((0, 3), maximal_suffix(Str(b"aabaa"), true)); 262 | assert_eq!((2, 3), maximal_suffix(Str(b"aabaa"), false)); 263 | 264 | assert_eq!((0, 7), maximal_suffix(Str(b"gcagagag"), false)); 265 | assert_eq!((2, 2), maximal_suffix(Str(b"gcagagag"), true)); 266 | assert_eq!((2, 2), crit_period(Str(b"gcagagag"))); 267 | 268 | assert_eq!((2, 1), crit_period(Str(b"aab"))); 269 | assert_eq!((2, 3), crit_period(Str(b"aabaa"))); 270 | 271 | assert_eq!((2, 4), crit_period(Str(b"abaaaba"))); 272 | 273 | // both of these factorizations are critial factorizations 274 | assert_eq!((2, 2), crit_period(Str(b"banana"))); 275 | assert_eq!((1, 2), crit_period(Str(b"zanana"))); 276 | 277 | assert_eq!((10, 1), crit_period(Str(b"caaaaaaaaacc"))); 278 | 279 | assert_eq!((2, 3), crit_period(Str(b"aabaab"))); 280 | assert_eq!((1, 3), crit_period(Str(b"baabaa"))); 281 | 282 | assert_eq!((2, 3), crit_period(Str(b"babbab"))); 283 | 284 | // NOTE: returns "long period" case per = 2, which is an approximation 285 | assert_eq!((2, 2), crit_period(Str(b"abca"))); 286 | assert_eq!((1, 3), crit_period(Str(b"acba"))); 287 | } 288 | #[test] 289 | fn test_find() { 290 | find_("aab", "aaable"); 291 | find_("aab", "aaabaabe"); 292 | find_("aaaa", "boyaaarateaaaade"); 293 | assert_eq!(Some(10), find_first(Str(b"aaaa"), Str(b"boyaaarateaaaade"))); 294 | 295 | find_("aab", "bbbbbbbbb"); 296 | find_("aabaa", "aabaaabaaabaa"); 297 | 298 | assert_eq!(find_first(Str(b"ababab"), Str(b"cbcbabababab")), Some(4)); 299 | // this was a bug (typo) in the short period case 300 | assert_eq!(find_first(Str(b"aabaab"), Str(b"abbaab")), None); 301 | } 302 | 303 | #[test] 304 | fn test_max_suf_pos() { 305 | assert_eq!(2, compute_max_suf_pos(b"aab")); 306 | 307 | assert_eq!(2, compute_max_suf_pos(b"aabaa")); 308 | 309 | assert_eq!(0, compute_max_suf_pos(b"gcagagag")); 310 | assert_eq!(2, compute_max_suf_pos(b"banana")); 311 | } 312 | 313 | #[test] 314 | fn test_maxsuf_and_period() { 315 | assert_eq!((2, 1), maxsuf_and_period(b"aab")); 316 | assert_eq!((2, 3), maxsuf_and_period(b"aabaa")); 317 | assert_eq!((0, 7), maxsuf_and_period(b"gcagagag")); 318 | } 319 | 320 | /* 321 | #[test] 322 | fn slow() { 323 | let needle = (0..100).map(|_| "b").collect::(); 324 | let heystack = (0..100_000).map(|_| "a").collect::(); 325 | 326 | println!("Data ready."); 327 | 328 | for _ in 0..100 { 329 | if find_first(Str(heystack.as_bytes()), Str(needle.as_bytes())).is_none() { 330 | // Stuff... 331 | } 332 | } 333 | } 334 | */ 335 | -------------------------------------------------------------------------------- /tests/quick.rs: -------------------------------------------------------------------------------- 1 | #![cfg(feature = "pattern")] 2 | #![feature(pattern)] 3 | #![allow(dead_code)] 4 | 5 | extern crate twoway; 6 | 7 | extern crate quickcheck; 8 | extern crate itertools as it; 9 | extern crate odds; 10 | #[macro_use] extern crate macro_attr; 11 | #[macro_use] extern crate newtype_derive; 12 | 13 | mod quickchecks { 14 | 15 | use twoway::{Str, StrSearcher}; 16 | use twoway::{ 17 | find_str, 18 | rfind_str, 19 | }; 20 | use it::{Itertools, unfold}; 21 | 22 | use std::str::pattern::{Pattern, Searcher, ReverseSearcher, SearchStep}; 23 | use std::str::pattern::SearchStep::{Match, Reject, Done}; 24 | 25 | use std::ops::Deref; 26 | 27 | use odds::string::StrExt; 28 | 29 | use quickcheck as qc; 30 | use quickcheck::TestResult; 31 | use quickcheck::Arbitrary; 32 | use quickcheck::quickcheck; 33 | 34 | #[derive(Copy, Clone, Debug)] 35 | /// quickcheck Arbitrary adaptor - half the size of `T` on average 36 | struct Short(T); 37 | 38 | impl Deref for Short { 39 | type Target = T; 40 | fn deref(&self) -> &T { &self.0 } 41 | } 42 | 43 | impl Arbitrary for Short 44 | where T: Arbitrary 45 | { 46 | fn arbitrary(g: &mut G) -> Self { 47 | let sz = g.size() / 2; 48 | Short(T::arbitrary(&mut qc::StdGen::new(g, sz))) 49 | } 50 | 51 | fn shrink(&self) -> Box> { 52 | Box::new((**self).shrink().map(Short)) 53 | } 54 | } 55 | 56 | macro_attr! { 57 | #[derive(Clone, Debug, NewtypeDeref!)] 58 | struct Text(String); 59 | } 60 | 61 | static ALPHABET: &'static str = "abñòαβ\u{3c72}"; 62 | static SIMPLEALPHABET: &'static str = "ab"; 63 | 64 | impl Arbitrary for Text { 65 | fn arbitrary(g: &mut G) -> Self { 66 | let len = u16::arbitrary(g); 67 | let mut s = String::with_capacity(len as usize); 68 | let alpha_len = ALPHABET.chars().count(); 69 | for _ in 0..len { 70 | let i = usize::arbitrary(g); 71 | let i = i % alpha_len; 72 | s.push(ALPHABET.chars().nth(i).unwrap()); 73 | } 74 | Text(s) 75 | } 76 | fn shrink(&self) -> Box> { 77 | Box::new(self.0.shrink().map(Text)) 78 | } 79 | } 80 | 81 | /// Text from an alphabet of only two letters 82 | macro_attr! { 83 | #[derive(Clone, Debug, NewtypeDeref!)] 84 | struct SimpleText(String); 85 | } 86 | 87 | impl Arbitrary for SimpleText { 88 | fn arbitrary(g: &mut G) -> Self { 89 | let len = u16::arbitrary(g); 90 | let mut s = String::with_capacity(len as usize); 91 | let alpha_len = SIMPLEALPHABET.chars().count(); 92 | for _ in 0..len { 93 | let i = usize::arbitrary(g); 94 | let i = i % alpha_len; 95 | s.push(SIMPLEALPHABET.chars().nth(i).unwrap()); 96 | } 97 | SimpleText(s) 98 | } 99 | fn shrink(&self) -> Box> { 100 | Box::new(self.0.shrink().map(SimpleText)) 101 | } 102 | } 103 | 104 | #[derive(Clone, Debug)] 105 | struct ShortText(String); 106 | // Half the length of Text on average 107 | impl Arbitrary for ShortText { 108 | fn arbitrary(g: &mut G) -> Self { 109 | let len = u16::arbitrary(g) / 2; 110 | let mut s = String::with_capacity(len as usize); 111 | let alpha_len = ALPHABET.chars().count(); 112 | for _ in 0..len { 113 | let i = usize::arbitrary(g); 114 | let i = i % alpha_len; 115 | s.push(ALPHABET.chars().nth(i).unwrap()); 116 | } 117 | ShortText(s) 118 | } 119 | fn shrink(&self) -> Box> { 120 | Box::new(self.0.shrink().map(ShortText)) 121 | } 122 | } 123 | 124 | pub fn contains(hay: &str, n: &str) -> bool { 125 | Str(n).is_contained_in(hay) 126 | } 127 | 128 | pub fn find(hay: &str, n: &str) -> Option { 129 | Str(n).into_searcher(hay).next_match().map(|(a, _)| a) 130 | } 131 | 132 | pub fn contains_rev(hay: &str, n: &str) -> bool { 133 | let mut tws = StrSearcher::new(hay, n); 134 | loop { 135 | match tws.next_back() { 136 | SearchStep::Done => return false, 137 | SearchStep::Match(..) => return true, 138 | _ => { } 139 | } 140 | } 141 | } 142 | 143 | pub fn rfind(hay: &str, n: &str) -> Option { 144 | Str(n).into_searcher(hay).next_match_back().map(|(a, _)| a) 145 | } 146 | 147 | #[test] 148 | fn test_contains() { 149 | fn prop(a: Text, b: Short) -> TestResult { 150 | let a = &a.0; 151 | let b = &b[..]; 152 | let truth = a.contains(b); 153 | TestResult::from_bool(contains(&a, &b) == truth) 154 | } 155 | quickcheck(prop as fn(_, _) -> _); 156 | } 157 | 158 | #[test] 159 | fn test_contains_rev() { 160 | fn prop(a: Text, b: Short) -> TestResult { 161 | let a = &a.0; 162 | let b = &b[..]; 163 | let truth = a.contains(b); 164 | TestResult::from_bool(contains_rev(&a, &b) == truth) 165 | } 166 | quickcheck(prop as fn(_, _) -> _); 167 | } 168 | 169 | #[test] 170 | fn test_find_str() { 171 | fn prop(a: Text, b: Short) -> TestResult { 172 | let a = &a.0; 173 | let b = &b[..]; 174 | let truth = a.find(b); 175 | TestResult::from_bool(find_str(&a, &b) == truth) 176 | } 177 | quickcheck(prop as fn(_, _) -> _); 178 | } 179 | 180 | #[test] 181 | fn test_rfind_str() { 182 | fn prop(a: Text, b: Short) -> TestResult { 183 | let a = &a.0; 184 | let b = &b[..]; 185 | let truth = a.rfind(b); 186 | TestResult::from_bool(rfind_str(&a, &b) == truth) 187 | } 188 | quickcheck(prop as fn(_, _) -> _); 189 | } 190 | 191 | #[test] 192 | fn test_contains_plus() { 193 | fn prop(a: Text, b: Short) -> TestResult { 194 | let a = &a.0; 195 | let b = &b[..]; 196 | //let b = &b.0; 197 | if b.len() == 0 { return TestResult::discard() } 198 | let truth = a.contains(b); 199 | TestResult::from_bool(contains(&a, &b) == truth && 200 | (!truth || b.substrings().all(|sub| contains(&a, sub)))) 201 | } 202 | quickcheck(prop as fn(_, _) -> _); 203 | } 204 | 205 | #[test] 206 | fn test_contains_rev_plus() { 207 | fn prop(a: Text, b: Short) -> TestResult { 208 | let a = &a.0; 209 | let b = &b[..]; 210 | if b.len() == 0 { return TestResult::discard() } 211 | let truth = a.contains(b); 212 | TestResult::from_bool(contains_rev(&a, &b) == truth && 213 | (!truth || b.substrings().all(|sub| contains_rev(&a, sub)))) 214 | } 215 | quickcheck(prop as fn(_, _) -> _); 216 | } 217 | 218 | #[test] 219 | fn test_starts_with() { 220 | fn prop(a: Text, b: Short) -> TestResult { 221 | let a = &a.0; 222 | let b = &b[..]; 223 | let truth = a.starts_with(b); 224 | TestResult::from_bool(Str(b).is_prefix_of(a) == truth) 225 | } 226 | quickcheck(prop as fn(_, _) -> _); 227 | } 228 | 229 | #[test] 230 | fn test_ends_with() { 231 | fn prop(a: Text, b: Short) -> TestResult { 232 | let a = &a.0; 233 | let b = &b[..]; 234 | let truth = a.ends_with(b); 235 | TestResult::from_bool(Str(b).is_suffix_of(a) == truth) 236 | } 237 | quickcheck(prop as fn(_, _) -> _); 238 | } 239 | 240 | #[test] 241 | fn test_next_reject() { 242 | fn prop(a: Text, b: Short) -> TestResult { 243 | let a = &a.0; 244 | let b = &b[..]; 245 | let truth = b.into_searcher(a).next_reject().map(|(a, _)| a); 246 | TestResult::from_bool(Str(b).into_searcher(a).next_reject().map(|(a, _)| a) == truth) 247 | } 248 | quickcheck(prop as fn(_, _) -> _); 249 | } 250 | 251 | #[test] 252 | fn test_next_reject_back() { 253 | fn prop(a: Text, b: Short) -> TestResult { 254 | let a = &a.0; 255 | let b = &b[..]; 256 | let truth = b.into_searcher(a).next_reject_back().map(|(_, b)| b); 257 | TestResult::from_bool(Str(b).into_searcher(a).next_reject_back().map(|(_, b)| b) == truth) 258 | } 259 | quickcheck(prop as fn(_, _) -> _); 260 | } 261 | 262 | fn coalesce_rejects(a: SearchStep, b: SearchStep) 263 | -> Result 264 | { 265 | match (a, b) { 266 | (SearchStep::Reject(a, b), SearchStep::Reject(c, d)) => { 267 | assert_eq!(b, c); 268 | Ok(SearchStep::Reject(a, d)) 269 | } 270 | otherwise => Err(otherwise), 271 | } 272 | } 273 | 274 | fn coalesce_intervals(a: Option<(usize, usize)>, b: Option<(usize, usize)> ) 275 | -> Result, (Option<(usize, usize)>, Option<(usize, usize)>)> 276 | { 277 | match (a, b) { 278 | (Some((x, y)), Some((w, z))) => { 279 | assert_eq!(y, w); 280 | Ok(Some((x, z))) 281 | } 282 | otherwise => Err(otherwise), 283 | } 284 | } 285 | 286 | // Test that all search steps are contiguous 287 | #[test] 288 | fn test_search_steps() { 289 | fn prop(a: Text, b: Text) -> bool { 290 | let hay = &a.0; 291 | let n = &b.0; 292 | let tws = StrSearcher::new(hay, n); 293 | // Make sure it covers the whole string 294 | let mut search_steps = unfold(tws, |tws| { 295 | match tws.next() { 296 | SearchStep::Done => None, 297 | otherwise => Some(otherwise), 298 | } 299 | }).map(|step| match step { 300 | SearchStep::Match(a, b) | SearchStep::Reject(a, b) => Some((a, b)), 301 | SearchStep::Done => None, 302 | }).coalesce(coalesce_intervals); 303 | match search_steps.next() { 304 | None => hay.len() == 0, 305 | Some(None) => true, 306 | Some(Some((a, b))) => { 307 | //println!("Next step would be: {:?}", search_steps.next()); 308 | assert_eq!((a, b), (0, hay.len())); 309 | true 310 | } 311 | } 312 | //assert_eq!(search_steps.next(), Some(SearchStep::Match(0, a.len()))); 313 | //true 314 | //search_steps.next() == Some(SearchStep::Match(0, a.len())) } 315 | } 316 | quickcheck(prop as fn(_, _) -> _); 317 | } 318 | 319 | #[test] 320 | fn test_search_steps_rev() { 321 | fn prop(a: Text, b: Text) -> bool { 322 | let hay = &a.0; 323 | let n = &b.0; 324 | let tws = StrSearcher::new(hay, n); 325 | // Make sure it covers the whole string 326 | let mut search_steps = unfold(tws, |tws| { 327 | match tws.next_back() { 328 | SearchStep::Done => None, 329 | otherwise => Some(otherwise), 330 | } 331 | }).map(|step| match step { 332 | SearchStep::Match(a, b) | SearchStep::Reject(a, b) => Some((a, b)), 333 | SearchStep::Done => None, 334 | }).coalesce(|a, b| match coalesce_intervals(b, a) { 335 | // adaption for reverse order 336 | Ok(c) => Ok(c), 337 | Err((d, e)) => Err((e, d)), 338 | }); 339 | match search_steps.next() { 340 | None => hay.len() == 0, 341 | Some(None) => true, 342 | Some(Some((a, b))) => { 343 | //println!("Next step would be: {:?}", search_steps.next()); 344 | assert_eq!((a, b), (0, hay.len())); 345 | true 346 | } 347 | } 348 | //assert_eq!(search_steps.next(), Some(SearchStep::Match(0, a.len()))); 349 | //true 350 | //search_steps.next() == Some(SearchStep::Match(0, a.len())) } 351 | } 352 | quickcheck(prop as fn(_, _) -> _); 353 | } 354 | 355 | // Test that all search steps are well formed 356 | #[test] 357 | fn test_search_steps_wf() { 358 | fn prop(a: Text, b: Text) -> bool { 359 | let hay = &a.0; 360 | let n = &b.0; 361 | let mut tws = StrSearcher::new(hay, n); 362 | let mut rejects_seen = 0; // n rejects seen since last match 363 | let test_single_rejects = false; 364 | let test_utf8_boundaries = true; 365 | loop { 366 | match tws.next() { 367 | Reject(a, b) => { 368 | assert!(!test_single_rejects || rejects_seen == 0); 369 | assert!(!test_utf8_boundaries || (hay.is_char_boundary(a) && hay.is_char_boundary(b))); 370 | rejects_seen += 1; 371 | assert!(a != b, "Reject({}, {}) is zero size", a, b); 372 | } 373 | Match(a, b) => { 374 | assert_eq!(b - a, n.len()); 375 | assert!(!test_single_rejects || rejects_seen <= 1, "rejects_seen={}", rejects_seen); 376 | rejects_seen = 0; 377 | } 378 | Done => { 379 | assert!(!test_single_rejects || rejects_seen <= 1, "rejects_seen={}", rejects_seen); 380 | break; 381 | } 382 | } 383 | } 384 | true 385 | } 386 | quickcheck(prop as fn(_, _) -> _); 387 | } 388 | 389 | // Test that all search steps are well formed 390 | #[test] 391 | fn test_search_steps_wf_rev() { 392 | fn prop(a: Text, b: Text) -> bool { 393 | let hay = &a.0; 394 | let n = &b.0; 395 | let mut tws = StrSearcher::new(hay, n); 396 | let mut rejects_seen = 0; // n rejects seen since last match 397 | let test_single_rejects = false; 398 | let test_utf8_boundaries = true; 399 | loop { 400 | match tws.next_back() { 401 | Reject(a, b) => { 402 | assert!(!test_utf8_boundaries || (hay.is_char_boundary(a) && hay.is_char_boundary(b))); 403 | assert!(!test_single_rejects || rejects_seen == 0); 404 | rejects_seen += 1; 405 | assert!(a != b, "Reject({}, {}) is zero size", a, b); 406 | } 407 | Match(a, b) => { 408 | assert_eq!(b - a, n.len()); 409 | assert!(!test_single_rejects || rejects_seen <= 1, "rejects_seen={}", rejects_seen); 410 | rejects_seen = 0; 411 | } 412 | Done => { 413 | assert!(!test_single_rejects || rejects_seen <= 1, "rejects_seen={}", rejects_seen); 414 | break; 415 | } 416 | } 417 | } 418 | true 419 | } 420 | quickcheck(prop as fn(_, _) -> _); 421 | } 422 | 423 | #[test] 424 | fn test_contains_substrings() { 425 | fn prop(s: (char, char, char, char)) -> bool { 426 | let mut ss = String::new(); 427 | ss.push(s.0); 428 | ss.push(s.1); 429 | ss.push(s.2); 430 | ss.push(s.3); 431 | let a = &ss; 432 | for sub in a.substrings() { 433 | assert!(a.contains(sub)); 434 | if !contains(a, sub) { 435 | return false; 436 | } 437 | } 438 | true 439 | } 440 | quickcheck(prop as fn(_) -> _); 441 | } 442 | 443 | #[test] 444 | fn test_contains_substrings_rev() { 445 | fn prop(s: (char, char, char, char)) -> bool { 446 | let mut ss = String::new(); 447 | ss.push(s.0); 448 | ss.push(s.1); 449 | ss.push(s.2); 450 | ss.push(s.3); 451 | let a = &ss; 452 | for sub in a.substrings() { 453 | assert!(a.contains(sub)); 454 | if !contains_rev(a, sub) { 455 | return false; 456 | } 457 | } 458 | true 459 | } 460 | quickcheck(prop as fn(_) -> _); 461 | } 462 | 463 | #[test] 464 | fn test_find_period() { 465 | fn prop(a: SimpleText, b: Short) -> TestResult { 466 | let a = &a.0; 467 | let b = &b[..]; 468 | let pat = [b, b].concat(); 469 | let truth = a.find(&pat); 470 | TestResult::from_bool(find(a, &pat) == truth) 471 | } 472 | quickcheck(prop as fn(_, _) -> _); 473 | } 474 | 475 | #[test] 476 | fn test_find_rev_period() { 477 | fn prop(a: SimpleText, b: Short) -> TestResult { 478 | let a = &a.0; 479 | let b = &b[..]; 480 | let pat = [b, b].concat(); 481 | let truth = a.rfind(&pat); 482 | TestResult::from_bool(rfind(a, &pat) == truth) 483 | } 484 | quickcheck(prop as fn(_, _) -> _); 485 | } 486 | 487 | 488 | } 489 | --------------------------------------------------------------------------------