regexr 0.1.2

A high-performance regex engine built from scratch with JIT compilation and SIMD acceleration
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! Single-byte search (memchr).
//!
//! AVX2-accelerated single byte search with scalar fallback.
//! Processes 32 bytes at a time using SIMD when available.

/// Finds the first occurrence of a byte in a slice.
///
/// Uses AVX2 SIMD when available, falls back to scalar otherwise.
pub fn memchr(needle: u8, haystack: &[u8]) -> Option<usize> {
    #[cfg(target_arch = "x86_64")]
    {
        if is_x86_feature_detected!("avx2") {
            // SAFETY: We just checked for AVX2 support
            return unsafe { memchr_avx2(needle, haystack) };
        }
    }

    // Scalar fallback
    memchr_scalar(needle, haystack)
}

/// AVX2-accelerated memchr implementation.
///
/// Processes 32 bytes at a time using SIMD comparison.
///
/// # Safety
/// - Requires AVX2 support
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2")]
unsafe fn memchr_avx2(needle: u8, haystack: &[u8]) -> Option<usize> {
    use std::arch::x86_64::*;

    let len = haystack.len();
    if len == 0 {
        return None;
    }

    let ptr = haystack.as_ptr();
    let needle_vec = _mm256_set1_epi8(needle as i8);

    let mut offset = 0;

    // Process 32 bytes at a time
    while offset + 32 <= len {
        let data = _mm256_loadu_si256(ptr.add(offset) as *const __m256i);
        let cmp = _mm256_cmpeq_epi8(data, needle_vec);
        let mask = _mm256_movemask_epi8(cmp) as u32;

        if mask != 0 {
            return Some(offset + mask.trailing_zeros() as usize);
        }

        offset += 32;
    }

    // Handle remaining bytes (scalar)
    (offset..len).find(|&i| *haystack.get_unchecked(i) == needle)
}

/// Scalar implementation of memchr.
#[inline]
fn memchr_scalar(needle: u8, haystack: &[u8]) -> Option<usize> {
    haystack.iter().position(|&b| b == needle)
}

/// Finds the first occurrence of any of 2 bytes.
///
/// Uses AVX2 SIMD when available.
pub fn memchr2(needle1: u8, needle2: u8, haystack: &[u8]) -> Option<usize> {
    #[cfg(target_arch = "x86_64")]
    {
        if is_x86_feature_detected!("avx2") {
            // SAFETY: We just checked for AVX2 support
            return unsafe { memchr2_avx2(needle1, needle2, haystack) };
        }
    }

    // Scalar fallback
    haystack.iter().position(|&b| b == needle1 || b == needle2)
}

/// AVX2-accelerated memchr2 implementation.
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2")]
unsafe fn memchr2_avx2(needle1: u8, needle2: u8, haystack: &[u8]) -> Option<usize> {
    use std::arch::x86_64::*;

    let len = haystack.len();
    if len == 0 {
        return None;
    }

    let ptr = haystack.as_ptr();
    let needle1_vec = _mm256_set1_epi8(needle1 as i8);
    let needle2_vec = _mm256_set1_epi8(needle2 as i8);

    let mut offset = 0;

    // Process 32 bytes at a time
    while offset + 32 <= len {
        let data = _mm256_loadu_si256(ptr.add(offset) as *const __m256i);
        let cmp1 = _mm256_cmpeq_epi8(data, needle1_vec);
        let cmp2 = _mm256_cmpeq_epi8(data, needle2_vec);
        let combined = _mm256_or_si256(cmp1, cmp2);
        let mask = _mm256_movemask_epi8(combined) as u32;

        if mask != 0 {
            return Some(offset + mask.trailing_zeros() as usize);
        }

        offset += 32;
    }

    // Handle remaining bytes (scalar)
    for i in offset..len {
        let b = *haystack.get_unchecked(i);
        if b == needle1 || b == needle2 {
            return Some(i);
        }
    }

    None
}

/// Finds the first occurrence of any of 3 bytes.
///
/// Uses AVX2 SIMD when available.
pub fn memchr3(needle1: u8, needle2: u8, needle3: u8, haystack: &[u8]) -> Option<usize> {
    #[cfg(target_arch = "x86_64")]
    {
        if is_x86_feature_detected!("avx2") {
            // SAFETY: We just checked for AVX2 support
            return unsafe { memchr3_avx2(needle1, needle2, needle3, haystack) };
        }
    }

    // Scalar fallback
    haystack
        .iter()
        .position(|&b| b == needle1 || b == needle2 || b == needle3)
}

