Skip to content

Commit

Permalink
feat: Implement the Sort stream adapter.
Browse files Browse the repository at this point in the history
`Sort` is `VectorDiff` stream adapter that presents a sorted view of the
underlying `ObservableVector` items.

```rust
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)
}

// Our vector.
let mut ob = ObservableVector::<char>::new();
let (values, mut sub) = ob.subscribe().sort(cmp);
//                                          ^^^
//                                          | our comparison function

assert!(values.is_empty());
assert_pending!(sub);

// Append multiple unsorted values.
ob.append(vector!['d', 'b', 'e']);
// We get a `VectorDiff::Append` with sorted values!
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`:
// | `ob`  | d b e |
// | `sub` | b d e |

// Append other multiple values.
ob.append(vector!['f', 'g', 'a', 'c']);
// We get three `VectorDiff`s!
assert_next_eq!(sub, VectorDiff::PushFront { value: 'a' });
assert_next_eq!(sub, VectorDiff::Insert { index: 2, value: 'c' });
assert_next_eq!(sub, VectorDiff::Append { values: vector!['f', 'g'] });

// Let's recap what we have:
// | `ob`  | d b e f g a c |
// | `sub` | a b c d e f g |
//           ^   ^     ^^^
//           |   |     |
//           |   |     with `VectorDiff::Append { .. }`
//           |   with `VectorDiff::Insert { index: 2, .. }`
//           with `VectorDiff::PushFront { .. }`

// Technically, `Sort` emits `VectorDiff` that mimics a sorted `Vector`.

drop(ob);
assert_closed!(sub);
```
  • Loading branch information
Hywan committed Jan 20, 2024
1 parent d0173f6 commit b86e737
Show file tree
Hide file tree
Showing 5 changed files with 1,077 additions and 1 deletion.
2 changes: 2 additions & 0 deletions eyeball-im-util/src/vector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
mod filter;
mod limit;
mod ops;
mod sort;
mod traits;

use eyeball_im::VectorDiff;
Expand All @@ -12,6 +13,7 @@ use self::ops::{VectorDiffContainerFamilyMember, VectorDiffContainerOps};
pub use self::{
filter::{Filter, FilterMap},
limit::{EmptyLimitStream, Limit},
sort::Sort,
traits::{
BatchedVectorSubscriber, VectorDiffContainer, VectorObserver, VectorObserverExt,
VectorSubscriberExt,
Expand Down
Loading

0 comments on commit b86e737

Please sign in to comment.