Skip to content

Commit

Permalink
im-util: Introduce helpers for ObservableVector2
Browse files Browse the repository at this point in the history
  • Loading branch information
jplatte committed Sep 1, 2023
1 parent a82eef5 commit cfc0414
Show file tree
Hide file tree
Showing 3 changed files with 448 additions and 0 deletions.
2 changes: 2 additions & 0 deletions eyeball-im-util/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,7 @@
//! The primary entry point of this library is [`VectorExt`].

pub mod vector;
pub mod vector2;

pub use vector::VectorExt;
pub use vector2::Vector2Ext;
51 changes: 51 additions & 0 deletions eyeball-im-util/src/vector2.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
//! Utilities around [`ObservableVector`].

use eyeball_im::{ObservableVector2, Vector, VectorSubscriber2};

mod filter;

pub use self::filter::{Filter, FilterMap};

/// Extension trait for [`ObservableVector`].
pub trait Vector2Ext<T>
where
T: Clone + Send + Sync + 'static,
{
/// Obtain a new subscriber that filters items by the given filter function.
///
/// Returns a filtered version of the current vector, and a subscriber to
/// get updates through.
fn subscribe_filter<F>(&self, f: F) -> (Vector<T>, Filter<VectorSubscriber2<T>, F>)
where
F: Fn(&T) -> bool;

/// Obtain a new subscriber that filters and maps items with the given
/// function.
///
/// Returns a filtered + mapped version of the current vector, and a
/// subscriber to get updates through.
fn subscribe_filter_map<U, F>(&self, f: F) -> (Vector<U>, FilterMap<VectorSubscriber2<T>, F>)
where
U: Clone,
F: Fn(T) -> Option<U>;
}

impl<T> Vector2Ext<T> for ObservableVector2<T>
where
T: Clone + Send + Sync + 'static,
{
fn subscribe_filter<F>(&self, f: F) -> (Vector<T>, Filter<VectorSubscriber2<T>, F>)
where
F: Fn(&T) -> bool,
{
Filter::new((*self).clone(), self.subscribe(), f)
}

fn subscribe_filter_map<U, F>(&self, f: F) -> (Vector<U>, FilterMap<VectorSubscriber2<T>, F>)
where
U: Clone,
F: Fn(T) -> Option<U>,
{
FilterMap::new((*self).clone(), self.subscribe(), f)
}
}
Loading

0 comments on commit cfc0414

Please sign in to comment.