From cee2b1bebf1eb23578e072b02ebc3d65e31a5b34 Mon Sep 17 00:00:00 2001 From: Ivan Enderlin Date: Tue, 11 Nov 2025 15:35:44 +0100 Subject: [PATCH] feat(common): Add `CrossProcessLockState::map`. This patch adds the `CrossProcessLockState::map` method along with its companion `MappedCrossProcessLockState` type. The idea is to facilitate the creation of custom `CrossProcessLockState`-like type in various usage of the cross-process lock. --- .../src/cross_process_lock.rs | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/crates/matrix-sdk-common/src/cross_process_lock.rs b/crates/matrix-sdk-common/src/cross_process_lock.rs index f9a74dd6e..7f834c303 100644 --- a/crates/matrix-sdk-common/src/cross_process_lock.rs +++ b/crates/matrix-sdk-common/src/cross_process_lock.rs @@ -496,6 +496,44 @@ impl CrossProcessLockState { Self::Clean(guard) | Self::Dirty(guard) => guard, } } + + /// Map this [`CrossProcessLockState`] into a + /// [`MappedCrossProcessLockState`]. + /// + /// This is helpful when one wants to create its own wrapper over + /// [`CrossProcessLockGuard`]. + pub fn map(self, mapper: F) -> MappedCrossProcessLockState + where + F: FnOnce(CrossProcessLockGuard) -> G, + { + match self { + Self::Clean(guard) => MappedCrossProcessLockState::Clean(mapper(guard)), + Self::Dirty(guard) => MappedCrossProcessLockState::Dirty(mapper(guard)), + } + } +} + +/// A mapped [`CrossProcessLockState`]. +/// +/// Created by [`CrossProcessLockState::map`]. +#[derive(Debug)] +#[must_use = "If unused, the `CrossProcessLock` will unlock at the end of the lease"] +pub enum MappedCrossProcessLockState { + /// The equivalent of [`CrossProcessLockState::Clean`]. + Clean(G), + + /// The equivalent of [`CrossProcessLockState::Dirty`]. + Dirty(G), +} + +impl MappedCrossProcessLockState { + /// Return `Some(G)` if `Self` is [`Clean`][Self::Clean]. + pub fn as_clean(&self) -> Option<&G> { + match self { + Self::Clean(guard) => Some(guard), + Self::Dirty(_) => None, + } + } } /// Represent an unsuccessful result of a lock attempt, either by