Skip to main content

primal_crossbeam/
lib.rs

1use crossbeam_channel::{bounded, unbounded, Receiver, Sender};
2use primal::{estimate_prime_pi, Primes, Sieve};
3use std::thread;
4
5pub fn thread_spawn<T>(
6    result: (impl FnOnce() + Send + 'static, T),
7) -> (thread::JoinHandle<()>, T) {
8    let (f, x) = result;
9    (thread::spawn(f), x)
10}
11
12fn from_iterator<'a, T: Send + 'a>(
13    it: impl Iterator<Item = T> + Send + 'a,
14    s: Sender<T>,
15    r: Receiver<T>,
16) -> (impl FnOnce() + Send + 'a, Receiver<T>) {
17    (
18        move || {
19            for x in it {
20                if s.send(x).is_err() {
21                    return;
22                }
23            }
24        },
25        r,
26    )
27}
28
29fn from_iterator_unbounded<'a, T: Send + 'a>(
30    it: impl Iterator<Item = T> + Send + 'a,
31) -> (impl FnOnce() + Send + 'a, Receiver<T>) {
32    let (s, r) = unbounded::<T>();
33    from_iterator(it, s, r)
34}
35
36/// Assumes that `it` has at most `bound` values.
37fn from_iterator_bounded<'a, T: Send + 'a>(
38    it: impl Iterator<Item = T> + Send + 'a,
39    bound: usize,
40) -> (impl FnOnce() + 'a, Receiver<T>) {
41    let (s, r) = bounded::<T>(bound);
42    from_iterator(it, s, r)
43}
44
45/// ```
46/// # use primal_crossbeam::*;
47/// # use std::thread;
48/// let (thread, r) = thread_spawn(primes_unbounded());
49/// assert_eq!(r.recv(), Ok(2));
50/// assert_eq!(r.recv(), Ok(3));
51/// assert_eq!(r.recv(), Ok(5));
52/// // thread.join(); // Would block indefinitely
53/// drop(r);
54/// thread.join();
55pub fn primes_unbounded() -> (impl FnOnce() + Send, Receiver<usize>) {
56    from_iterator_unbounded(Primes::all())
57}
58
59struct WithObj<T, U> {
60    pub value: T,
61    #[allow(dead_code)]
62    obj_box: Box<U>,
63}
64
65impl<T, U> WithObj<T, U> {
66    fn new<'a, F>(obj: U, make_value: F) -> Self
67    where
68        U: 'a,
69        F: FnOnce(&'a U) -> T + 'a,
70    {
71        let obj_box = Box::new(obj);
72        Self {
73            value: make_value(unsafe { &*(&*obj_box as *const U) }),
74            obj_box,
75        }
76    }
77}
78
79impl<T, U, V> Iterator for WithObj<T, U>
80where
81    T: Iterator<Item = V>,
82{
83    type Item = V;
84
85    fn next(&mut self) -> Option<V> {
86        self.value.next()
87    }
88}
89
90/// ```
91/// # use primal_crossbeam::*;
92/// # use std::thread;
93/// let (thread, r) = thread_spawn(primes_bounded(5));
94/// assert_eq!(r.recv(), Ok(2));
95/// assert_eq!(r.recv(), Ok(3));
96/// thread.join(); // Since the number of primes is bounded, this will eventually terminate.
97/// assert_eq!(r.recv(), Ok(5));
98pub fn primes_bounded(limit: usize) -> (impl FnOnce() + Send, Receiver<usize>) {
99    let (_, high) = estimate_prime_pi(limit as u64);
100    #[allow(clippy::cast_possible_truncation)]
101    let len = high as usize;
102    let sieve = Sieve::new(limit);
103    from_iterator_bounded(
104        WithObj::new(sieve, move |s| {
105            Sieve::primes_from(s, 0).take_while(move |x| x <= &limit)
106        }),
107        len,
108    )
109}