Files
continuwuity/src/core/utils/set.rs
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

111 lines
2.6 KiB
Rust
Raw Normal View History

use std::{
cmp::{Eq, Ord},
pin::Pin,
sync::Arc,
};
use futures::{Stream, StreamExt};
2024-08-08 17:18:30 +00:00
use crate::{is_equal_to, is_less_than};
/// Intersection of sets
///
/// Outputs the set of elements common to all input sets. Inputs do not have to
/// be sorted. If inputs are sorted a more optimized function is available in
/// this suite and should be used.
pub fn intersection<Item, Iter, Iters>(mut input: Iters) -> impl Iterator<Item = Item> + Send
where
Iters: Iterator<Item = Iter> + Clone + Send,
Iter: Iterator<Item = Item> + Send,
2024-12-17 14:52:12 +00:00
Item: Eq,
2024-08-08 17:18:30 +00:00
{
input.next().into_iter().flat_map(move |first| {
let input = input.clone();
first.filter(move |targ| {
input
.clone()
.all(|mut other| other.any(is_equal_to!(*targ)))
})
})
}
/// Intersection of sets
///
/// Outputs the set of elements common to all input sets. Inputs must be sorted.
pub fn intersection_sorted<Item, Iter, Iters>(
mut input: Iters,
) -> impl Iterator<Item = Item> + Send
2024-08-08 17:18:30 +00:00
where
Iters: Iterator<Item = Iter> + Clone + Send,
Iter: Iterator<Item = Item> + Send,
2024-12-17 14:52:12 +00:00
Item: Eq + Ord,
2024-08-08 17:18:30 +00:00
{
input.next().into_iter().flat_map(move |first| {
let mut input = input.clone().collect::<Vec<_>>();
first.filter(move |targ| {
input.iter_mut().all(|it| {
it.by_ref()
.skip_while(is_less_than!(targ))
.peekable()
.peek()
.is_some_and(is_equal_to!(targ))
})
})
})
}
/// Intersection of sets
///
/// Outputs the set of elements common to both streams. Streams must be sorted.
pub fn intersection_sorted_stream2<Item, S>(a: S, b: S) -> impl Stream<Item = Item> + Send
where
S: Stream<Item = Item> + Send + Unpin,
Item: Eq + PartialOrd + Send + Sync,
{
use tokio::sync::Mutex;
let b = Arc::new(Mutex::new(b.peekable()));
a.map(move |ai| (ai, b.clone()))
2025-07-08 11:08:58 +00:00
.filter_map(async move |(ai, b)| {
let mut lock = b.lock().await;
2025-04-22 04:42:26 +00:00
while let Some(bi) = Pin::new(&mut *lock)
.next_if(|bi| *bi <= ai)
.await
.as_ref()
{
if ai == *bi {
return Some(ai);
}
}
None
})
}
2025-09-29 01:52:05 +00:00
/// Difference of sets
///
/// Outputs the set of elements found in `a` which are not found in `b`. Streams
/// must be sorted.
pub fn difference_sorted_stream2<Item, S>(a: S, b: S) -> impl Stream<Item = Item> + Send
where
S: Stream<Item = Item> + Send + Unpin,
Item: Eq + PartialOrd + Send + Sync,
{
use tokio::sync::Mutex;
let b = Arc::new(Mutex::new(b.peekable()));
a.map(move |ai| (ai, b.clone()))
.filter_map(async move |(ai, b)| {
let mut lock = b.lock().await;
let b = &mut Pin::new(&mut *lock);
while b.as_mut().next_if(|bi| *bi < ai).await.is_some() {
continue;
}
b.as_mut()
.next_if_eq(&ai)
.await
.is_none()
.then_some(ai)
})
}