From 79025e3f402749d4cad8dd794530bdafed490ef5 Mon Sep 17 00:00:00 2001 From: Austin Ray Date: Fri, 21 May 2021 17:25:59 -0400 Subject: [PATCH] base: split `calculate_room_name()` Split `calculate_room_name()` into a high-level function using Matrix data types and low-level function containing the core logic using plain Rust data types. Since the low-level function uses simple data types, unit testing becomes easier. --- matrix_sdk_base/src/rooms/mod.rs | 57 +++++++++++++++++++------------- 1 file changed, 34 insertions(+), 23 deletions(-) diff --git a/matrix_sdk_base/src/rooms/mod.rs b/matrix_sdk_base/src/rooms/mod.rs index 30d7bc2e..6ade20f4 100644 --- a/matrix_sdk_base/src/rooms/mod.rs +++ b/matrix_sdk_base/src/rooms/mod.rs @@ -62,29 +62,11 @@ impl BaseRoomInfo { invited_member_count: u64, heroes: Vec, ) -> String { - let heroes_count = heroes.len() as u64; - let invited_joined = invited_member_count + joined_member_count; - let invited_joined_minus_one = invited_joined.saturating_sub(1); - - if heroes_count >= invited_joined_minus_one { - let mut names = heroes.iter().take(3).map(|mem| mem.name()).collect::>(); - // stabilize ordering - names.sort_unstable(); - names.join(", ") - } else if heroes_count < invited_joined_minus_one && invited_joined > 1 { - let mut names = heroes.iter().take(3).map(|mem| mem.name()).collect::>(); - names.sort_unstable(); - - // TODO: What length does the spec want us to use here and in - // the `else`? - format!( - "{}, and {} others", - names.join(", "), - (joined_member_count + invited_member_count) - ) - } else { - "Empty room".to_string() - } + calculate_room_name( + joined_member_count, + invited_member_count, + heroes.iter().take(3).map(|mem| mem.name()).collect::>(), + ) } /// Handle a state event for this room and update our info accordingly. @@ -165,3 +147,32 @@ impl Default for BaseRoomInfo { } } } + +/// Calculate room name according to step 3 of the [naming algorithm.][spec] +/// +/// [spec]: +fn calculate_room_name( + joined_member_count: u64, + invited_member_count: u64, + heroes: Vec<&str>, +) -> String { + let heroes_count = heroes.len() as u64; + let invited_joined = invited_member_count + joined_member_count; + let invited_joined_minus_one = invited_joined.saturating_sub(1); + + if heroes_count >= invited_joined_minus_one { + let mut names = heroes; + // stabilize ordering + names.sort_unstable(); + names.join(", ") + } else if heroes_count < invited_joined_minus_one && invited_joined > 1 { + let mut names = heroes; + names.sort_unstable(); + + // TODO: What length does the spec want us to use here and in + // the `else`? + format!("{}, and {} others", names.join(", "), (joined_member_count + invited_member_count)) + } else { + "Empty room".to_string() + } +}