From 7ba9263cc669eaadecd22558eb4e9410c96593c8 Mon Sep 17 00:00:00 2001 From: Timo Date: Sat, 22 Aug 2020 23:09:53 +0200 Subject: [PATCH] improvement: show most recent PDUs first when searching --- src/client_server/account.rs | 5 ++++- src/database/rooms.rs | 13 +++++++++++-- src/utils.rs | 16 ++++++++++------ 3 files changed, 25 insertions(+), 9 deletions(-) diff --git a/src/client_server/account.rs b/src/client_server/account.rs index fe5ac97d..9837d1b9 100644 --- a/src/client_server/account.rs +++ b/src/client_server/account.rs @@ -145,7 +145,10 @@ pub fn register_route( } if missing_username { - return Err(Error::BadRequest(ErrorKind::MissingParam, "Missing username field.")); + return Err(Error::BadRequest( + ErrorKind::MissingParam, + "Missing username field.", + )); } let password = if is_guest { diff --git a/src/database/rooms.rs b/src/database/rooms.rs index 767f581c..d2cd5e9f 100644 --- a/src/database/rooms.rs +++ b/src/database/rooms.rs @@ -965,6 +965,7 @@ impl Rooms { self.tokenids .scan_prefix(&prefix2) .keys() + .rev() // Newest pdus first .filter_map(|r| r.ok()) .map(|key| { let pduid_index = key @@ -983,7 +984,14 @@ impl Rooms { .filter_map(|r| r.ok()) }); - Ok((utils::common_elements(iterators).unwrap(), words)) + Ok(( + utils::common_elements(iterators, |a, b| { + // We compare b with a because we reversed the iterator earlier + b.cmp(a) + }) + .unwrap(), + words, + )) } pub fn get_shared_rooms<'a>( @@ -1015,7 +1023,8 @@ impl Rooms { .filter_map(|r| r.ok()) }); - utils::common_elements(iterators) + // We use the default compare function because keys are sorted correctly (not reversed) + utils::common_elements(iterators, Ord::cmp) .expect("users is not empty") .map(|bytes| { RoomId::try_from(utils::string_from_bytes(&*bytes).map_err(|_| { diff --git a/src/utils.rs b/src/utils.rs index 473c18f5..8cf1b2ce 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -1,7 +1,9 @@ use argon2::{Config, Variant}; +use cmp::Ordering; use rand::prelude::*; use sled::IVec; use std::{ + cmp, convert::TryInto, time::{SystemTime, UNIX_EPOCH}, }; @@ -63,6 +65,7 @@ pub fn calculate_hash(password: &str) -> Result { pub fn common_elements( mut iterators: impl Iterator>, + check_order: impl Fn(&IVec, &IVec) -> Ordering, ) -> Option> { let first_iterator = iterators.next()?; let mut other_iterators = iterators.map(|i| i.peekable()).collect::>(); @@ -72,12 +75,13 @@ pub fn common_elements( .iter_mut() .map(|it| { while let Some(element) = it.peek() { - if element > target { - return false; - } else if element == target { - return true; - } else { - it.next(); + match check_order(element, target) { + Ordering::Greater => return false, // We went too far + Ordering::Equal => return true, // Element is in both iters + Ordering::Less => { + // Keep searching + it.next(); + } } }