From ab2b5bfa23aff4dd5b9fe8c0ff36aad224b80aa2 Mon Sep 17 00:00:00 2001 From: Ivan Enderlin Date: Wed, 20 Mar 2024 21:08:01 +0100 Subject: [PATCH] feat(sdk): Remove `AtomicU64::load` in `ChunkIdentifierGenerator`. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit As suggested in https://github.com/matrix-org/matrix-rust-sdk/ pull/3251#discussion_r1532103818 by Poljar, it is possible that the value of the atomic changes between the `fetch_add` and the `load` (if and only if it is used in a concurrency model, which is not the case right now, but anyway… better being correct now!). The idea is not `load` but repeat the addition manually to compute the “current” value. --- crates/matrix-sdk/src/event_cache/linked_chunk.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/crates/matrix-sdk/src/event_cache/linked_chunk.rs b/crates/matrix-sdk/src/event_cache/linked_chunk.rs index 0630d8b81..f73df70f6 100644 --- a/crates/matrix-sdk/src/event_cache/linked_chunk.rs +++ b/crates/matrix-sdk/src/event_cache/linked_chunk.rs @@ -593,15 +593,14 @@ impl ChunkIdentifierGenerator { /// In this case, `Result::Err` contains the previous unique identifier. pub fn generate_next(&self) -> Result { let previous = self.next.fetch_add(1, Ordering::Relaxed); - let current = self.next.load(Ordering::Relaxed); // Check for overflows. // unlikely — TODO: call `std::intrinsics::unlikely` once it's stable. - if current < previous { + if previous == u64::MAX { return Err(ChunkIdentifier(previous)); } - Ok(ChunkIdentifier(current)) + Ok(ChunkIdentifier(previous.saturating_add(1))) } }