From a7ff0587a675c1aa7d08180f73e57cab860090f4 Mon Sep 17 00:00:00 2001 From: Ivan Enderlin Date: Thu, 13 Jun 2024 15:03:59 +0200 Subject: [PATCH] fix(ui): Replace the `RwLock` by a `Mutex` in `RoomListService::rooms`. This patch replaces the `RwLock` by a `Mutex` in `RoomListService::rooms` because: 1. it removes a race condition, 2. `RwLock` was used because the lock could have been taken for a long time due to the previous `.await` point. It's no longer the case, so we can blindly use a `Mutex` here. --- .../matrix-sdk-ui/src/room_list_service/mod.rs | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/crates/matrix-sdk-ui/src/room_list_service/mod.rs b/crates/matrix-sdk-ui/src/room_list_service/mod.rs index 4861cc9fd01..50fa5137012 100644 --- a/crates/matrix-sdk-ui/src/room_list_service/mod.rs +++ b/crates/matrix-sdk-ui/src/room_list_service/mod.rs @@ -69,7 +69,7 @@ mod state; use std::{ future::ready, num::NonZeroUsize, - sync::{Arc, RwLock}, + sync::{Arc, Mutex as StdMutex}, time::Duration, }; @@ -114,7 +114,7 @@ pub struct RoomListService { state: SharedObservable, /// Room cache, to avoid recreating `Room`s every time users fetch them. - rooms: Arc>>, + rooms: Arc>>, /// The current viewport ranges. /// @@ -204,7 +204,7 @@ impl RoomListService { client, sliding_sync, state: SharedObservable::new(State::Init), - rooms: Arc::new(RwLock::new(RingBuffer::new(Self::ROOM_OBJECT_CACHE_SIZE))), + rooms: Arc::new(StdMutex::new(RingBuffer::new(Self::ROOM_OBJECT_CACHE_SIZE))), viewport_ranges: Mutex::new(vec![VISIBLE_ROOMS_DEFAULT_RANGE]), }) } @@ -427,17 +427,16 @@ impl RoomListService { /// Get a [`Room`] if it exists. pub fn room(&self, room_id: &RoomId) -> Result { - { - let rooms = self.rooms.read().unwrap(); + let mut rooms = self.rooms.lock().unwrap(); - if let Some(room) = rooms.iter().rfind(|room| room.id() == room_id) { - return Ok(room.clone()); - } + if let Some(room) = rooms.iter().rfind(|room| room.id() == room_id) { + return Ok(room.clone()); } let room = Room::new(&self.client, room_id, &self.sliding_sync)?; - self.rooms.write().unwrap().push(room.clone()); + // Save for later. + rooms.push(room.clone()); Ok(room) }