LCOV - code coverage report
Current view: top level - libs/utils/src - guard_arc_swap.rs (source / functions) Coverage Total Hit
Test: 1e20c4f2b28aa592527961bb32170ebbd2c9172f.info Lines: 65.4 % 26 17
Test Date: 2025-07-16 12:29:03 Functions: 41.7 % 12 5

            Line data    Source code
       1              : //! A wrapper around `ArcSwap` that ensures there is only one writer at a time and writes
       2              : //! don't block reads.
       3              : 
       4              : use std::sync::Arc;
       5              : 
       6              : use arc_swap::ArcSwap;
       7              : use tokio::sync::TryLockError;
       8              : 
       9              : pub struct GuardArcSwap<T> {
      10              :     inner: ArcSwap<T>,
      11              :     guard: tokio::sync::Mutex<()>,
      12              : }
      13              : 
      14              : pub struct Guard<'a, T> {
      15              :     _guard: tokio::sync::MutexGuard<'a, ()>,
      16              :     inner: &'a ArcSwap<T>,
      17              : }
      18              : 
      19              : impl<T> GuardArcSwap<T> {
      20          235 :     pub fn new(inner: T) -> Self {
      21          235 :         Self {
      22          235 :             inner: ArcSwap::new(Arc::new(inner)),
      23          235 :             guard: tokio::sync::Mutex::new(()),
      24          235 :         }
      25            0 :     }
      26              : 
      27          384 :     pub fn read(&self) -> Arc<T> {
      28          384 :         self.inner.load_full()
      29            0 :     }
      30              : 
      31            0 :     pub async fn write_guard(&self) -> Guard<'_, T> {
      32              :         Guard {
      33            0 :             _guard: self.guard.lock().await,
      34            0 :             inner: &self.inner,
      35              :         }
      36            0 :     }
      37              : 
      38          303 :     pub fn try_write_guard(&self) -> Result<Guard<'_, T>, TryLockError> {
      39          303 :         let guard = self.guard.try_lock()?;
      40          303 :         Ok(Guard {
      41          303 :             _guard: guard,
      42          303 :             inner: &self.inner,
      43          303 :         })
      44            0 :     }
      45              : }
      46              : 
      47              : impl<T> Guard<'_, T> {
      48          303 :     pub fn read(&self) -> Arc<T> {
      49          303 :         self.inner.load_full()
      50            0 :     }
      51              : 
      52          169 :     pub fn write(&mut self, value: T) {
      53          169 :         self.inner.store(Arc::new(value));
      54            0 :     }
      55              : }
        

Generated by: LCOV version 2.1-beta