Skip to main content

git_pack_delta/
match_bytes.rs

1//! SIMD accelerated utilities for counting the number of matching bytes from the start of two slices.
2
3#[allow(unused_imports)]
4#[cfg(target_arch = "x86")]
5use core::arch::x86::*;
6#[allow(unused_imports)]
7#[cfg(target_arch = "x86_64")]
8use core::arch::x86_64::*;
9
10// TODO: try returning u32 on all paths
11
12/// Counts the number of matching bytes from the start of two slices.
13/// ```
14/// let i = git_pack_delta::match_bytes::count_matches(b"Hello, World!", b"Hello, world!");
15/// assert_eq!(i, 7);
16/// ```
17#[inline(always)]
18pub fn count_matches(a: &[u8], b: &[u8]) -> usize {
19    cfg_select! {
20        target_feature = "avx512bw" => unsafe { count_matches_avx512bw(a, b) },
21        target_feature = "avx2" => unsafe { count_matches_avx2(a, b) },
22        target_feature = "sse2" => unsafe { count_matches_sse2(a, b) },
23        _ => count_matches_u128(a, b),
24    }
25}
26
27/// Fallback implementation for when the remaining bytes do not fit into a full word.
28#[inline]
29fn count_matches_u8(a: &[u8], b: &[u8]) -> usize {
30    a.iter().zip(b).take_while(|(x, y)| **x == **y).count()
31}
32
33#[inline]
34pub fn count_matches_rev(a: &[u8], b: &[u8], n: usize) -> usize {
35    a.iter()
36        .rev()
37        .zip(b.iter().rev())
38        .take(n)
39        .take_while(|(x, y)| **x == **y)
40        .count()
41}
42
43trait NumWord: Sized {
44    const SIZE: usize = core::mem::size_of::<Self>();
45    unsafe fn from_ne_slice(bytes: &[u8]) -> Self;
46    // both methods must be "unsafe" to use #[target_feature]
47    unsafe fn count_matches(a: Self, b: Self) -> Option<usize>;
48}
49
50impl NumWord for u128 {
51    // The compiler should translate this into SIMD instructions (if available)
52    #[inline]
53    unsafe fn from_ne_slice(bytes: &[u8]) -> Self {
54        debug_assert!(bytes.len() >= Self::SIZE);
55        let array = unsafe { bytes[..Self::SIZE].try_into().unwrap_unchecked() };
56        Self::from_ne_bytes(array)
57    }
58    #[inline]
59    unsafe fn count_matches(a: Self, b: Self) -> Option<usize> {
60        let c = a ^ b;
61        if c != 0 {
62            let z = cfg_select! {
63                target_endian = "little" => c.trailing_zeros(),
64                _ => c.leading_zeros(),
65            };
66            Some({ z / 8 } as usize)
67        } else {
68            None
69        }
70    }
71}
72
73#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
74impl NumWord for __m128i {
75    #[inline]
76    #[target_feature(enable = "sse2")]
77    unsafe fn from_ne_slice(bytes: &[u8]) -> Self {
78        debug_assert!(bytes.len() >= Self::SIZE);
79        #[cfg(target_feature = "sse3")]
80        unsafe {
81            _mm_lddqu_si128(bytes.as_ptr() as _)
82        }
83        #[cfg(not(target_feature = "sse3"))]
84        unsafe {
85            _mm_loadu_si128(bytes.as_ptr() as _)
86        }
87    }
88    #[inline]
89    #[target_feature(enable = "sse2")]
90    unsafe fn count_matches(a: Self, b: Self) -> Option<usize> {
91        let c = _mm_cmpeq_epi8(a, b);
92        let c = _mm_movemask_epi8(c);
93        if c != 0xffff {
94            return Some(c.trailing_ones() as usize);
95        }
96        None
97    }
98}
99
100#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
101impl NumWord for __m256i {
102    #[inline]
103    #[target_feature(enable = "avx2")]
104    unsafe fn from_ne_slice(bytes: &[u8]) -> Self {
105        debug_assert!(bytes.len() >= Self::SIZE);
106        unsafe { _mm256_lddqu_si256(bytes.as_ptr() as _) }
107    }
108    #[inline]
109    #[target_feature(enable = "avx2")]
110    unsafe fn count_matches(a: Self, b: Self) -> Option<usize> {
111        #[cfg(all(target_feature = "avx512bw", target_feature = "avx512vl"))]
112        unsafe {
113            let c = _mm256_cmpneq_epu8_mask(a, b);
114            if c != 0 {
115                return Some(c.trailing_zeros() as usize);
116            }
117        }
118        #[cfg(not(all(target_feature = "avx512bw", target_feature = "avx512vl")))]
119        {
120            let c = _mm256_cmpeq_epi8(a, b);
121            let c = _mm256_movemask_epi8(c);
122            if c != -1 {
123                return Some(c.trailing_ones() as usize);
124            }
125        }
126        None
127    }
128}
129
130#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
131impl NumWord for __m512i {
132    #[inline]
133    #[target_feature(enable = "avx512bw")]
134    unsafe fn from_ne_slice(bytes: &[u8]) -> Self {
135        debug_assert!(bytes.len() >= Self::SIZE);
136        #[cfg(target_feature = "avx512f")]
137        unsafe {
138            _mm512_loadu_si512(bytes.as_ptr() as _)
139        }
140        #[cfg(not(target_feature = "avx512f"))]
141        unsafe {
142            _mm512_loadu_epi8(bytes.as_ptr() as _)
143        }
144    }
145    #[inline]
146    #[target_feature(enable = "avx512bw")]
147    unsafe fn count_matches(a: Self, b: Self) -> Option<usize> {
148        let c = _mm512_cmpneq_epu8_mask(a, b);
149        if c != 0 {
150            return Some(c.trailing_zeros() as usize);
151        }
152        None
153    }
154}
155
156#[allow(unused)]
157pub fn count_matches_u128(a: &[u8], b: &[u8]) -> usize {
158    count_matches_word::<u128>(a, b)
159}
160
161/// # Safety
162/// UB if the CPU does not support SSE2.
163#[allow(unused)]
164#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
165#[target_feature(enable = "sse2")]
166pub unsafe fn count_matches_sse2(a: &[u8], b: &[u8]) -> usize {
167    count_matches_word::<__m128i>(a, b)
168}
169
170/// # Safety
171/// UB if the CPU does not support AVX2.
172#[allow(unused)]
173#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
174#[target_feature(enable = "avx2")]
175pub unsafe fn count_matches_avx2(a: &[u8], b: &[u8]) -> usize {
176    count_matches_word::<__m256i>(a, b)
177}
178
179/// # Safety
180/// UB if the CPU does not support AVX512BW.
181#[allow(unused)]
182#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
183#[target_feature(enable = "avx512bw")]
184pub unsafe fn count_matches_avx512bw(a: &[u8], b: &[u8]) -> usize {
185    count_matches_word::<__m512i>(a, b)
186}
187
188#[inline(always)]
189fn count_matches_word<T: NumWord>(a: &[u8], b: &[u8]) -> usize {
190    let max = a.len().min(b.len());
191    let mut a = &a[..max];
192    let mut b = &b[..max];
193    let mut i = 0;
194    while a.len() >= T::SIZE {
195        unsafe {
196            let a = T::from_ne_slice(&a[..T::SIZE]);
197            let b = T::from_ne_slice(&b[..T::SIZE]);
198            if let Some(m) = T::count_matches(a, b) {
199                return i + m;
200            }
201        }
202        a = &a[T::SIZE..];
203        b = &b[T::SIZE..];
204        i += T::SIZE;
205    }
206    i + count_matches_u8(a, b)
207}
208
209#[cfg(test)]
210mod tests {
211    use super::*;
212    // use yare::parameterized; // can't use yare here since some of the functions are conditionally compiled
213
214    #[test]
215    fn test_count_matches_u8() {
216        test_count_matches(count_matches_u8);
217    }
218
219    #[test]
220    fn test_count_matches_u128() {
221        test_count_matches(count_matches_u128);
222    }
223
224    #[test]
225    #[cfg(target_feature = "sse2")]
226    fn test_count_matches_sse2() {
227        test_count_matches(count_matches_sse2);
228    }
229
230    #[test]
231    #[cfg(target_feature = "avx2")]
232    fn test_count_matches_avx2() {
233        test_count_matches(count_matches_avx2);
234    }
235
236    #[test]
237    #[cfg(target_feature = "avx512bw")]
238    fn test_count_matches_avx512bw() {
239        test_count_matches(count_matches_avx512bw);
240    }
241
242    fn test_count_matches(count: unsafe fn(&[u8], &[u8]) -> usize) {
243        unsafe {
244            assert_eq!(count(b"hello", b"hello"), 5);
245            assert_eq!(count(b"hello", b"world"), 0);
246            assert_eq!(count(b"hello", b"help"), 3);
247            assert_eq!(count(b"", b"hello"), 0);
248            assert_eq!(count(b"hello", b""), 0);
249        }
250
251        for _ in 0..1000 {
252            let size = rand::random_range(1..=1024);
253            let mut buf = vec![0u8; size];
254            rand::fill(&mut buf);
255            let mut buf2 = buf.clone();
256            let ixd = rand::random_range(0..buf2.len());
257            buf2[ixd] ^= 0xFF; // modify one byte
258            let match_len = unsafe { count(&buf, &buf2) };
259            assert_eq!(match_len, ixd);
260        }
261    }
262
263    #[test]
264    fn test_count_matches_rev() {
265        assert_eq!(count_matches_rev(b"hello", b"hello", 10), 5);
266        assert_eq!(count_matches_rev(b"hello", b"world", 10), 0);
267        assert_eq!(count_matches_rev(b"hello", b"jello", 10), 4);
268        assert_eq!(count_matches_rev(b"hello", b"jello", 2), 2);
269        assert_eq!(count_matches_rev(b"world!", b"hello, world!", 7), 6);
270        assert_eq!(count_matches_rev(b"world!", b"hello, world!", 4), 4);
271        assert_eq!(count_matches_rev(b"hello, world!", b"world!", 7), 6);
272        assert_eq!(count_matches_rev(b"hello, world!", b"world!", 4), 4);
273        assert_eq!(count_matches_rev(b"", b"hello", 10), 0);
274        assert_eq!(count_matches_rev(b"hello", b"", 10), 0);
275
276        for _ in 0..1000 {
277            let size = rand::random_range(1..=1024);
278            let mut buf = vec![0u8; size];
279            rand::fill(&mut buf);
280            let mut buf2 = buf.clone();
281            let ixd = rand::random_range(0..buf2.len());
282            buf2[ixd] ^= 0xFF; // modify one byte
283            let match_len = count_matches_rev(&buf, &buf2, size);
284            assert_eq!(match_len, size - ixd - 1);
285        }
286    }
287}