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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
|
/*!
This module defines 128-bit vector implementations of `memchr` and friends.
The main types in this module are [`One`], [`Two`] and [`Three`]. They are for
searching for one, two or three distinct bytes, respectively, in a haystack.
Each type also has corresponding double ended iterators. These searchers are
typically much faster than scalar routines accomplishing the same task.
The `One` searcher also provides a [`One::count`] routine for efficiently
counting the number of times a single byte occurs in a haystack. This is
useful, for example, for counting the number of lines in a haystack. This
routine exists because it is usually faster, especially with a high match
count, then using [`One::find`] repeatedly. ([`OneIter`] specializes its
`Iterator::count` implementation to use this routine.)
Only one, two and three bytes are supported because three bytes is about
the point where one sees diminishing returns. Beyond this point and it's
probably (but not necessarily) better to just use a simple `[bool; 256]` array
or similar. However, it depends mightily on the specific work-load and the
expected match frequency.
*/
use core::arch::x86_64::__m128i;
use crate::{arch::generic::memchr as generic, ext::Pointer, vector::Vector};
/// Finds all occurrences of a single byte in a haystack.
#[derive(Clone, Copy, Debug)]
pub struct One(generic::One<__m128i>);
impl One {
/// Create a new searcher that finds occurrences of the needle byte given.
///
/// This particular searcher is specialized to use SSE2 vector instructions
/// that typically make it quite fast.
///
/// If SSE2 is unavailable in the current environment, then `None` is
/// returned.
#[inline]
pub fn new(needle: u8) -> Option<One> {
if One::is_available() {
// SAFETY: we check that sse2 is available above.
unsafe { Some(One::new_unchecked(needle)) }
} else {
None
}
}
/// Create a new finder specific to SSE2 vectors and routines without
/// checking that SSE2 is available.
///
/// # Safety
///
/// Callers must guarantee that it is safe to execute `sse2` instructions
/// in the current environment.
///
/// Note that it is a common misconception that if one compiles for an
/// `x86_64` target, then they therefore automatically have access to SSE2
/// instructions. While this is almost always the case, it isn't true in
/// 100% of cases.
#[target_feature(enable = "sse2")]
#[inline]
pub unsafe fn new_unchecked(needle: u8) -> One {
One(generic::One::new(needle))
}
/// Returns true when this implementation is available in the current
/// environment.
///
/// When this is true, it is guaranteed that [`One::new`] will return
/// a `Some` value. Similarly, when it is false, it is guaranteed that
/// `One::new` will return a `None` value.
///
/// Note also that for the lifetime of a single program, if this returns
/// true then it will always return true.
#[inline]
pub fn is_available() -> bool {
#[cfg(target_feature = "sse2")]
{
true
}
#[cfg(not(target_feature = "sse2"))]
{
false
}
}
/// Return the first occurrence of one of the needle bytes in the given
/// haystack. If no such occurrence exists, then `None` is returned.
///
/// The occurrence is reported as an offset into `haystack`. Its maximum
/// value is `haystack.len() - 1`.
#[inline]
pub fn find(&self, haystack: &[u8]) -> Option<usize> {
// SAFETY: `find_raw` guarantees that if a pointer is returned, it
// falls within the bounds of the start and end pointers.
unsafe {
generic::search_slice_with_raw(haystack, |s, e| {
self.find_raw(s, e)
})
}
}
/// Return the last occurrence of one of the needle bytes in the given
/// haystack. If no such occurrence exists, then `None` is returned.
///
/// The occurrence is reported as an offset into `haystack`. Its maximum
/// value is `haystack.len() - 1`.
#[inline]
pub fn rfind(&self, haystack: &[u8]) -> Option<usize> {
// SAFETY: `rfind_raw` guarantees that if a pointer is returned, it
// falls within the bounds of the start and end pointers.
unsafe {
generic::search_slice_with_raw(haystack, |s, e| {
self.rfind_raw(s, e)
})
}
}
/// Counts all occurrences of this byte in the given haystack.
#[inline]
pub fn count(&self, haystack: &[u8]) -> usize {
// SAFETY: All of our pointers are derived directly from a borrowed
// slice, which is guaranteed to be valid.
unsafe {
let start = haystack.as_ptr();
let end = start.add(haystack.len());
self.count_raw(start, end)
}
}
/// Like `find`, but accepts and returns raw pointers.
///
/// When a match is found, the pointer returned is guaranteed to be
/// `>= start` and `< end`.
///
/// This routine is useful if you're already using raw pointers and would
/// like to avoid converting back to a slice before executing a search.
///
/// # Safety
///
/// * Both `start` and `end` must be valid for reads.
/// * Both `start` and `end` must point to an initialized value.
/// * Both `start` and `end` must point to the same allocated object and
/// must either be in bounds or at most one byte past the end of the
/// allocated object.
/// * Both `start` and `end` must be _derived from_ a pointer to the same
/// object.
/// * The distance between `start` and `end` must not overflow `isize`.
/// * The distance being in bounds must not rely on "wrapping around" the
/// address space.
///
/// Note that callers may pass a pair of pointers such that `start >= end`.
/// In that case, `None` will always be returned.
#[inline]
pub unsafe fn find_raw(
&self,
start: *const u8,
end: *const u8,
) -> Option<*const u8> {
if start >= end {
return None;
}
if end.distance(start) < __m128i::BYTES {
// SAFETY: We require the caller to pass valid start/end pointers.
return generic::fwd_byte_by_byte(start, end, |b| {
b == self.0.needle1()
});
}
// SAFETY: Building a `One` means it's safe to call 'sse2' routines.
// Also, we've checked that our haystack is big enough to run on the
// vector routine. Pointer validity is caller's responsibility.
//
// Note that we could call `self.0.find_raw` directly here. But that
// means we'd have to annotate this routine with `target_feature`.
// Which is fine, because this routine is `unsafe` anyway and the
// `target_feature` obligation is met by virtue of building a `One`.
// The real problem is that a routine with a `target_feature`
// annotation generally can't be inlined into caller code unless the
// caller code has the same target feature annotations. Which is maybe
// okay for SSE2, but we do the same thing for AVX2 where caller code
// probably usually doesn't have AVX2 enabled. That means that this
// routine can be inlined which will handle some of the short-haystack
// cases above without touching the architecture specific code.
self.find_raw_impl(start, end)
}
/// Like `rfind`, but accepts and returns raw pointers.
///
/// When a match is found, the pointer returned is guaranteed to be
/// `>= start` and `< end`.
///
/// This routine is useful if you're already using raw pointers and would
/// like to avoid converting back to a slice before executing a search.
///
/// # Safety
///
/// * Both `start` and `end` must be valid for reads.
/// * Both `start` and `end` must point to an initialized value.
/// * Both `start` and `end` must point to the same allocated object and
/// must either be in bounds or at most one byte past the end of the
/// allocated object.
/// * Both `start` and `end` must be _derived from_ a pointer to the same
/// object.
/// * The distance between `start` and `end` must not overflow `isize`.
/// * The distance being in bounds must not rely on "wrapping around" the
/// address space.
///
/// Note that callers may pass a pair of pointers such that `start >= end`.
/// In that case, `None` will always be returned.
#[inline]
pub unsafe fn rfind_raw(
&self,
start: *const u8,
end: *const u8,
) -> Option<*const u8> {
if start >= end {
return None;
}
if end.distance(start) < __m128i::BYTES {
// SAFETY: We require the caller to pass valid start/end pointers.
return generic::rev_byte_by_byte(start, end, |b| {
b == self.0.needle1()
});
}
// SAFETY: Building a `One` means it's safe to call 'sse2' routines.
// Also, we've checked that our haystack is big enough to run on the
// vector routine. Pointer validity is caller's responsibility.
//
// See note in forward routine above for why we don't just call
// `self.0.rfind_raw` directly here.
self.rfind_raw_impl(start, end)
}
/// Counts all occurrences of this byte in the given haystack represented
/// by raw pointers.
///
/// This routine is useful if you're already using raw pointers and would
/// like to avoid converting back to a slice before executing a search.
///
/// # Safety
///
/// * Both `start` and `end` must be valid for reads.
/// * Both `start` and `end` must point to an initialized value.
/// * Both `start` and `end` must point to the same allocated object and
/// must either be in bounds or at most one byte past the end of the
/// allocated object.
/// * Both `start` and `end` must be _derived from_ a pointer to the same
/// object.
/// * The distance between `start` and `end` must not overflow `isize`.
/// * The distance being in bounds must not rely on "wrapping around" the
/// address space.
///
/// Note that callers may pass a pair of pointers such that `start >= end`.
/// In that case, `0` will always be returned.
#[inline]
pub unsafe fn count_raw(&self, start: *const u8, end: *const u8) -> usize {
if start >= end {
return 0;
}
if end.distance(start) < __m128i::BYTES {
// SAFETY: We require the caller to pass valid start/end pointers.
return generic::count_byte_by_byte(start, end, |b| {
b == self.0.needle1()
});
}
// SAFETY: Building a `One` means it's safe to call 'sse2' routines.
// Also, we've checked that our haystack is big enough to run on the
// vector routine. Pointer validity is caller's responsibility.
self.count_raw_impl(start, end)
}
/// Execute a search using SSE2 vectors and routines.
///
/// # Safety
///
/// Same as [`One::find_raw`], except the distance between `start` and
/// `end` must be at least the size of an SSE2 vector (in bytes).
///
/// (The target feature safety obligation is automatically fulfilled by
/// virtue of being a method on `One`, which can only be constructed
/// when it is safe to call `sse2` routines.)
#[target_feature(enable = "sse2")]
#[inline]
unsafe fn find_raw_impl(
&self,
start: *const u8,
end: *const u8,
) -> Option<*const u8> {
self.0.find_raw(start, end)
}
/// Execute a search using SSE2 vectors and routines.
///
/// # Safety
///
/// Same as [`One::rfind_raw`], except the distance between `start` and
/// `end` must be at least the size of an SSE2 vector (in bytes).
///
/// (The target feature safety obligation is automatically fulfilled by
/// virtue of being a method on `One`, which can only be constructed
/// when it is safe to call `sse2` routines.)
#[target_feature(enable = "sse2")]
#[inline]
unsafe fn rfind_raw_impl(
&self,
start: *const u8,
end: *const u8,
) -> Option<*const u8> {
self.0.rfind_raw(start, end)
}
/// Execute a count using SSE2 vectors and routines.
///
/// # Safety
///
/// Same as [`One::count_raw`], except the distance between `start` and
/// `end` must be at least the size of an SSE2 vector (in bytes).
///
/// (The target feature safety obligation is automatically fulfilled by
/// virtue of being a method on `One`, which can only be constructed
/// when it is safe to call `sse2` routines.)
#[target_feature(enable = "sse2")]
#[inline]
unsafe fn count_raw_impl(
&self,
start: *const u8,
end: *const u8,
) -> usize {
self.0.count_raw(start, end)
}
/// Returns an iterator over all occurrences of the needle byte in the
/// given haystack.
///
/// The iterator returned implements `DoubleEndedIterator`. This means it
/// can also be used to find occurrences in reverse order.
#[inline]
pub fn iter<'a, 'h>(&'a self, haystack: &'h [u8]) -> OneIter<'a, 'h> {
OneIter { searcher: self, it: generic::Iter::new(haystack) }
}
}
/// An iterator over all occurrences of a single byte in a haystack.
///
/// This iterator implements `DoubleEndedIterator`, which means it can also be
/// used to find occurrences in reverse order.
///
/// This iterator is created by the [`One::iter`] method.
///
/// The lifetime parameters are as follows:
///
/// * `'a` refers to the lifetime of the underlying [`One`] searcher.
/// * `'h` refers to the lifetime of the haystack being searched.
#[derive(Clone, Debug)]
pub struct OneIter<'a, 'h> {
searcher: &'a One,
it: generic::Iter<'h>,
}
impl<'a, 'h> Iterator for OneIter<'a, 'h> {
type Item = usize;
#[inline]
fn next(&mut self) -> Option<usize> {
// SAFETY: We rely on the generic iterator to provide valid start
// and end pointers, but we guarantee that any pointer returned by
// 'find_raw' falls within the bounds of the start and end pointer.
unsafe { self.it.next(|s, e| self.searcher.find_raw(s, e)) }
}
#[inline]
fn count(self) -> usize {
self.it.count(|s, e| {
// SAFETY: We rely on our generic iterator to return valid start
// and end pointers.
unsafe { self.searcher.count_raw(s, e) }
})
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.it.size_hint()
}
}
impl<'a, 'h> DoubleEndedIterator for OneIter<'a, 'h> {
#[inline]
fn next_back(&mut self) -> Option<usize> {
// SAFETY: We rely on the generic iterator to provide valid start
// and end pointers, but we guarantee that any pointer returned by
// 'rfind_raw' falls within the bounds of the start and end pointer.
unsafe { self.it.next_back(|s, e| self.searcher.rfind_raw(s, e)) }
}
}
impl<'a, 'h> core::iter::FusedIterator for OneIter<'a, 'h> {}
/// Finds all occurrences of two bytes in a haystack.
///
/// That is, this reports matches of one of two possible bytes. For example,
/// searching for `a` or `b` in `afoobar` would report matches at offsets `0`,
/// `4` and `5`.
#[derive(Clone, Copy, Debug)]
pub struct Two(generic::Two<__m128i>);
impl Two {
/// Create a new searcher that finds occurrences of the needle bytes given.
///
/// This particular searcher is specialized to use SSE2 vector instructions
/// that typically make it quite fast.
///
/// If SSE2 is unavailable in the current environment, then `None` is
/// returned.
#[inline]
pub fn new(needle1: u8, needle2: u8) -> Option<Two> {
if Two::is_available() {
// SAFETY: we check that sse2 is available above.
unsafe { Some(Two::new_unchecked(needle1, needle2)) }
} else {
None
}
}
/// Create a new finder specific to SSE2 vectors and routines without
/// checking that SSE2 is available.
///
/// # Safety
///
/// Callers must guarantee that it is safe to execute `sse2` instructions
/// in the current environment.
///
/// Note that it is a common misconception that if one compiles for an
/// `x86_64` target, then they therefore automatically have access to SSE2
/// instructions. While this is almost always the case, it isn't true in
/// 100% of cases.
#[target_feature(enable = "sse2")]
#[inline]
pub unsafe fn new_unchecked(needle1: u8, needle2: u8) -> Two {
Two(generic::Two::new(needle1, needle2))
}
/// Returns true when this implementation is available in the current
/// environment.
///
/// When this is true, it is guaranteed that [`Two::new`] will return
/// a `Some` value. Similarly, when it is false, it is guaranteed that
/// `Two::new` will return a `None` value.
///
/// Note also that for the lifetime of a single program, if this returns
/// true then it will always return true.
#[inline]
pub fn is_available() -> bool {
#[cfg(target_feature = "sse2")]
{
true
}
#[cfg(not(target_feature = "sse2"))]
{
false
}
}
/// Return the first occurrence of one of the needle bytes in the given
/// haystack. If no such occurrence exists, then `None` is returned.
///
/// The occurrence is reported as an offset into `haystack`. Its maximum
/// value is `haystack.len() - 1`.
#[inline]
pub fn find(&self, haystack: &[u8]) -> Option<usize> {
// SAFETY: `find_raw` guarantees that if a pointer is returned, it
// falls within the bounds of the start and end pointers.
unsafe {
generic::search_slice_with_raw(haystack, |s, e| {
self.find_raw(s, e)
})
}
}
/// Return the last occurrence of one of the needle bytes in the given
/// haystack. If no such occurrence exists, then `None` is returned.
///
/// The occurrence is reported as an offset into `haystack`. Its maximum
/// value is `haystack.len() - 1`.
#[inline]
pub fn rfind(&self, haystack: &[u8]) -> Option<usize> {
// SAFETY: `rfind_raw` guarantees that if a pointer is returned, it
// falls within the bounds of the start and end pointers.
unsafe {
generic::search_slice_with_raw(haystack, |s, e| {
self.rfind_raw(s, e)
})
}
}
/// Like `find`, but accepts and returns raw pointers.
///
/// When a match is found, the pointer returned is guaranteed to be
/// `>= start` and `< end`.
///
/// This routine is useful if you're already using raw pointers and would
/// like to avoid converting back to a slice before executing a search.
///
/// # Safety
///
/// * Both `start` and `end` must be valid for reads.
/// * Both `start` and `end` must point to an initialized value.
/// * Both `start` and `end` must point to the same allocated object and
/// must either be in bounds or at most one byte past the end of the
/// allocated object.
/// * Both `start` and `end` must be _derived from_ a pointer to the same
/// object.
/// * The distance between `start` and `end` must not overflow `isize`.
/// * The distance being in bounds must not rely on "wrapping around" the
/// address space.
///
/// Note that callers may pass a pair of pointers such that `start >= end`.
/// In that case, `None` will always be returned.
#[inline]
pub unsafe fn find_raw(
&self,
start: *const u8,
end: *const u8,
) -> Option<*const u8> {
if start >= end {
return None;
}
if end.distance(start) < __m128i::BYTES {
// SAFETY: We require the caller to pass valid start/end pointers.
return generic::fwd_byte_by_byte(start, end, |b| {
b == self.0.needle1() || b == self.0.needle2()
});
}
// SAFETY: Building a `Two` means it's safe to call 'sse2' routines.
// Also, we've checked that our haystack is big enough to run on the
// vector routine. Pointer validity is caller's responsibility.
//
// Note that we could call `self.0.find_raw` directly here. But that
// means we'd have to annotate this routine with `target_feature`.
// Which is fine, because this routine is `unsafe` anyway and the
// `target_feature` obligation is met by virtue of building a `Two`.
// The real problem is that a routine with a `target_feature`
// annotation generally can't be inlined into caller code unless the
// caller code has the same target feature annotations. Which is maybe
// okay for SSE2, but we do the same thing for AVX2 where caller code
// probably usually doesn't have AVX2 enabled. That means that this
// routine can be inlined which will handle some of the short-haystack
// cases above without touching the architecture specific code.
self.find_raw_impl(start, end)
}
/// Like `rfind`, but accepts and returns raw pointers.
///
/// When a match is found, the pointer returned is guaranteed to be
/// `>= start` and `< end`.
///
/// This routine is useful if you're already using raw pointers and would
/// like to avoid converting back to a slice before executing a search.
///
/// # Safety
///
/// * Both `start` and `end` must be valid for reads.
/// * Both `start` and `end` must point to an initialized value.
/// * Both `start` and `end` must point to the same allocated object and
/// must either be in bounds or at most one byte past the end of the
/// allocated object.
/// * Both `start` and `end` must be _derived from_ a pointer to the same
/// object.
/// * The distance between `start` and `end` must not overflow `isize`.
/// * The distance being in bounds must not rely on "wrapping around" the
/// address space.
///
/// Note that callers may pass a pair of pointers such that `start >= end`.
/// In that case, `None` will always be returned.
#[inline]
pub unsafe fn rfind_raw(
&self,
start: *const u8,
end: *const u8,
) -> Option<*const u8> {
if start >= end {
return None;
}
if end.distance(start) < __m128i::BYTES {
// SAFETY: We require the caller to pass valid start/end pointers.
return generic::rev_byte_by_byte(start, end, |b| {
b == self.0.needle1() || b == self.0.needle2()
});
}
// SAFETY: Building a `Two` means it's safe to call 'sse2' routines.
// Also, we've checked that our haystack is big enough to run on the
// vector routine. Pointer validity is caller's responsibility.
//
// See note in forward routine above for why we don't just call
// `self.0.rfind_raw` directly here.
self.rfind_raw_impl(start, end)
}
/// Execute a search using SSE2 vectors and routines.
///
/// # Safety
///
/// Same as [`Two::find_raw`], except the distance between `start` and
/// `end` must be at least the size of an SSE2 vector (in bytes).
///
/// (The target feature safety obligation is automatically fulfilled by
/// virtue of being a method on `Two`, which can only be constructed
/// when it is safe to call `sse2` routines.)
#[target_feature(enable = "sse2")]
#[inline]
unsafe fn find_raw_impl(
&self,
start: *const u8,
end: *const u8,
) -> Option<*const u8> {
self.0.find_raw(start, end)
}
/// Execute a search using SSE2 vectors and routines.
///
/// # Safety
///
/// Same as [`Two::rfind_raw`], except the distance between `start` and
/// `end` must be at least the size of an SSE2 vector (in bytes).
///
/// (The target feature safety obligation is automatically fulfilled by
/// virtue of being a method on `Two`, which can only be constructed
/// when it is safe to call `sse2` routines.)
#[target_feature(enable = "sse2")]
#[inline]
unsafe fn rfind_raw_impl(
&self,
start: *const u8,
end: *const u8,
) -> Option<*const u8> {
self.0.rfind_raw(start, end)
}
/// Returns an iterator over all occurrences of the needle bytes in the
/// given haystack.
///
/// The iterator returned implements `DoubleEndedIterator`. This means it
/// can also be used to find occurrences in reverse order.
#[inline]
pub fn iter<'a, 'h>(&'a self, haystack: &'h [u8]) -> TwoIter<'a, 'h> {
TwoIter { searcher: self, it: generic::Iter::new(haystack) }
}
}
/// An iterator over all occurrences of two possible bytes in a haystack.
///
/// This iterator implements `DoubleEndedIterator`, which means it can also be
/// used to find occurrences in reverse order.
///
/// This iterator is created by the [`Two::iter`] method.
///
/// The lifetime parameters are as follows:
///
/// * `'a` refers to the lifetime of the underlying [`Two`] searcher.
/// * `'h` refers to the lifetime of the haystack being searched.
#[derive(Clone, Debug)]
pub struct TwoIter<'a, 'h> {
searcher: &'a Two,
it: generic::Iter<'h>,
}
impl<'a, 'h> Iterator for TwoIter<'a, 'h> {
type Item = usize;
#[inline]
fn next(&mut self) -> Option<usize> {
// SAFETY: We rely on the generic iterator to provide valid start
// and end pointers, but we guarantee that any pointer returned by
// 'find_raw' falls within the bounds of the start and end pointer.
unsafe { self.it.next(|s, e| self.searcher.find_raw(s, e)) }
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.it.size_hint()
}
}
impl<'a, 'h> DoubleEndedIterator for TwoIter<'a, 'h> {
#[inline]
fn next_back(&mut self) -> Option<usize> {
// SAFETY: We rely on the generic iterator to provide valid start
// and end pointers, but we guarantee that any pointer returned by
// 'rfind_raw' falls within the bounds of the start and end pointer.
unsafe { self.it.next_back(|s, e| self.searcher.rfind_raw(s, e)) }
}
}
impl<'a, 'h> core::iter::FusedIterator for TwoIter<'a, 'h> {}
/// Finds all occurrences of three bytes in a haystack.
///
/// That is, this reports matches of one of three possible bytes. For example,
/// searching for `a`, `b` or `o` in `afoobar` would report matches at offsets
/// `0`, `2`, `3`, `4` and `5`.
#[derive(Clone, Copy, Debug)]
pub struct Three(generic::Three<__m128i>);
impl Three {
/// Create a new searcher that finds occurrences of the needle bytes given.
///
/// This particular searcher is specialized to use SSE2 vector instructions
/// that typically make it quite fast.
///
/// If SSE2 is unavailable in the current environment, then `None` is
/// returned.
#[inline]
pub fn new(needle1: u8, needle2: u8, needle3: u8) -> Option<Three> {
if Three::is_available() {
// SAFETY: we check that sse2 is available above.
unsafe { Some(Three::new_unchecked(needle1, needle2, needle3)) }
} else {
None
}
}
/// Create a new finder specific to SSE2 vectors and routines without
/// checking that SSE2 is available.
///
/// # Safety
///
/// Callers must guarantee that it is safe to execute `sse2` instructions
/// in the current environment.
///
/// Note that it is a common misconception that if one compiles for an
/// `x86_64` target, then they therefore automatically have access to SSE2
/// instructions. While this is almost always the case, it isn't true in
/// 100% of cases.
#[target_feature(enable = "sse2")]
#[inline]
pub unsafe fn new_unchecked(
needle1: u8,
needle2: u8,
needle3: u8,
) -> Three {
Three(generic::Three::new(needle1, needle2, needle3))
}
/// Returns true when this implementation is available in the current
/// environment.
///
/// When this is true, it is guaranteed that [`Three::new`] will return
/// a `Some` value. Similarly, when it is false, it is guaranteed that
/// `Three::new` will return a `None` value.
///
/// Note also that for the lifetime of a single program, if this returns
/// true then it will always return true.
#[inline]
pub fn is_available() -> bool {
#[cfg(target_feature = "sse2")]
{
true
}
#[cfg(not(target_feature = "sse2"))]
{
false
}
}
/// Return the first occurrence of one of the needle bytes in the given
/// haystack. If no such occurrence exists, then `None` is returned.
///
/// The occurrence is reported as an offset into `haystack`. Its maximum
/// value is `haystack.len() - 1`.
#[inline]
pub fn find(&self, haystack: &[u8]) -> Option<usize> {
// SAFETY: `find_raw` guarantees that if a pointer is returned, it
// falls within the bounds of the start and end pointers.
unsafe {
generic::search_slice_with_raw(haystack, |s, e| {
self.find_raw(s, e)
})
}
}
/// Return the last occurrence of one of the needle bytes in the given
/// haystack. If no such occurrence exists, then `None` is returned.
///
/// The occurrence is reported as an offset into `haystack`. Its maximum
/// value is `haystack.len() - 1`.
#[inline]
pub fn rfind(&self, haystack: &[u8]) -> Option<usize> {
// SAFETY: `rfind_raw` guarantees that if a pointer is returned, it
// falls within the bounds of the start and end pointers.
unsafe {
generic::search_slice_with_raw(haystack, |s, e| {
self.rfind_raw(s, e)
})
}
}
/// Like `find`, but accepts and returns raw pointers.
///
/// When a match is found, the pointer returned is guaranteed to be
/// `>= start` and `< end`.
///
/// This routine is useful if you're already using raw pointers and would
/// like to avoid converting back to a slice before executing a search.
///
/// # Safety
///
/// * Both `start` and `end` must be valid for reads.
/// * Both `start` and `end` must point to an initialized value.
/// * Both `start` and `end` must point to the same allocated object and
/// must either be in bounds or at most one byte past the end of the
/// allocated object.
/// * Both `start` and `end` must be _derived from_ a pointer to the same
/// object.
/// * The distance between `start` and `end` must not overflow `isize`.
/// * The distance being in bounds must not rely on "wrapping around" the
/// address space.
///
/// Note that callers may pass a pair of pointers such that `start >= end`.
/// In that case, `None` will always be returned.
#[inline]
pub unsafe fn find_raw(
&self,
start: *const u8,
end: *const u8,
) -> Option<*const u8> {
if start >= end {
return None;
}
if end.distance(start) < __m128i::BYTES {
// SAFETY: We require the caller to pass valid start/end pointers.
return generic::fwd_byte_by_byte(start, end, |b| {
b == self.0.needle1()
|| b == self.0.needle2()
|| b == self.0.needle3()
});
}
// SAFETY: Building a `Three` means it's safe to call 'sse2' routines.
// Also, we've checked that our haystack is big enough to run on the
// vector routine. Pointer validity is caller's responsibility.
//
// Note that we could call `self.0.find_raw` directly here. But that
// means we'd have to annotate this routine with `target_feature`.
// Which is fine, because this routine is `unsafe` anyway and the
// `target_feature` obligation is met by virtue of building a `Three`.
// The real problem is that a routine with a `target_feature`
// annotation generally can't be inlined into caller code unless the
// caller code has the same target feature annotations. Which is maybe
// okay for SSE2, but we do the same thing for AVX2 where caller code
// probably usually doesn't have AVX2 enabled. That means that this
// routine can be inlined which will handle some of the short-haystack
// cases above without touching the architecture specific code.
self.find_raw_impl(start, end)
}
/// Like `rfind`, but accepts and returns raw pointers.
///
/// When a match is found, the pointer returned is guaranteed to be
/// `>= start` and `< end`.
///
/// This routine is useful if you're already using raw pointers and would
/// like to avoid converting back to a slice before executing a search.
///
/// # Safety
///
/// * Both `start` and `end` must be valid for reads.
/// * Both `start` and `end` must point to an initialized value.
/// * Both `start` and `end` must point to the same allocated object and
/// must either be in bounds or at most one byte past the end of the
/// allocated object.
/// * Both `start` and `end` must be _derived from_ a pointer to the same
/// object.
/// * The distance between `start` and `end` must not overflow `isize`.
/// * The distance being in bounds must not rely on "wrapping around" the
/// address space.
///
/// Note that callers may pass a pair of pointers such that `start >= end`.
/// In that case, `None` will always be returned.
#[inline]
pub unsafe fn rfind_raw(
&self,
start: *const u8,
end: *const u8,
) -> Option<*const u8> {
if start >= end {
return None;
}
if end.distance(start) < __m128i::BYTES {
// SAFETY: We require the caller to pass valid start/end pointers.
return generic::rev_byte_by_byte(start, end, |b| {
b == self.0.needle1()
|| b == self.0.needle2()
|| b == self.0.needle3()
});
}
// SAFETY: Building a `Three` means it's safe to call 'sse2' routines.
// Also, we've checked that our haystack is big enough to run on the
// vector routine. Pointer validity is caller's responsibility.
//
// See note in forward routine above for why we don't just call
// `self.0.rfind_raw` directly here.
self.rfind_raw_impl(start, end)
}
/// Execute a search using SSE2 vectors and routines.
///
/// # Safety
///
/// Same as [`Three::find_raw`], except the distance between `start` and
/// `end` must be at least the size of an SSE2 vector (in bytes).
///
/// (The target feature safety obligation is automatically fulfilled by
/// virtue of being a method on `Three`, which can only be constructed
/// when it is safe to call `sse2` routines.)
#[target_feature(enable = "sse2")]
#[inline]
unsafe fn find_raw_impl(
&self,
start: *const u8,
end: *const u8,
) -> Option<*const u8> {
self.0.find_raw(start, end)
}
/// Execute a search using SSE2 vectors and routines.
///
/// # Safety
///
/// Same as [`Three::rfind_raw`], except the distance between `start` and
/// `end` must be at least the size of an SSE2 vector (in bytes).
///
/// (The target feature safety obligation is automatically fulfilled by
/// virtue of being a method on `Three`, which can only be constructed
/// when it is safe to call `sse2` routines.)
#[target_feature(enable = "sse2")]
#[inline]
unsafe fn rfind_raw_impl(
&self,
start: *const u8,
end: *const u8,
) -> Option<*const u8> {
self.0.rfind_raw(start, end)
}
/// Returns an iterator over all occurrences of the needle byte in the
/// given haystack.
///
/// The iterator returned implements `DoubleEndedIterator`. This means it
/// can also be used to find occurrences in reverse order.
#[inline]
pub fn iter<'a, 'h>(&'a self, haystack: &'h [u8]) -> ThreeIter<'a, 'h> {
ThreeIter { searcher: self, it: generic::Iter::new(haystack) }
}
}
/// An iterator over all occurrences of three possible bytes in a haystack.
///
/// This iterator implements `DoubleEndedIterator`, which means it can also be
/// used to find occurrences in reverse order.
///
/// This iterator is created by the [`Three::iter`] method.
///
/// The lifetime parameters are as follows:
///
/// * `'a` refers to the lifetime of the underlying [`Three`] searcher.
/// * `'h` refers to the lifetime of the haystack being searched.
#[derive(Clone, Debug)]
pub struct ThreeIter<'a, 'h> {
searcher: &'a Three,
it: generic::Iter<'h>,
}
impl<'a, 'h> Iterator for ThreeIter<'a, 'h> {
type Item = usize;
#[inline]
fn next(&mut self) -> Option<usize> {
// SAFETY: We rely on the generic iterator to provide valid start
// and end pointers, but we guarantee that any pointer returned by
// 'find_raw' falls within the bounds of the start and end pointer.
unsafe { self.it.next(|s, e| self.searcher.find_raw(s, e)) }
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.it.size_hint()
}
}
impl<'a, 'h> DoubleEndedIterator for ThreeIter<'a, 'h> {
#[inline]
fn next_back(&mut self) -> Option<usize> {
// SAFETY: We rely on the generic iterator to provide valid start
// and end pointers, but we guarantee that any pointer returned by
// 'rfind_raw' falls within the bounds of the start and end pointer.
unsafe { self.it.next_back(|s, e| self.searcher.rfind_raw(s, e)) }
}
}
impl<'a, 'h> core::iter::FusedIterator for ThreeIter<'a, 'h> {}
#[cfg(test)]
mod tests {
use super::*;
define_memchr_quickcheck!(super);
#[test]
fn forward_one() {
crate::tests::memchr::Runner::new(1).forward_iter(
|haystack, needles| {
Some(One::new(needles[0])?.iter(haystack).collect())
},
)
}
#[test]
fn reverse_one() {
crate::tests::memchr::Runner::new(1).reverse_iter(
|haystack, needles| {
Some(One::new(needles[0])?.iter(haystack).rev().collect())
},
)
}
#[test]
fn count_one() {
crate::tests::memchr::Runner::new(1).count_iter(|haystack, needles| {
Some(One::new(needles[0])?.iter(haystack).count())
})
}
#[test]
fn forward_two() {
crate::tests::memchr::Runner::new(2).forward_iter(
|haystack, needles| {
let n1 = needles.get(0).copied()?;
let n2 = needles.get(1).copied()?;
Some(Two::new(n1, n2)?.iter(haystack).collect())
},
)
}
#[test]
fn reverse_two() {
crate::tests::memchr::Runner::new(2).reverse_iter(
|haystack, needles| {
let n1 = needles.get(0).copied()?;
let n2 = needles.get(1).copied()?;
Some(Two::new(n1, n2)?.iter(haystack).rev().collect())
},
)
}
#[test]
fn forward_three() {
crate::tests::memchr::Runner::new(3).forward_iter(
|haystack, needles| {
let n1 = needles.get(0).copied()?;
let n2 = needles.get(1).copied()?;
let n3 = needles.get(2).copied()?;
Some(Three::new(n1, n2, n3)?.iter(haystack).collect())
},
)
}
#[test]
fn reverse_three() {
crate::tests::memchr::Runner::new(3).reverse_iter(
|haystack, needles| {
let n1 = needles.get(0).copied()?;
let n2 = needles.get(1).copied()?;
let n3 = needles.get(2).copied()?;
Some(Three::new(n1, n2, n3)?.iter(haystack).rev().collect())
},
)
}
}
|