use std::cmp::Ordering;
use super::{Room, Sorter};
struct NameMatcher<F>
where
F: Fn(&Room, &Room) -> (Option<String>, Option<String>),
{
names: F,
}
impl<F> NameMatcher<F>
where
F: Fn(&Room, &Room) -> (Option<String>, Option<String>),
{
fn matches(&self, left: &Room, right: &Room) -> Ordering {
let (left_name, right_name) = (self.names)(left, right);
left_name.cmp(&right_name)
}
}
pub fn new_sorter() -> impl Sorter {
let matcher = NameMatcher {
names: move |left, right| (left.cached_display_name(), right.cached_display_name()),
};
move |left, right| -> Ordering { matcher.matches(left, right) }
}
#[cfg(test)]
mod tests {
use matrix_sdk_test::async_test;
use ruma::room_id;
use super::{
super::super::filters::{client_and_server_prelude, new_rooms},
*,
};
#[async_test]
async fn test_with_two_names() {
let (client, server, sliding_sync) = client_and_server_prelude().await;
let [room_a, room_b] =
new_rooms([room_id!("!a:b.c"), room_id!("!d:e.f")], &client, &server, &sliding_sync)
.await;
{
let matcher = NameMatcher {
names: |_left, _right| (Some("Foo".to_owned()), Some("Baz".to_owned())),
};
assert_eq!(matcher.matches(&room_a, &room_b), Ordering::Greater);
}
{
let matcher = NameMatcher {
names: |_left, _right| (Some("Bar".to_owned()), Some("Baz".to_owned())),
};
assert_eq!(matcher.matches(&room_a, &room_b), Ordering::Less);
}
{
let matcher = NameMatcher {
names: |_left, _right| (Some("Baz".to_owned()), Some("Baz".to_owned())),
};
assert_eq!(matcher.matches(&room_a, &room_b), Ordering::Equal);
}
}
#[async_test]
async fn test_with_one_name() {
let (client, server, sliding_sync) = client_and_server_prelude().await;
let [room_a, room_b] =
new_rooms([room_id!("!a:b.c"), room_id!("!d:e.f")], &client, &server, &sliding_sync)
.await;
{
let matcher = NameMatcher { names: |_left, _right| (Some("Foo".to_owned()), None) };
assert_eq!(matcher.matches(&room_a, &room_b), Ordering::Greater);
}
{
let matcher = NameMatcher { names: |_left, _right| (None, Some("Bar".to_owned())) };
assert_eq!(matcher.matches(&room_a, &room_b), Ordering::Less);
}
}
#[async_test]
async fn test_with_zero_name() {
let (client, server, sliding_sync) = client_and_server_prelude().await;
let [room_a, room_b] =
new_rooms([room_id!("!a:b.c"), room_id!("!d:e.f")], &client, &server, &sliding_sync)
.await;
{
let matcher = NameMatcher { names: |_left, _right| (None, None) };
assert_eq!(matcher.matches(&room_a, &room_b), Ordering::Equal);
}
}
}