Skip to content

Commit

Permalink
refactor: use std::sync::RwLock's try api, remove tokio dependency
Browse files Browse the repository at this point in the history
  • Loading branch information
willothy committed Nov 2, 2024
1 parent 73c9bf8 commit a812b42
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/mapref.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
//! });

use hashbrown::HashTable;
use tokio::sync::{RwLockReadGuard, RwLockWriteGuard};
use std::sync::{RwLockReadGuard, RwLockWriteGuard};

/// A reference to a key-value pair in a [`crate::ShardMap`]. Holds a shared (read-only) lock on the shard
/// associated with the key.
Expand Down
22 changes: 21 additions & 1 deletion src/shard.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
use hashbrown::HashTable;
use tokio::sync::RwLock;
use std::{
future::Future,
sync::{RwLock, RwLockReadGuard, RwLockWriteGuard, TryLockError},
task::Poll,
};

/// A shard in a [`crate::ShardMap`]. Each shard contains a [`hashbrown::HashTable`] of key-value pairs.
pub(crate) struct Shard<K, V> {
Expand All @@ -15,6 +19,22 @@ where
data: RwLock::new(HashTable::new()),
}
}

pub fn write<'a>(&'a self) -> impl Future<Output = RwLockWriteGuard<'a, HashTable<(K, V)>>> {
std::future::poll_fn(|_ctx| match self.data.try_write() {
Ok(guard) => Poll::Ready(guard),
Err(TryLockError::WouldBlock) => Poll::Pending,
Err(TryLockError::Poisoned(_)) => panic!("lock poisoned"),
})
}

pub fn read<'a>(&'a self) -> impl Future<Output = RwLockReadGuard<'a, HashTable<(K, V)>>> {
std::future::poll_fn(|_ctx| match self.data.try_read() {
Ok(guard) => Poll::Ready(guard),
Err(TryLockError::WouldBlock) => Poll::Pending,
Err(TryLockError::Poisoned(_)) => panic!("lock poisoned"),
})
}
}

impl<K, V> std::ops::Deref for Shard<K, V> {
Expand Down

0 comments on commit a812b42

Please sign in to comment.