async_map/
lib.rs

1//! This crate provides data-structure for concurrent use by many tasks in an asynschronous contexts,
2//! with a particular focus on high-read/low-write situations.
3#![crate_name = "async_map"]
4#![macro_use]
5#[doc(hidden)] // Really just to provide a comparison for bechmarking
6pub mod lockingmap;
7pub mod non_locking_map;
8pub mod single_writer_versioned;
9mod versioned_map;
10
11use std::borrow::Borrow;
12use std::future::Future;
13use std::hash::Hash;
14use std::pin::Pin;
15
16pub use versioned_map::VersionedMap;
17
18/// A trait for types that can be held in a collection used in an asynchronous context,
19/// which might be shared between many tasks. A blanket implementation is provided.
20pub trait AsyncStorable: Clone + Send + Sync + std::fmt::Debug + Unpin + 'static {}
21impl<T: Clone + Send + Sync + Unpin + std::fmt::Debug + 'static> AsyncStorable for T {}
22
23/// A trait for types that can be keys in an asynchronous map. A blanket implementation is provided.
24pub trait AsyncKey: AsyncStorable + Hash + Eq {}
25impl<T: AsyncStorable + Hash + Eq> AsyncKey for T {}
26
27/// A trait for factory methods that can be used to create new values for a key in an asynchronous map. A blanket implementation is provided.
28pub trait AsyncFactory<K: AsyncKey, V: AsyncStorable>:
29    (Fn(&K) -> V) + Send + Sync + 'static
30{
31}
32impl<K: AsyncKey, V: AsyncStorable, F: (Fn(&K) -> V) + Send + Sync + 'static> AsyncFactory<K, V>
33    for F
34{
35}
36
37/// A trait for types from which a factory method can be borrowed. A blanket implementation is provided.
38pub trait FactoryBorrow<K: AsyncKey, V: AsyncStorable>:
39    Borrow<dyn AsyncFactory<K, V>> + Send + Unpin + 'static
40{
41}
42
43impl<K: AsyncKey, V: AsyncStorable, T: Borrow<dyn AsyncFactory<K, V>> + Send + Unpin + 'static>
44    FactoryBorrow<K, V> for T
45{
46}
47
48pub trait AsyncMap: Clone + Send {
49    type Key: AsyncKey;
50    type Value: AsyncStorable;
51    fn get_if_present(&self, key: &Self::Key) -> Option<Self::Value>;
52
53    fn get<'a, 'b, B: FactoryBorrow<Self::Key, Self::Value>>(
54        &'a self,
55        key: &'a Self::Key,
56        factory: B,
57    ) -> Pin<Box<dyn Future<Output = Self::Value> + Send + 'b>>;
58}
59
60#[cfg(test)]
61mod tests {
62    #[test]
63    fn it_works() {
64        assert_eq!(2 + 2, 4);
65    }
66}