Skip to main content

writerslogic_warm/core/
intersection.rs

1// Copyright 2024-2026 WritersLogic Contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Sparse intersection primitives.
5//!
6//! Galloping intersection for skewed sizes, sorted merge for balanced.
7
8/// Count common elements in two sorted u32 slices.
9///
10/// Adaptively picks the best algorithm:
11/// - When one slice is much smaller (|a| * 8 < |b|), uses galloping search
12///   which is O(|small| * log(|large|)) and beats O(|a| + |b|) merge.
13/// - Otherwise uses the standard sorted merge at O(|a| + |b|).
14#[inline]
15pub fn sparse_intersection_count(a: &[u32], b: &[u32]) -> usize {
16    if a.is_empty() || b.is_empty() {
17        return 0;
18    }
19
20    let (small, large) = if a.len() <= b.len() { (a, b) } else { (b, a) };
21    // Skewed sizes gallop before any block kernel: a block kernel walks the
22    // large side linearly.
23    if small.len() * 8 < large.len() {
24        return galloping_intersection_count(small, large);
25    }
26
27    #[cfg(target_arch = "x86_64")]
28    if let Some(count) = crate::core::simd_math::simd_intersection_count(small, large) {
29        return count;
30    }
31
32    merge_intersection_count(small, large)
33}
34
35/// Sorted merge intersection count: O(|a| + |b|).
36#[inline]
37fn merge_intersection_count(a: &[u32], b: &[u32]) -> usize {
38    let mut count = 0;
39    let mut i = 0;
40    let mut j = 0;
41    while i < a.len() && j < b.len() {
42        match a[i].cmp(&b[j]) {
43            std::cmp::Ordering::Less => i += 1,
44            std::cmp::Ordering::Greater => j += 1,
45            std::cmp::Ordering::Equal => {
46                count += 1;
47                i += 1;
48                j += 1;
49            }
50        }
51    }
52    count
53}
54
55/// Galloping (exponential search) intersection: O(|small| * log(|large|)).
56///
57/// For each element in `small`, does an exponential search in `large` to find
58/// the matching position. Maintains a cursor into `large` so total work on
59/// the large array is bounded by O(|small| * log(|large|/|small|)).
60#[inline]
61fn galloping_intersection_count(small: &[u32], large: &[u32]) -> usize {
62    let mut count = 0;
63    let mut lo = 0; // cursor into large; advances monotonically
64    for &val in small {
65        let mut step = 1;
66        while lo + step < large.len() && large[lo + step] < val {
67            step *= 2;
68        }
69        let hi = (lo + step).min(large.len());
70        lo = binary_search_left(&large[lo..hi], val) + lo;
71        if lo < large.len() && large[lo] == val {
72            count += 1;
73            lo += 1; // move past this match
74        }
75    }
76    count
77}
78
79/// Binary search for the leftmost position where `slice[pos] >= target`.
80#[inline]
81fn binary_search_left(slice: &[u32], target: u32) -> usize {
82    let mut lo = 0;
83    let mut hi = slice.len();
84    while lo < hi {
85        let mid = lo + (hi - lo) / 2;
86        if slice[mid] < target {
87            lo = mid + 1;
88        } else {
89            hi = mid;
90        }
91    }
92    lo
93}
94
95#[cfg(test)]
96mod tests {
97    use super::*;
98
99    fn naive(a: &[u32], b: &[u32]) -> usize {
100        let set: std::collections::HashSet<u32> = b.iter().copied().collect();
101        a.iter().filter(|x| set.contains(x)).count()
102    }
103
104    struct Lcg(u64);
105    impl Lcg {
106        fn next(&mut self) -> u64 {
107            self.0 = self
108                .0
109                .wrapping_mul(6364136223846793005)
110                .wrapping_add(1442695040888963407);
111            self.0 >> 33
112        }
113    }
114
115    /// Sorted, deduplicated sample of `n` values below `universe` (`universe >= n`).
116    fn sample(rng: &mut Lcg, n: usize, universe: u64) -> Vec<u32> {
117        let mut set = std::collections::BTreeSet::new();
118        while set.len() < n {
119            set.insert((rng.next() % universe) as u32);
120        }
121        set.into_iter().collect()
122    }
123
124    fn check_all(a: &[u32], b: &[u32]) {
125        let want = naive(a, b);
126        assert_eq!(sparse_intersection_count(a, b), want, "dispatch a,b");
127        assert_eq!(sparse_intersection_count(b, a), want, "dispatch b,a");
128        assert_eq!(merge_intersection_count(a, b), want, "merge");
129        let (small, large) = if a.len() <= b.len() { (a, b) } else { (b, a) };
130        assert_eq!(galloping_intersection_count(small, large), want, "gallop");
131        #[cfg(target_arch = "x86_64")]
132        if let Some(c) = crate::core::simd_math::simd_intersection_count(a, b) {
133            assert_eq!(c, want, "avx2");
134        }
135    }
136
137    #[test]
138    fn all_kernels_match_naive_count() {
139        for seed in 0..300u64 {
140            let mut rng = Lcg(seed);
141            let na = (rng.next() % 2001) as usize;
142            let nb = (rng.next() % 2001) as usize;
143            // A universe near max(na, nb) forces heavy overlap; a wide one forces little.
144            let universe = (na.max(nb) as u64 + 1) * (1 + rng.next() % 8);
145            check_all(
146                &sample(&mut rng, na, universe),
147                &sample(&mut rng, nb, universe),
148            );
149        }
150    }
151
152    #[test]
153    fn kernels_match_on_edge_shapes_and_tails() {
154        let mut rng = Lcg(7);
155        for na in 0..=17usize {
156            for nb in (0..=17usize).chain([64, 65, 600]) {
157                for universe in [40u64, 2000, 1 << 20] {
158                    let universe = universe.max(na.max(nb) as u64);
159                    check_all(
160                        &sample(&mut rng, na, universe),
161                        &sample(&mut rng, nb, universe),
162                    );
163                }
164            }
165        }
166        let ident = sample(&mut rng, 777, 5000);
167        check_all(&ident, &ident);
168        let evens: Vec<u32> = (0..1000).map(|x| x * 2).collect();
169        let odds: Vec<u32> = (0..1000).map(|x| x * 2 + 1).collect();
170        check_all(&evens, &odds);
171        check_all(&[], &odds);
172        check_all(&[], &[]);
173    }
174}