medea_reactive/collections/hash_set.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
//! Reactive hash set based on [`HashSet`].
use std::{collections::hash_set::Iter, hash::Hash, marker::PhantomData};
use futures::stream::LocalBoxStream;
use crate::subscribers_store::{
common, progressable,
progressable::{AllProcessed, Processed},
SubscribersStore,
};
/// Reactive hash set based on [`HashSet`] with an ability to recognize when all
/// updates was processed by subscribers.
pub type ProgressableHashSet<T> =
HashSet<T, progressable::SubStore<T>, progressable::Guarded<T>>;
/// Reactive hash set based on [`HashSet`].
pub type ObservableHashSet<T> = HashSet<T, common::SubStore<T>, T>;
/// Reactive hash set based on [`HashSet`].
///
/// # Usage
///
/// ```rust
/// # use futures::{executor, StreamExt as _, Stream};
/// # use std::collections::HashSet;
/// use medea_reactive::collections::ObservableHashSet;
///
/// # executor::block_on(async {
/// let mut set = ObservableHashSet::new();
///
/// // You can subscribe on insert action:
/// let mut inserts = set.on_insert();
///
/// set.insert("foo");
///
/// let item = inserts.next()
/// .await
/// .unwrap();
/// assert_eq!(item, "foo");
///
/// // Also you can subscribe on remove action:
/// let mut removals = set.on_remove();
///
/// set.remove(&"foo");
///
/// let removed_item = removals.next()
/// .await
/// .unwrap();
/// assert_eq!(removed_item, "foo");
///
/// // When you update HashSet by another HashSet all events will
/// // work fine:
/// set.insert("foo-1");
/// set.insert("foo-2");
/// set.insert("foo-3");
///
/// let mut set_for_update = HashSet::new();
/// set_for_update.insert("foo-1");
/// set_for_update.insert("foo-4");
/// set.update(set_for_update);
///
/// let removed_items: HashSet<_> = removals.take(2)
/// .collect()
/// .await;
/// let inserted_item = inserts.skip(3)
/// .next()
/// .await
/// .unwrap();
/// assert!(removed_items.contains("foo-2"));
/// assert!(removed_items.contains("foo-3"));
/// assert_eq!(inserted_item, "foo-4");
/// assert!(set.contains(&"foo-1"));
/// assert!(set.contains(&"foo-4"));
/// # });
/// ```
///
/// # Waiting for subscribers to complete
///
/// ```rust
/// # use futures::{executor, StreamExt as _, Stream};
/// use medea_reactive::collections::ProgressableHashSet;
///
/// # executor::block_on(async {
/// let mut hash_set = ProgressableHashSet::new();
///
/// let mut on_insert = hash_set.on_insert();
/// hash_set.insert(1);
///
/// // hash_set.when_insert_processed().await; <- wouldn't be resolved
/// let value = on_insert.next().await.unwrap();
/// // hash_set.when_insert_processed().await; <- wouldn't be resolved
/// drop(value);
///
/// hash_set.when_insert_processed().await; // will be resolved
/// # });
/// ```
#[derive(Debug)]
pub struct HashSet<T, S: SubscribersStore<T, O>, O> {
/// Data stored by this [`HashSet`].
store: std::collections::HashSet<T>,
/// Subscribers of the [`HashSet::on_insert()`] method.
on_insert_subs: S,
/// Subscribers of the [`HashSet::on_remove()`] method.
on_remove_subs: S,
/// Phantom type of [`HashSet::on_insert()`] and [`HashSet::on_remove()`]
/// output.
_output: PhantomData<O>,
}
impl<T> ProgressableHashSet<T>
where
T: Clone + 'static,
{
/// Returns [`Future`] resolving when all push updates will be processed by
/// [`HashSet::on_insert()`] subscribers.
///
/// [`Future`]: std::future::Future
pub fn when_insert_processed(&self) -> Processed<'static> {
self.on_insert_subs.when_all_processed()
}
/// Returns [`Future`] resolving when all remove updates will be processed
/// by [`HashSet::on_remove()`] subscribers.
///
/// [`Future`]: std::future::Future
pub fn when_remove_processed(&self) -> Processed<'static> {
self.on_remove_subs.when_all_processed()
}
/// Returns [`Future`] resolving when all insert and remove updates will be
/// processed by subscribers.
///
/// [`Future`]: std::future::Future
pub fn when_all_processed(&self) -> AllProcessed<'static> {
crate::when_all_processed(vec![
self.when_remove_processed().into(),
self.when_insert_processed().into(),
])
}
}
impl<T, S: SubscribersStore<T, O>, O> HashSet<T, S, O> {
/// Creates new empty [`HashSet`].
#[must_use]
pub fn new() -> Self {
Self::default()
}
/// Returns [`Iterator`] visiting all values in an arbitrary order.
pub fn iter(&self) -> impl Iterator<Item = &T> {
self.into_iter()
}
/// Returns [`Stream`] yielding inserted values to this [`HashSet`].
///
/// [`Stream`]: futures::Stream
#[must_use]
pub fn on_insert(&self) -> LocalBoxStream<'static, O> {
self.on_insert_subs.subscribe()
}
/// Returns the [`Stream`] yielding removed values from this [`HashSet`].
///
/// Note, that this [`Stream`] will yield all values of this [`HashSet`] on
/// [`Drop`].
///
/// [`Stream`]: futures::Stream
#[must_use]
pub fn on_remove(&self) -> LocalBoxStream<'static, O> {
self.on_remove_subs.subscribe()
}
}
impl<T, S, O> HashSet<T, S, O>
where
T: Clone + 'static,
S: SubscribersStore<T, O>,
O: 'static,
{
/// Returns [`Stream`] containing values from this [`HashSet`].
///
/// Returned [`Stream`] contains only current values. It won't update on new
/// inserts, but you can merge returned [`Stream`] with a
/// [`HashSet::on_insert()`] [`Stream`] if you want to process current
/// values and values that will be inserted.
///
/// [`Stream`]: futures::Stream
pub fn replay_on_insert(&self) -> LocalBoxStream<'static, O> {
Box::pin(futures::stream::iter(
self.store
.clone()
.into_iter()
.map(|val| self.on_insert_subs.wrap(val))
.collect::<Vec<_>>(),
))
}
}
impl<T, S, O> HashSet<T, S, O>
where
T: Clone + Hash + Eq + 'static,
S: SubscribersStore<T, O>,
{
/// Adds the `value` to this [`HashSet`].
///
/// If it didn't have such `value` present, `true` is returned.
///
/// If it did have such `value` present, `false` is returned.
///
/// This will produce [`HashSet::on_inser()t`] event.
pub fn insert(&mut self, value: T) -> bool {
if self.store.insert(value.clone()) {
self.on_insert_subs.send_update(value);
true
} else {
false
}
}
/// Removes the `value` from this [`HashSet`] and returns it, if any.
///
/// This will produce [`HashSet::on_remove()`] event.
pub fn remove(&mut self, value: &T) -> Option<T> {
let value = self.store.take(value);
if let Some(val) = &value {
self.on_remove_subs.send_update(val.clone());
}
value
}
/// Makes this [`HashSet`] exactly the same as the `updated` one.
///
/// It will calculate a diff between this [`HashSet`] and the `updated`, and
/// will spawn [`HashSet::on_insert()`] and [`HashSet::on_remove()`] if the
/// diff is not empty.
///
/// For the usage example you can read [`HashSet`] docs.
pub fn update(&mut self, updated: std::collections::HashSet<T>) {
let removed_elems = self.store.difference(&updated);
let inserted_elems = updated.difference(&self.store);
for removed_elem in removed_elems {
self.on_remove_subs.send_update(removed_elem.clone());
}
for inserted_elem in inserted_elems {
self.on_insert_subs.send_update(inserted_elem.clone());
}
self.store = updated;
}
/// Indicates whether this [`HashSet`] contains the `value`.
#[must_use]
pub fn contains(&self, value: &T) -> bool {
self.store.contains(value)
}
}
// Implemented manually to omit redundant `: Default` trait bounds, imposed by
// `#[derive(Default)]`.
impl<T, S, O> Default for HashSet<T, S, O>
where
S: SubscribersStore<T, O>,
{
fn default() -> Self {
Self {
store: std::collections::HashSet::new(),
on_insert_subs: S::default(),
on_remove_subs: S::default(),
_output: PhantomData::default(),
}
}
}
impl<'a, T, S: SubscribersStore<T, O>, O> IntoIterator
for &'a HashSet<T, S, O>
{
type IntoIter = Iter<'a, T>;
type Item = &'a T;
fn into_iter(self) -> Self::IntoIter {
self.store.iter()
}
}
impl<T, S, O> Drop for HashSet<T, S, O>
where
S: SubscribersStore<T, O>,
{
/// Sends all values of a dropped [`HashSet`] to the
/// [`HashSet::on_remove()`] subscriptions.
fn drop(&mut self) {
for val in self.store.drain() {
self.on_remove_subs.send_update(val);
}
}
}
impl<T, S, O> From<std::collections::HashSet<T>> for HashSet<T, S, O>
where
S: SubscribersStore<T, O>,
{
fn from(from: std::collections::HashSet<T>) -> Self {
Self {
store: from,
on_insert_subs: S::default(),
on_remove_subs: S::default(),
_output: PhantomData::default(),
}
}
}