Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

im-util: Add Sort, SortBy adapters #46

Merged
merged 3 commits into from
Jun 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions eyeball-im-util/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
# unreleased

- Remove lifetime parameter from `SortBy`
- Allow `SortBy::new` and `VectorObserverExt::sort_by` to accept a callable
directly, instead of through a reference (references still work since `&F`
also implements `Fn(X) -> Y` if `F` does)
- Add `Sort`, `SortByKey` adapters and corresponding `VectorObserverExt` methods

# 0.5.3

- Add the `SortBy` adapter
Expand Down
2 changes: 1 addition & 1 deletion eyeball-im-util/src/vector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use self::ops::{VectorDiffContainerFamilyMember, VectorDiffContainerOps};
pub use self::{
filter::{Filter, FilterMap},
limit::{EmptyLimitStream, Limit},
sort::SortBy,
sort::{Sort, SortBy, SortByKey},
traits::{
BatchedVectorSubscriber, VectorDiffContainer, VectorObserver, VectorObserverExt,
VectorSubscriberExt,
Expand Down
222 changes: 181 additions & 41 deletions eyeball-im-util/src/vector/sort.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,24 +25,11 @@ pin_project! {
/// use eyeball_im::{ObservableVector, VectorDiff};
/// use eyeball_im_util::vector::VectorObserverExt;
/// use imbl::vector;
/// use std::cmp::Ordering;
/// use stream_assert::{assert_closed, assert_next_eq, assert_pending};
///
/// // A comparison function that is used to sort our
/// // `ObservableVector` values.
/// fn cmp<T>(left: &T, right: &T) -> Ordering
/// where
/// T: Ord,
/// {
/// left.cmp(right)
/// }
///
/// # fn main() {
/// // Our vector.
/// let mut ob = ObservableVector::<char>::new();
/// let (values, mut sub) = ob.subscribe().sort_by(&cmp);
/// // ^^^^
/// // | our comparison function
/// let (values, mut sub) = ob.subscribe().sort();
///
/// assert!(values.is_empty());
/// assert_pending!(sub);
Expand All @@ -53,11 +40,11 @@ pin_project! {
/// assert_next_eq!(sub, VectorDiff::Append { values: vector!['b', 'd', 'e'] });
///
/// // Let's recap what we have. `ob` is our `ObservableVector`,
/// // `sub` is the “sorted view”/“sorted stream” of `ob`:
/// // `sub` is the “sorted view” / “sorted stream” of `ob`:
/// // | `ob` | d b e |
/// // | `sub` | b d e |
///
/// // Append other multiple values.
/// // Append multiple other values.
/// ob.append(vector!['f', 'g', 'a', 'c']);
/// // We get three `VectorDiff`s!
/// assert_next_eq!(sub, VectorDiff::PushFront { value: 'a' });
Expand All @@ -73,25 +60,174 @@ pin_project! {
/// // | with `VectorDiff::Insert { index: 2, .. }`
/// // with `VectorDiff::PushFront { .. }`
///
/// // Technically, `SortBy` emits `VectorDiff`s that mimic a sorted `Vector`.
/// // Technically, `Sort` emits `VectorDiff`s that mimic a sorted `Vector`.
///
/// drop(ob);
/// assert_closed!(sub);
/// # }
/// ```
///
/// [`ObservableVector`]: eyeball_im::ObservableVector
pub struct SortBy<'a, S, F>
pub struct Sort<S>
where
S: Stream,
S::Item: VectorDiffContainer,
{
// The main stream to poll items from.
#[pin]
inner: SortImpl<S>,
}
}

impl<S> Sort<S>
where
S: Stream,
S::Item: VectorDiffContainer,
VectorDiffContainerStreamElement<S>: Ord,
{
/// Create a new `Sort` with the given (unsorted) initial values and stream
/// of `VectorDiff` updates for those values.
pub fn new(
initial_values: Vector<VectorDiffContainerStreamElement<S>>,
inner_stream: S,
) -> (Vector<VectorDiffContainerStreamElement<S>>, Self) {
let (initial_sorted, inner) = SortImpl::new(initial_values, inner_stream, Ord::cmp);
(initial_sorted, Self { inner })
}
}

impl<S> Stream for Sort<S>
where
S: Stream,
S::Item: VectorDiffContainer,
VectorDiffContainerStreamElement<S>: Ord,
{
type Item = S::Item;

fn poll_next(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Option<Self::Item>> {
self.project().inner.poll_next(cx, Ord::cmp)
}
}

pin_project! {
/// A [`VectorDiff`] stream adapter that presents a sorted view of the
/// underlying [`ObservableVector`] items.
///
/// Sorting is done using a custom comparison function. Otherwise this
/// adapter works exactly like [`Sort`], see that type's documentation for
/// details on how this adapter operates.
///
/// [`ObservableVector`]: eyeball_im::ObservableVector
pub struct SortBy<S, F>
where
S: Stream,
S::Item: VectorDiffContainer,
{
#[pin]
inner: SortImpl<S>,

// The comparison function to sort items.
compare: &'a F,
compare: F,
}
}

impl<S, F> SortBy<S, F>
where
S: Stream,
S::Item: VectorDiffContainer,
F: Fn(&VectorDiffContainerStreamElement<S>, &VectorDiffContainerStreamElement<S>) -> Ordering,
{
/// Create a new `SortBy` with the given (unsorted) initial values, stream
/// of `VectorDiff` updates for those values, and the comparison function.
pub fn new(
initial_values: Vector<VectorDiffContainerStreamElement<S>>,
inner_stream: S,
compare: F,
) -> (Vector<VectorDiffContainerStreamElement<S>>, Self) {
let (initial_sorted, inner) = SortImpl::new(initial_values, inner_stream, &compare);
(initial_sorted, Self { inner, compare })
}
}

impl<S, F> Stream for SortBy<S, F>
where
S: Stream,
S::Item: VectorDiffContainer,
F: Fn(&VectorDiffContainerStreamElement<S>, &VectorDiffContainerStreamElement<S>) -> Ordering,
{
type Item = S::Item;

fn poll_next(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.project();
this.inner.poll_next(cx, &*this.compare)
}
}

pin_project! {
/// A [`VectorDiff`] stream adapter that presents a sorted view of the
/// underlying [`ObservableVector`] items.
///
/// Sorting is done by transforming items to a key with a custom function
/// and comparing those. Otherwise this adapter works exactly like [`Sort`],
/// see that type's documentation for details on how this adapter operates.
///
/// [`ObservableVector`]: eyeball_im::ObservableVector
pub struct SortByKey<S, F>
where
S: Stream,
S::Item: VectorDiffContainer,
{
#[pin]
inner: SortImpl<S>,

// The function to convert an item to a key used for comparison.
key_fn: F,
}
}

impl<S, F, K> SortByKey<S, F>
where
S: Stream,
S::Item: VectorDiffContainer,
F: Fn(&VectorDiffContainerStreamElement<S>) -> K,
K: Ord,
{
/// Create a new `SortByKey` with the given (unsorted) initial values,
/// stream of `VectorDiff` updates for those values, and the key function.
pub fn new(
initial_values: Vector<VectorDiffContainerStreamElement<S>>,
inner_stream: S,
key_fn: F,
) -> (Vector<VectorDiffContainerStreamElement<S>>, Self) {
let (initial_sorted, inner) =
SortImpl::new(initial_values, inner_stream, |a, b| key_fn(a).cmp(&key_fn(b)));
(initial_sorted, Self { inner, key_fn })
}
}

impl<S, F, K> Stream for SortByKey<S, F>
where
S: Stream,
S::Item: VectorDiffContainer,
F: Fn(&VectorDiffContainerStreamElement<S>) -> K,
K: Ord,
{
type Item = S::Item;

fn poll_next(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.project();
let key_fn = &*this.key_fn;
this.inner.poll_next(cx, |a, b| key_fn(a).cmp(&key_fn(b)))
}
}

pin_project! {
pub struct SortImpl<S>
where
S: Stream,
S::Item: VectorDiffContainer,
{
// The main stream to poll items from.
#[pin]
inner_stream: S,

// This is the **sorted** buffered vector.
buffered_vector: Vector<(UnsortedIndex, VectorDiffContainerStreamElement<S>)>,
Expand All @@ -105,43 +241,47 @@ pin_project! {
}
}

impl<'a, S, F> SortBy<'a, S, F>
impl<S> SortImpl<S>
where
S: Stream,
S::Item: VectorDiffContainer,
F: Fn(&VectorDiffContainerStreamElement<S>, &VectorDiffContainerStreamElement<S>) -> Ordering,
{
/// Create a new `SortBy` with the given (unsorted) initial values, stream
/// of `VectorDiff` updates for those values, and the comparison function.
pub fn new(
fn new<F>(
initial_values: Vector<VectorDiffContainerStreamElement<S>>,
inner_stream: S,
compare: &'a F,
) -> (Vector<VectorDiffContainerStreamElement<S>>, Self) {
compare: F,
) -> (Vector<VectorDiffContainerStreamElement<S>>, Self)
where
F: Fn(
&VectorDiffContainerStreamElement<S>,
&VectorDiffContainerStreamElement<S>,
) -> Ordering,
{
let mut initial_values = initial_values.into_iter().enumerate().collect::<Vector<_>>();
initial_values.sort_by(|(_, left), (_, right)| compare(left, right));

(
initial_values.iter().map(|(_, value)| value.clone()).collect(),
Self {
inner_stream,
compare,
buffered_vector: initial_values,
ready_values: Default::default(),
},
)
}
}

impl<'a, S, F> Stream for SortBy<'a, S, F>
where
S: Stream,
S::Item: VectorDiffContainer,
F: Fn(&VectorDiffContainerStreamElement<S>, &VectorDiffContainerStreamElement<S>) -> Ordering,
{
type Item = S::Item;

fn poll_next(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Option<Self::Item>> {
fn poll_next<F>(
self: Pin<&mut Self>,
cx: &mut task::Context<'_>,
compare: F,
) -> Poll<Option<S::Item>>
where
F: Fn(
&VectorDiffContainerStreamElement<S>,
&VectorDiffContainerStreamElement<S>,
) -> Ordering
+ Copy,
Hywan marked this conversation as resolved.
Show resolved Hide resolved
{
let mut this = self.project();

loop {
Expand All @@ -157,7 +297,7 @@ where

// Consume and apply the diffs if possible.
let ready = diffs.push_into_sort_buf(this.ready_values, |diff| {
handle_diff_and_update_buffered_vector(diff, this.compare, this.buffered_vector)
handle_diff_and_update_buffered_vector(diff, compare, this.buffered_vector)
});

if let Some(diff) = ready {
Expand All @@ -178,7 +318,7 @@ where
/// `Iterator::position` is used.
fn handle_diff_and_update_buffered_vector<T, F>(
diff: VectorDiff<T>,
compare: &F,
compare: F,
buffered_vector: &mut Vector<(usize, T)>,
) -> SmallVec<[VectorDiff<T>; 2]>
where
Expand Down
29 changes: 26 additions & 3 deletions eyeball-im-util/src/vector/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use super::{
ops::{
VecVectorDiffFamily, VectorDiffContainerFamily, VectorDiffContainerOps, VectorDiffFamily,
},
EmptyLimitStream, Filter, FilterMap, Limit, SortBy,
EmptyLimitStream, Filter, FilterMap, Limit, Sort, SortBy, SortByKey,
};

/// Abstraction over stream items that the adapters in this module can deal
Expand Down Expand Up @@ -160,16 +160,39 @@ where
Limit::dynamic_with_initial_limit(items, stream, initial_limit, limit_stream)
}

/// Sort the observed values with `compare`.
/// Sort the observed values.
///
/// See [`Sort`] for more details.
fn sort(self) -> (Vector<T>, Sort<Self::Stream>)
where
T: Ord,
{
let (items, stream) = self.into_parts();
Sort::new(items, stream)
}

/// Sort the observed values with the given comparison function.
///
/// See [`SortBy`] for more details.
fn sort_by<F>(self, compare: &F) -> (Vector<T>, SortBy<'_, Self::Stream, F>)
fn sort_by<F>(self, compare: F) -> (Vector<T>, SortBy<Self::Stream, F>)
where
F: Fn(&T, &T) -> Ordering,
{
let (items, stream) = self.into_parts();
SortBy::new(items, stream, compare)
}

/// Sort the observed values with the given key function.
///
/// See [`SortBy`] for more details.
fn sort_by_key<F, K>(self, key_fn: F) -> (Vector<T>, SortByKey<Self::Stream, F>)
where
F: Fn(&T) -> K,
K: Ord,
{
let (items, stream) = self.into_parts();
SortByKey::new(items, stream, key_fn)
}
}

impl<T, O> VectorObserverExt<T> for O
Expand Down
2 changes: 2 additions & 0 deletions eyeball-im-util/tests/it/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@ mod filter;
mod filter_map;
mod limit;
mod sort;
mod sort_by;
mod sort_by_key;
Loading