LCOV - code coverage report
Current view: top level - libs/utils/src - guard_arc_swap.rs (source / functions) Coverage Total Hit
Test: 45c9170b95180e9ecfad9a53e031030abf2a178c.info Lines: 75.0 % 28 21
Test Date: 2025-02-21 15:51:08 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 arc_swap::ArcSwap;
       5              : use std::sync::Arc;
       6              : use tokio::sync::TryLockError;
       7              : 
       8              : pub struct GuardArcSwap<T> {
       9              :     inner: ArcSwap<T>,
      10              :     guard: tokio::sync::Mutex<()>,
      11              : }
      12              : 
      13              : pub struct Guard<'a, T> {
      14              :     _guard: tokio::sync::MutexGuard<'a, ()>,
      15              :     inner: &'a ArcSwap<T>,
      16              : }
      17              : 
      18              : impl<T> GuardArcSwap<T> {
      19          897 :     pub fn new(inner: T) -> Self {
      20          897 :         Self {
      21          897 :             inner: ArcSwap::new(Arc::new(inner)),
      22          897 :             guard: tokio::sync::Mutex::new(()),
      23          897 :         }
      24          897 :     }
      25              : 
      26          728 :     pub fn read(&self) -> Arc<T> {
      27          728 :         self.inner.load_full()
      28          728 :     }
      29              : 
      30            0 :     pub async fn write_guard(&self) -> Guard<'_, T> {
      31            0 :         Guard {
      32            0 :             _guard: self.guard.lock().await,
      33            0 :             inner: &self.inner,
      34            0 :         }
      35            0 :     }
      36              : 
      37         1141 :     pub fn try_write_guard(&self) -> Result<Guard<'_, T>, TryLockError> {
      38         1141 :         let guard = self.guard.try_lock()?;
      39         1141 :         Ok(Guard {
      40         1141 :             _guard: guard,
      41         1141 :             inner: &self.inner,
      42         1141 :         })
      43            0 :     }
      44              : }
      45              : 
      46              : impl<T> Guard<'_, T> {
      47         1141 :     pub fn read(&self) -> Arc<T> {
      48         1141 :         self.inner.load_full()
      49         1141 :     }
      50              : 
      51          645 :     pub fn write(&mut self, value: T) {
      52          645 :         self.inner.store(Arc::new(value));
      53          645 :     }
      54              : }
        

Generated by: LCOV version 2.1-beta