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
//! DHashMap is a threadsafe concurrent hashmap with good allround performance and a tuned for both reads and writes.
//!
//! The API mostly matches that of the standard library hashmap but there are some
//! differences to due to the design of the hashmap.

use hashbrown::HashMap;
use crate::parking_lot::RwLock;
use crate::std::hash::Hash;
use crate::std::hash::Hasher;
use crate::std::ops::{Deref, DerefMut};
use crate::std::vec::Vec;

/// The amount of bits to look at when determining maps.
const NCB: u64 = 8;

// Amount of shards. Equals 2^NCB.
const NCM: usize = 1 << NCB;

#[derive(Default)]
pub struct DHashMap<K, V>
where
    K: Hash + Eq,
{
    submaps: Vec<RwLock<HashMap<K, V>>>,
    hash_nonce: u64,
}

impl<'a, K: 'a, V: 'a> DHashMap<K, V>
where
    K: Hash + Eq,
{
    #[cfg(feature = "std")]
    #[cfg_attr(feature = "std", inline(always))]
    pub fn new() -> Self {
        if !check_opt(NCB, NCM) {
            panic!("dhashmap params illegal");
        }

        Self {
            submaps: (0..NCM).map(|_| RwLock::new(HashMap::new())).collect(),
            hash_nonce: rand::random(),
        }
    }

    pub fn with_nonce(hash_nonce: u64) -> Self {
        if !check_opt(NCB, NCM) {
            panic!("dhashmap params illegal");
        }

        Self {
            submaps: (0..NCM).map(|_| RwLock::new(HashMap::new())).collect(),
            hash_nonce,
        }
    }

    #[inline(always)]
    pub fn insert(&self, key: K, value: V) {
        let mapi = self.determine_map(&key);
        let mut submap = unsafe { self.submaps.get_unchecked(mapi).write() };
        submap.insert(key, value);
    }

    #[inline(always)]
    pub fn contains_key(&self, key: &K) -> bool {
        let mapi = self.determine_map(&key);
        let submap = unsafe { self.submaps.get_unchecked(mapi).read() };
        submap.contains_key(&key)
    }

    #[inline(always)]
    pub fn get(&'a self, key: &'a K) -> Option<DHashMapRef<'a, K, V>> {
        let mapi = self.determine_map(&key);
        let submap = unsafe { self.submaps.get_unchecked(mapi).read() };
        if submap.contains_key(&key) {
            Some(DHashMapRef { lock: submap, key })
        } else {
            None
        }
    }

    #[inline(always)]
    pub fn get_mut(&'a self, key: &'a K) -> Option<DHashMapRefMut<'a, K, V>> {
        let mapi = self.determine_map(&key);
        let submap = unsafe { self.submaps.get_unchecked(mapi).write() };
        if submap.contains_key(&key) {
            Some(DHashMapRefMut { lock: submap, key })
        } else {
            None
        }
    }

    #[inline(always)]
    pub fn remove(&self, key: &K) -> Option<(K, V)> {
        let mapi = self.determine_map(&key);
        let mut submap = unsafe { self.submaps.get_unchecked(mapi).write() };
        submap.remove_entry(key)
    }

    #[inline(always)]
    pub fn retain<F: Clone + FnMut(&K, &mut V) -> bool>(&self, f: F) {
        self.submaps.iter().for_each(|locked| {
            let mut submap = locked.write();
            submap.retain(f.clone());
        });
    }

    #[inline(always)]
    pub fn clear(&self) {
        self.submaps.iter().for_each(|locked| {
            let mut submap = locked.write();
            submap.clear();
        });
    }

    #[inline(always)]
    pub fn submaps_read(
        &self,
    ) -> impl Iterator<Item = crate::parking_lot::RwLockReadGuard<HashMap<K, V>>> {
        self.submaps.iter().map(RwLock::read)
    }

    #[inline(always)]
    pub fn submaps_write(
        &self,
    ) -> impl Iterator<Item = crate::parking_lot::RwLockWriteGuard<HashMap<K, V>>> {
        self.submaps.iter().map(RwLock::write)
    }

    #[inline(always)]
    pub fn determine_map(&self, key: &K) -> usize {
        let mut hash_state = fxhash::FxHasher64::default();
        hash_state.write_u64(self.hash_nonce);
        key.hash(&mut hash_state);

        let hash = hash_state.finish();
        let shift = 64 - NCB;

        (hash >> shift) as usize
    }
}

#[inline(always)]
fn check_opt(ncb: u64, ncm: usize) -> bool {
    2_u64.pow(ncb as u32) == ncm as u64
}

pub struct DHashMapRef<'a, K, V>
where
    K: Hash + Eq,
{
    pub lock: crate::parking_lot::RwLockReadGuard<'a, HashMap<K, V>>,
    pub key: &'a K,
}

impl<'a, K, V> Deref for DHashMapRef<'a, K, V>
where
    K: Hash + Eq,
{
    type Target = V;

    #[inline(always)]
    fn deref(&self) -> &V {
        self.lock.get(self.key).unwrap()
    }
}

pub struct DHashMapRefMut<'a, K, V>
where
    K: Hash + Eq,
{
    pub lock: crate::parking_lot::RwLockWriteGuard<'a, HashMap<K, V>>,
    pub key: &'a K,
}

impl<'a, K, V> Deref for DHashMapRefMut<'a, K, V>
where
    K: Hash + Eq,
{
    type Target = V;

    #[inline(always)]
    fn deref(&self) -> &V {
        self.lock.get(self.key).unwrap()
    }
}

impl<'a, K, V> DerefMut for DHashMapRefMut<'a, K, V>
where
    K: Hash + Eq,
{
    #[inline(always)]
    fn deref_mut(&mut self) -> &mut V {
        self.lock.get_mut(self.key).unwrap()
    }
}

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

    #[test]
    fn insert_then_assert_64() {
        let map = DHashMap::new();

        for i in 0..64_i32 {
            map.insert(i, i * 2);
        }

        for i in 0..64_i32 {
            assert_eq!(i * 2, *map.get(&i).unwrap());
        }
    }
}