| 1 | //! # triple_accel |
| 2 | //! |
| 3 | //! Rust edit distance routines accelerated using SIMD. Supports fast Hamming, Levenshtein, |
| 4 | //! restricted Damerau-Levenshtein, etc. distance calculations and string search. |
| 5 | //! |
| 6 | //! Although vectorized SIMD code allows for up to 20-30x speedups over their scalar counterparts, |
| 7 | //! the difficulty of handling platform-dependent SIMD code makes SIMD routines less attractive. |
| 8 | //! The goal of this library is to provide an easy-to-use abstraction over SIMD edit distance routines |
| 9 | //! that fall back to scalar routines if the target CPU architecture is not supported. |
| 10 | //! Additionally, all limitations and tradeoffs of the edit distance routines should be provided upfront |
| 11 | //! so the user knows exactly what to expect. |
| 12 | //! Finally, this library should lead to performance boosts on both short and longer strings, so it |
| 13 | //! can be used for a variety of tasks, from bioinformatics to natural language processing. |
| 14 | //! `triple_accel` is very lightweight: it only has dependencies on other crates for benchmarking. |
| 15 | //! It can be built on machines without CPUs that have AVX2 or SSE4.1 support. It can also run on |
| 16 | //! machines without SIMD support by automatically using scalar alternatives. |
| 17 | //! |
| 18 | //! ## Features |
| 19 | //! |
| 20 | //! This library provides routines for both searching for some needle string in a haystack string |
| 21 | //! and calculating the edit distance between two strings. Hamming distance (mismatches only), |
| 22 | //! Levenshtein distance (mismatches + gaps), and restricted Damerau-Levenshtein distance |
| 23 | //! (transpositions + mismatches + gaps) are supported, along with arbitrary edit costs. This |
| 24 | //! library provides a simple interface, in addition to powerful lower-level control over the edit |
| 25 | //! distance calculations. |
| 26 | //! |
| 27 | //! At runtime, the implementation for a certain algorithm is selected based on CPU support, going |
| 28 | //! down the list: |
| 29 | //! |
| 30 | //! 1. Vectorized implementation with 256-bit AVX vectors, if AVX2 is supported. |
| 31 | //! 2. Vectorized implementation with 128-bit SSE vectors, if SSE4.1 is supported. |
| 32 | //! 3. Scalar implementation. |
| 33 | //! |
| 34 | //! Currently, vectorized SIMD implementations are only available for x86 or x86-64 CPUs. However, |
| 35 | //! after compiling this library on a machine that supports those SIMD intrinsics, the library can |
| 36 | //! be used on other machines. |
| 37 | //! Additionally, the internal data structure for storing vectors and the bit width of the values |
| 38 | //! in the vectors are selected at runtime for maximum efficiency and accuracy, given the lengths |
| 39 | //! of the input strings. |
| 40 | //! |
| 41 | //! ## Limitations |
| 42 | //! |
| 43 | //! Due to the use of SIMD intrinsics, only binary strings that are represented with `u8` bytes |
| 44 | //! are supported. Unicode strings are not currently supported. |
| 45 | //! |
| 46 | //! ## Notation |
| 47 | //! |
| 48 | //! Quick notation notes that will often appear in the code/documentation: |
| 49 | //! |
| 50 | //! * `k` - the number of edits that are allowed |
| 51 | //! * `a` and `b` - any two strings; this is usually used for edit distance routines |
| 52 | //! * `needle` and `haystack` - any two strings; we want to search for where needle appears in |
| 53 | //! haystack |
| 54 | //! |
| 55 | //! ## Examples |
| 56 | //! |
| 57 | //! Calculating the Hamming distance (number of mismatches) between two strings is extremely simple: |
| 58 | //! ``` |
| 59 | //! use triple_accel::*; |
| 60 | //! |
| 61 | //! let a = b"abcd"; |
| 62 | //! let b = b"abcc"; |
| 63 | //! |
| 64 | //! let dist = hamming(a, b); |
| 65 | //! assert!(dist == 1); |
| 66 | //! ``` |
| 67 | //! By default, SIMD will be used if possible. Similarly, we can easily calculate the Levenshtein |
| 68 | //! distance (character mismatches and gaps all have a cost of 1) between two strings with the |
| 69 | //! following code: |
| 70 | //! ``` |
| 71 | //! use triple_accel::*; |
| 72 | //! |
| 73 | //! let a = b"abc"; |
| 74 | //! let b = b"abcd"; |
| 75 | //! |
| 76 | //! let dist = levenshtein_exp(a, b); |
| 77 | //! assert!(dist == 1); |
| 78 | //! ``` |
| 79 | //! This uses exponential search to estimate the number of edits between `a` and `b`, which makes it |
| 80 | //! more efficient than the alternative `levenshtein` function when the number of edits between `a` |
| 81 | //! and `b` is low. |
| 82 | //! |
| 83 | //! In addition to edit distance routines, `triple_accel` also provides search routines. These |
| 84 | //! routines return an iterator over matches that indicate where the `needle` string matches the `haystack` |
| 85 | //! string. `triple_accel` will attempt to maximize the length of matches that end at the same position and |
| 86 | //! remove shorter matches when some matches fully overlap. |
| 87 | //! ``` |
| 88 | //! use triple_accel::*; |
| 89 | //! |
| 90 | //! let needle = b"helllo"; |
| 91 | //! let haystack = b"hello world"; |
| 92 | //! |
| 93 | //! let matches: Vec<Match> = levenshtein_search(needle, haystack).collect(); |
| 94 | //! // note: start index is inclusive, end index is exclusive! |
| 95 | //! assert!(matches == vec![Match{start: 0, end: 5, k: 1}]); |
| 96 | //! ``` |
| 97 | //! Sometimes, it is necessary to use the slightly lower level, but also more powerful routines |
| 98 | //! that `triple_accel` provides. For example, it is possible to allow transpositions (character swaps) |
| 99 | //! that have a cost of 1, in addition to mismatches and gaps: |
| 100 | //! ``` |
| 101 | //! use triple_accel::levenshtein::*; |
| 102 | //! |
| 103 | //! let a = b"abcd"; |
| 104 | //! let b = b"abdc"; |
| 105 | //! let k = 2; // upper bound on allowed cost |
| 106 | //! let trace_on = false; // return edit traceback? |
| 107 | //! |
| 108 | //! let dist = levenshtein_simd_k_with_opts(a, b, k, trace_on, RDAMERAU_COSTS); |
| 109 | //! // note: dist may be None if a and b do not match within a cost of k |
| 110 | //! assert!(dist.unwrap().0 == 1); |
| 111 | //! ``` |
| 112 | //! Don't let the name of the function fool you! `levenshtein_simd_k_with_opts` will still fall back to |
| 113 | //! the scalar implementation if AVX2 or SSE4.1 support is not available. It just prefers to use SIMD |
| 114 | //! where possible. |
| 115 | //! |
| 116 | //! For most common cases, the re-exported functions are enough, and the low level functions do not |
| 117 | //! have to be used directly. |
| 118 | |
| 119 | use std::*; |
| 120 | |
| 121 | mod jewel; |
| 122 | pub mod hamming; |
| 123 | pub mod levenshtein; |
| 124 | |
| 125 | // re-export common functions |
| 126 | pub use hamming::{hamming, hamming_search}; |
| 127 | pub use levenshtein::{levenshtein, rdamerau, levenshtein_exp, rdamerau_exp, levenshtein_search}; |
| 128 | |
| 129 | // some shared utility stuff below |
| 130 | |
| 131 | /// A struct that describes a single matching location. |
| 132 | /// |
| 133 | /// This is usually returned as part of searching routines. |
| 134 | #[derive(Debug, PartialEq)] |
| 135 | pub struct Match { |
| 136 | /// The start index of the match (inclusive). |
| 137 | pub start: usize, |
| 138 | /// The end index of the match (exclusive). |
| 139 | pub end: usize, |
| 140 | /// Number of edits for the match. |
| 141 | pub k: u32 |
| 142 | } |
| 143 | |
| 144 | /// An enum describing possible edit operations. |
| 145 | /// |
| 146 | /// This is usually returned as part of the traceback for edit distance routines. |
| 147 | #[derive(Debug, PartialEq)] |
| 148 | pub enum EditType { |
| 149 | Match, |
| 150 | Mismatch, |
| 151 | AGap, |
| 152 | BGap, |
| 153 | Transpose |
| 154 | } |
| 155 | |
| 156 | /// A struct representing a sequence of edits of the same type. |
| 157 | /// |
| 158 | /// This is returned in the run-length encoded traceback of edit distance routines. |
| 159 | #[derive(Debug, PartialEq)] |
| 160 | pub struct Edit { |
| 161 | /// The type of edit operation. |
| 162 | pub edit: EditType, |
| 163 | /// The number of consecutive edit operations of the same type. |
| 164 | pub count: usize |
| 165 | } |
| 166 | |
| 167 | /// An enum representing whether to return all matches or just the best matches. |
| 168 | /// |
| 169 | /// This is used as an argument for searching routines. |
| 170 | #[derive(Debug, PartialEq, Copy, Clone)] |
| 171 | pub enum SearchType { |
| 172 | All, |
| 173 | Best |
| 174 | } |
| 175 | |
| 176 | /// This creates a vector with the alignment and padding for `u128` values, and |
| 177 | /// then convert it to a vector of `u8` values that is returned. |
| 178 | /// |
| 179 | /// This is possible because u8 has looser alignment requirements than `u128`. |
| 180 | /// This vector can be easily converted back to `u128` or `u64` later, for Hamming |
| 181 | /// distance routines. |
| 182 | /// The returned vector can be edited by copying `u8` values into it. |
| 183 | /// However, do not do any operation (like `push`) that may cause the the vector to be |
| 184 | /// reallocated. |
| 185 | /// |
| 186 | /// # Arguments |
| 187 | /// * `len` - the length of the resulting array of u8 values |
| 188 | /// |
| 189 | /// # Example |
| 190 | /// ``` |
| 191 | /// # use triple_accel::*; |
| 192 | /// let s = alloc_str(10); |
| 193 | /// |
| 194 | /// assert!(s.len() == 10); |
| 195 | /// ``` |
| 196 | #[inline] |
| 197 | pub fn alloc_str(len: usize) -> Vec<u8> { |
| 198 | let words_len = (len >> 4) + (if (len & 15) > 0 {1} else {0}); |
| 199 | let words = vec![0u128; words_len]; |
| 200 | let mut words = mem::ManuallyDrop::new(words); |
| 201 | |
| 202 | unsafe { |
| 203 | Vec::from_raw_parts(words.as_mut_ptr() as *mut u8, len, words_len << 4) |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | /// Directly copy from the a source `u8` slice to a destination `u8` slice. |
| 208 | /// |
| 209 | /// Can be used to copy string data after allocating a vector using `alloc_str`. |
| 210 | /// |
| 211 | /// # Arguments |
| 212 | /// * `dest` - the destination slice |
| 213 | /// * `src` - the source slice |
| 214 | /// |
| 215 | /// # Panics |
| 216 | /// * If the length of `src` is greater than the length of `dest`. |
| 217 | /// |
| 218 | /// # Example |
| 219 | /// ``` |
| 220 | /// # use triple_accel::*; |
| 221 | /// let mut a = vec![0u8; 5]; |
| 222 | /// let b = vec![1u8, 2u8, 3u8, 4u8]; |
| 223 | /// |
| 224 | /// fill_str(&mut a, &b); |
| 225 | /// |
| 226 | /// assert!(a == vec![1u8, 2u8, 3u8, 4u8, 0u8]); |
| 227 | /// ``` |
| 228 | #[inline] |
| 229 | pub fn fill_str(dest: &mut [u8], src: &[u8]) { |
| 230 | assert!(dest.len() >= src.len()); |
| 231 | |
| 232 | unsafe { |
| 233 | ptr::copy_nonoverlapping(src.as_ptr(), dest.as_mut_ptr(), src.len()); |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | fn check_no_null_bytes(s: &[u8]) { |
| 238 | for i in 0..s.len() { |
| 239 | if s[i] == 0u8 { |
| 240 | panic!("No zero/null bytes allowed in the string!"); |
| 241 | } |
| 242 | } |
| 243 | } |
| 244 |