1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
//! A generic sharded locking mechanism for hash based collections to speed up concurrent reads/writes. `Shard::new` splits
//! the underlying collection into N shards each with its own lock. Calling `read(key)` or `write(key)`
//! returns a guard for only a single shard. The underlying locks should be generic, so you can use
//! it with any `Mutex` or `RwLock` in `std::sync` or `parking_lot`.
//!
//! In a probably wrong and unscientific test of concurrent readers/single writer,
//! `shard_lock` is **100-∞∞x faster** (deadlocks?) than [`dashmap`](https://github.com/xacrimon/dashmap), and
//! **13x faster** than a single `parking_lot::RwLock`. Carrying `Shard<RwLock<T>>` is possibly more obvious
//! and simpler than other approaches. The library has a very small footprint at ~100 loc and optionally no
//! dependencies.
//!
//! `shard_lock` is flexible enough to shard any hash based collection such as `HashMap`, `HashSet`, `BTreeMap`, and `BTreeSet`.
//!
//! _**Warning:** shard_lock is in early development and unsuitable for production. The API is undergoing changes and is not dependable._
#![forbid(unsafe_code)]
#![allow(dead_code)]
#![allow(unused_macros)]
#![allow(incomplete_features)]
#![feature(generic_associated_types)]
#![feature(in_band_lifetimes)]

#[cfg(feature = "3rd-party")]
use ahash::AHasher as DefaultHasher;

#[cfg(not(feature = "3rd-party"))]
use std::collections::hash_map::DefaultHasher;

use std::hash::Hasher;

#[cfg(feature = "3rd-party")]
use hashbrown::HashMap;

#[cfg(feature = "3rd-party")]
use hashbrown::HashSet;

#[cfg(not(feature = "3rd-party"))]
use std::collections::HashMap;

#[cfg(not(feature = "3rd-party"))]
use std::collections::HashSet;

#[cfg(feature = "3rd-party")]
use parking_lot;

#[cfg(feature = "3rd-party")]
mod parking_lock;

#[cfg(not(feature = "3rd-party"))]
mod std_lock;

#[cfg(feature = "3rd-party")]
pub type RwLock<T> = parking_lot::RwLock<T>;

#[cfg(not(feature = "3rd-party"))]
pub type RwLock<T> = std::sync::RwLock<T>;

/// Sharded lock-based concurrent map using the crate default lock and map implementations.
pub type Map<K, V> = Shard<RwLock<HashMap<K, V>>>;

/// Sharded lock-based concurrent set using the crate default lock and set implementations.
pub type Set<K> = Shard<RwLock<HashSet<K>>>;

use std::hash::Hash;

// Global shard count for collections
// TODO configurable via construction
const SHARD_COUNT: usize = 128;

/// Generic locking implementation.
pub trait Lock<T> {
    #[rustfmt::skip]
    type ReadGuard<'a> where T: 'a;
    #[rustfmt::skip]
    type WriteGuard<'a> where T: 'a;

    fn new(t: T) -> Self;

    fn write(&self) -> Self::WriteGuard<'_>;

    fn read(&self) -> Self::ReadGuard<'_>;
}

/// Teases out the sharding key for example
/// from an IntoIterator value.
pub trait ExtractShardKey<K: Hash> {
    fn key(&self) -> &K;
}

/// Basic methods needing implemented for shard construction
pub trait Collection<K, Value>: IntoIterator<Item = Value> + Clone
where
    K: Hash,
    Value: ExtractShardKey<K>,
{
    fn with_capacity(capacity: usize) -> Self;

    fn insert(&mut self, v: Value);

    fn len(&self) -> usize;

    fn capacity(&self) -> usize;
}

// Takes key from map iter values
impl<K: Hash, V> ExtractShardKey<K> for (K, V) {
    fn key(&self) -> &K {
        &self.0
    }
}

impl<K, V> Collection<K, (K, V)> for HashMap<K, V>
where
    K: Hash + Clone + Eq,
    V: Clone,
{
    fn with_capacity(capacity: usize) -> Self {
        Self::with_capacity(capacity)
    }

    fn insert(&mut self, v: (K, V)) {
        HashMap::insert(self, v.0, v.1);
    }

    fn len(&self) -> usize {
        self.len()
    }

    fn capacity(&self) -> usize {
        self.capacity()
    }
}

/// The sharded lock collection. This is the main data type in the crate. See also the type aliases
/// `Map`, `Set`, and so on.
///
/// # Examples
///
/// ```ignore
/// use sharded::Shard;
///
/// let users = Shard::from(HashMap::new());
///
/// let guard = users.read("uid-31356");
///
/// guard.get("uid-31356");
/// ```
pub struct Shard<T> {
    shards: Vec<T>,
}

impl<K: Hash> Shard<K> {
    /// Create a new shard from an existing collection
    pub fn from<V, U, L>(inner: U) -> Shard<L>
    where
        V: ExtractShardKey<K>,
        U: Collection<K, V>,
        L: Lock<U>,
    {
        let mut shards = vec![U::with_capacity(inner.len() / SHARD_COUNT); SHARD_COUNT];

        inner.into_iter().for_each(|item| {
            // for each item, push it to the appropriate shard
            let i = index(item.key());
            if let Some(shard) = shards.get_mut(i) {
                shard.insert(item)
            } else {
                panic!(
                    "We just initialized shards to `SHARD_COUNT` and hash % `SHARD_COUNT`
                    should be bounded"
                );
            }
        });

        let shards = shards.into_iter().map(|shard| L::new(shard)).collect();

        Shard { shards }
    }
}

fn index<K: Hash>(k: &K) -> usize {
    let mut s = DefaultHasher::default();
    k.hash(&mut s);
    (s.finish() as usize % SHARD_COUNT) as usize
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn read_and_write() {
        let x: Shard<RwLock<HashMap<String, String>>> = Shard::from(HashMap::new());

        x.write(&"key".to_string())
            .insert("key".to_string(), "value".to_string());

        assert_eq!(
            x.read(&"key".to_string()).get(&"key".to_string()).unwrap(),
            "value"
        );
    }

    #[test]
    fn hold_read_and_write() {
        let map = Shard::from(HashMap::new());

        let mut write = map.write(&"abc".to_string());
        write.insert("abc".to_string(), "asdf".to_string());

        let _read = map.read(&"asdfas".to_string());
        let _read_too = map.read(&"asdfas".to_string());
        assert!(_read.is_empty());
    }
}