/// AVX2-accelerated memchr3 implementation.
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2")]
unsafe fn memchr3_avx2(needle1: u8, needle2: u8, needle3: u8, haystack: &[u8]) -> Option<usize> {
    use std::arch::x86_64::*;

    let len = haystack.len();
    if len == 0 {
        return None;
    }

    let ptr = haystack.as_ptr();
    let needle1_vec = _mm256_set1_epi8(needle1 as i8);
    let needle2_vec = _mm256_set1_epi8(needle2 as i8);
    let needle3_vec = _mm256_set1_epi8(needle3 as i8);

    let mut offset = 0;

    // Process 32 bytes at a time
    while offset + 32 <= len {
        let data = _mm256_loadu_si256(ptr.add(offset) as *const __m256i);
        let cmp1 = _mm256_cmpeq_epi8(data, needle1_vec);
        let cmp2 = _mm256_cmpeq_epi8(data, needle2_vec);
        let cmp3 = _mm256_cmpeq_epi8(data, needle3_vec);
        let combined = _mm256_or_si256(_mm256_or_si256(cmp1, cmp2), cmp3);
        let mask = _mm256_movemask_epi8(combined) as u32;

        if mask != 0 {
            return Some(offset + mask.trailing_zeros() as usize);
        }

        offset += 32;
    }

    // Handle remaining bytes (scalar)
    for i in offset..len {
        let b = *haystack.get_unchecked(i);
        if b == needle1 || b == needle2 || b == needle3 {
            return Some(i);
        }
    }

    None
}

/// Reverse memchr - finds the last occurrence of a byte.
///
/// Uses AVX2 SIMD when available.
pub fn memrchr(needle: u8, haystack: &[u8]) -> Option<usize> {
    #[cfg(target_arch = "x86_64")]
    {
        if is_x86_feature_detected!("avx2") {
            // SAFETY: We just checked for AVX2 support
            return unsafe { memrchr_avx2(needle, haystack) };
        }
    }

    // Scalar fallback
    haystack.iter().rposition(|&b| b == needle)
}

/// AVX2-accelerated reverse memchr implementation.
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2")]
unsafe fn memrchr_avx2(needle: u8, haystack: &[u8]) -> Option<usize> {
    use std::arch::x86_64::*;

    let len = haystack.len();
    if len == 0 {
        return None;
    }

    let ptr = haystack.as_ptr();
    let needle_vec = _mm256_set1_epi8(needle as i8);

    // Start from the end, rounding down to 32-byte boundary
    let mut offset = (len / 32) * 32;

    // Handle trailing bytes first (scalar)
    for i in (offset..len).rev() {
        if *haystack.get_unchecked(i) == needle {
            return Some(i);
        }
    }

    // Process 32 bytes at a time, backwards
    while offset >= 32 {
        offset -= 32;
        let data = _mm256_loadu_si256(ptr.add(offset) as *const __m256i);
        let cmp = _mm256_cmpeq_epi8(data, needle_vec);
        let mask = _mm256_movemask_epi8(cmp) as u32;

        if mask != 0 {
            // Find the highest set bit (last occurrence in this chunk)
            return Some(offset + 31 - mask.leading_zeros() as usize);
        }
    }

    None
}

/// Finds the first byte in a contiguous range [lo, hi].
///
/// Uses AVX2 SIMD range comparison when available.
/// This is much faster than calling memchr 10 times for digits (0-9).
pub fn memchr_range(lo: u8, hi: u8, haystack: &[u8]) -> Option<usize> {
    #[cfg(target_arch = "x86_64")]
    {
        if is_x86_feature_detected!("avx2") {
            // SAFETY: We just checked for AVX2 support
            return unsafe { memchr_range_avx2(lo, hi, haystack) };
        }
    }

    // Scalar fallback
    haystack.iter().position(|&b| b >= lo && b <= hi)
}

/// AVX2-accelerated range search.
///
/// Uses two comparisons: x >= lo AND x <= hi.
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2")]
unsafe fn memchr_range_avx2(lo: u8, hi: u8, haystack: &[u8]) -> Option<usize> {
    use std::arch::x86_64::*;

    let len = haystack.len();
    if len == 0 {
        return None;
    }

    let ptr = haystack.as_ptr();

    // For unsigned range check [lo, hi], we use:
    // x >= lo AND x <= hi
    //
    // For unsigned comparison with signed instructions, we add 128 to convert
    // the unsigned range [0, 255] to signed range [-128, 127].
    // Then x >= lo becomes (x + 128) >= (lo + 128) using signed comparison.
    let bias = _mm256_set1_epi8(-128i8); // Add 128 as signed = -128 unsigned
    let lo_biased = _mm256_set1_epi8((lo as i8).wrapping_add(-128i8));
    let hi_biased = _mm256_set1_epi8((hi as i8).wrapping_add(-128i8));

    let mut offset = 0;

    // Process 32 bytes at a time
    while offset + 32 <= len {
        let data = _mm256_loadu_si256(ptr.add(offset) as *const __m256i);

        // Convert to signed by adding bias (XOR with 0x80 = add 128)
        let data_biased = _mm256_add_epi8(data, bias);

        // Check x >= lo: data_biased > lo_biased - 1, or equivalently NOT(data_biased < lo_biased) AND NOT(data_biased == lo_biased - 1)
        // Simpler: use _mm256_cmpgt_epi8 for > and _mm256_cmpeq_epi8 for ==
        // x >= lo means x > lo - 1, but we need to handle underflow.
        // Instead: x >= lo is equivalent to NOT(x < lo) = NOT(lo > x)
        let lt_lo = _mm256_cmpgt_epi8(lo_biased, data_biased); // data < lo
        let gt_hi = _mm256_cmpgt_epi8(data_biased, hi_biased); // data > hi

        // In range if NOT(lt_lo) AND NOT(gt_hi)
        let out_of_range = _mm256_or_si256(lt_lo, gt_hi);
        let in_range = _mm256_andnot_si256(out_of_range, _mm256_set1_epi8(-1i8));
        let mask = _mm256_movemask_epi8(in_range) as u32;

        if mask != 0 {
            return Some(offset + mask.trailing_zeros() as usize);
        }

        offset += 32;
    }

    // Handle remaining bytes (scalar)
    for i in offset..len {
        let b = *haystack.get_unchecked(i);
        if b >= lo && b <= hi {
            return Some(i);
        }
    }

    None
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_memchr() {
        assert_eq!(memchr(b'o', b"hello"), Some(4));
        assert_eq!(memchr(b'x', b"hello"), None);
        assert_eq!(memchr(b'h', b"hello"), Some(0));
        assert_eq!(memchr(b'o', b"hello world"), Some(4));
    }

    #[test]
    fn test_memchr_empty() {
        assert_eq!(memchr(b'x', b""), None);
    }

    #[test]
    fn test_memchr_large() {
        // Test with data larger than 32 bytes to exercise SIMD path
        let data = b"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaax";
        assert_eq!(memchr(b'x', data), Some(64));

        let data = b"xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        assert_eq!(memchr(b'x', data), Some(0));
    }

    #[test]
    fn test_memchr2() {
        assert_eq!(memchr2(b'e', b'o', b"hello"), Some(1));
        assert_eq!(memchr2(b'x', b'y', b"hello"), None);
        assert_eq!(memchr2(b'o', b'h', b"hello"), Some(0)); // h comes first
    }

    #[test]
    fn test_memchr3() {
        assert_eq!(memchr3(b'x', b'y', b'e', b"hello"), Some(1));
        assert_eq!(memchr3(b'x', b'y', b'z', b"hello"), None);
    }

    #[test]
    fn test_memrchr() {
        assert_eq!(memrchr(b'l', b"hello"), Some(3));
        assert_eq!(memrchr(b'x', b"hello"), None);
        assert_eq!(memrchr(b'o', b"hello world"), Some(7));
    }

    #[test]
    fn test_memrchr_large() {
        // Test with data larger than 32 bytes
        let data = b"xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaax";
        assert_eq!(memrchr(b'x', data), Some(64));
    }

    #[test]
    fn test_memchr_at_chunk_boundaries() {
        // Test finding bytes at various positions around 32-byte boundaries
        for pos in [0, 1, 15, 16, 30, 31, 32, 33, 63, 64, 65] {
            if pos < 70 {
                let mut data = vec![b'a'; 70];
                data[pos] = b'x';
                assert_eq!(memchr(b'x', &data), Some(pos), "Failed at position {}", pos);
            }
        }
    }

    #[test]
    fn test_memchr_range_digits() {
        // Find digits in a string
        assert_eq!(memchr_range(b'0', b'9', b"hello 123 world"), Some(6));
        assert_eq!(memchr_range(b'0', b'9', b"no digits here"), None);
        assert_eq!(memchr_range(b'0', b'9', b"0 at start"), Some(0));
        assert_eq!(memchr_range(b'0', b'9', b"end is 9"), Some(7));
    }

    #[test]
    fn test_memchr_range_letters() {
        // Find lowercase letters
        assert_eq!(memchr_range(b'a', b'z', b"123 abc"), Some(4));
        assert_eq!(memchr_range(b'a', b'z', b"123 456"), None);
    }

    #[test]
    fn test_memchr_range_large() {
        // Test with data larger than 32 bytes
        let data = b"............................................5....................";
        assert_eq!(memchr_range(b'0', b'9', data), Some(44));
    }

    #[test]
    fn test_memchr_range_empty() {
        assert_eq!(memchr_range(b'0', b'9', b""), None);
    }

    #[test]
    fn test_memchr_range_all_match() {
        // All bytes are in range - should find first
        assert_eq!(memchr_range(b'0', b'9', b"123456"), Some(0));
    }
}