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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
//! See struct level documentation.

mod raw;

#[cfg(test)]
mod tests;

use crate::uniform_allocator::UniformAllocator;
use crate::util::UniformAllocExt;
use ccl_crossbeam_epoch::{self as epoch, Guard, Owned};
use rand::prelude::*;
pub use raw::{TableRef, TableIter};
use raw::{Bucket, Entry as RawEntry, Table};
use std::hash::Hash;
use std::sync::Arc;
use std::rc::Rc;
use std::fmt;

// TO-DO: fix vanishing items when inserting concurrent from multiple threads

pub struct OccupiedEntry<'a, K: Hash + Eq, V> {
    map: &'a NestedMap<K, V>,
    guard: Guard,
    r: TableRef<'a, K, V>,
    key: K,
}

impl<'a, K: Hash + Eq, V> OccupiedEntry<'a, K, V> {
    #[inline]
    pub fn new(guard: Guard, map: &'a NestedMap<K, V>, r: TableRef<'a, K, V>, key: K) -> Self {
        Self {
            map,
            guard,
            r,
            key,
        }
    }

    #[inline]
    pub fn key(&self) -> &K {
        self.r.key()
    }

    #[inline]
    pub fn remove(self) {
        self.map.remove_with_guard(self.r.key(), &self.guard);
    }

    #[inline]
    pub fn get(&self) -> &V {
        self.r.value()
    }

    #[inline]
    pub fn insert(self, value: V) {
        self.map.insert_with_guard(self.key, value, &self.guard);
    }

    #[inline]
    pub fn into_ref(self) -> TableRef<'a, K, V> {
        self.r
    }
}

pub struct VacantEntry<'a, K: Hash + Eq, V> {
    map: &'a NestedMap<K, V>,
    guard: Guard,
    key: K,
}

impl<'a, K: Hash + Eq, V> VacantEntry<'a, K, V> {
    #[inline]
    pub fn new(guard: Guard, map: &'a NestedMap<K, V>, key: K) -> Self {
        Self {
            map,
            guard,
            key,
        }
    }

    #[inline]
    pub fn insert(self, value: V) {
        self.map.insert_with_guard(self.key, value, &self.guard);
    }

    #[inline]
    pub fn into_key(self) -> K {
        self.key
    }

    #[inline]
    pub fn key(&self) -> &K {
        &self.key
    }
}

impl<'a, K: Hash + Eq + Clone, V> VacantEntry<'a, K, V> {
    #[inline]
    pub fn insert_with_ret(self, value: V) -> (&'a NestedMap<K, V>, Guard, K) {
        self.map.insert_with_guard(self.key.clone(), value, &self.guard);
        (self.map, self.guard, self.key)
    }
}

pub enum Entry<'a, K: Hash + Eq, V> {
    Occupied(OccupiedEntry<'a, K, V>),
    Vacant(VacantEntry<'a, K, V>),
}

impl<'a, K: Hash + Eq, V> Entry<'a, K, V> {
    #[inline]
    pub fn is_occupied(&self) -> bool {
        if let Entry::Occupied(_) = self {
            true
        } else {
            false
        }
    }

    #[inline]
    pub fn into_occupied(self) -> Option<OccupiedEntry<'a, K, V>> {
        if let Entry::Occupied(v) = self {
            Some(v)
        } else {
            None
        }
    }

    #[inline]
    pub fn is_vacant(&self) -> bool {
        if let Entry::Vacant(_) = self {
            true
        } else {
            false
        }
    }

    #[inline]
    pub fn into_vacant(self) -> Option<VacantEntry<'a, K, V>> {
        if let Entry::Vacant(v) = self {
            Some(v)
        } else {
            None
        }
    }

    #[inline]
    pub fn key(&self) -> &K {
        match self {
            Entry::Occupied(v) => v.key(),
            Entry::Vacant(v) => v.key(),
        }
    }

    #[inline]
    pub fn and_inspect<F: FnOnce(&V)>(self, f: F) -> Self {
        if let Entry::Occupied(occupied) = &self {
            f(occupied.get());
        }

        self
    }
}

impl<'a, K: Hash + Eq + Clone, V> Entry<'a, K, V>  {
    pub fn or_insert(self, default: V) -> TableRef<'a, K, V> {
        match self {
            Entry::Occupied(occupied) => occupied.into_ref(),
            Entry::Vacant(vacant) => {
                let (map, guard, key) = vacant.insert_with_ret(default);
                map.get_with_guard(&key, guard).expect("this should never happen; nestedmap entry or_insert")
            }
        }
    }

    pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> TableRef<'a, K, V> {
        match self {
            Entry::Occupied(occupied) => occupied.into_ref(),
            Entry::Vacant(vacant) => {
                let (map, guard, key) = vacant.insert_with_ret(default());
                map.get_with_guard(&key, guard).expect("this should never happen; nestedmap entry or_insert")
            }
        }
    }
}

#[inline]
pub fn aquire_guard() -> Guard {
    epoch::pin()
}

/// NestedMap is a threadsafe concurrent hashmap with generally good performance.
///
///
/// The primary difference compared to DHashMap is that NestedMap is lockfree and non-blocking which
/// makes it more appealing for latency critical things. It also has faster reads that DHashMap.
pub struct NestedMap<K: Hash + Eq, V> {
    root: Table<K, V>,
}

impl<'a, K: 'a + Hash + Eq, V: 'a> NestedMap<K, V> {
    /// Create a new completely empty map.
    pub fn new() -> Self {
        Self {
            root: Table::empty(Arc::new(UniformAllocator::default())),
        }
    }

    /// Create a new map but the root table is prefilled. This may make rapid initial growth more efficient.
    pub fn new_layer_prefill() -> Self {
        Self {
            root: Table::layer_pregen(Arc::new(UniformAllocator::default()), 1),
        }
    }

    /// Insert a value into the map.
    #[inline]
    pub fn insert(&self, key: K, value: V) {
        let guard = &epoch::pin();
        self.insert_with_guard(key, value, guard);
    }

    /// Insert a value into the map with an existing guard, saving on guard creation.
    #[inline]
    pub fn insert_with_guard(&self, key: K, value: V, guard: &Guard) {
        let tag: u8 = rand::thread_rng().gen();

        let bucket = Owned::uniform_alloc(
            self.root.allocator(),
            tag as usize,
            Bucket::Leaf(tag, RawEntry { key, value }),
        );
        self.root.insert(bucket, guard);
    }

    /// Get a reference to a value in the map.
    #[inline]
    pub fn get(&'a self, key: &K) -> Option<TableRef<'a, K, V>> {
        let guard = epoch::pin();
        self.get_with_guard(key, guard)
    }

    /// Get a value from the map with an existing guard, saving on guard cration.
    #[inline]
    pub fn get_with_guard(&'a self, key: &K, guard: Guard) -> Option<TableRef<'a, K, V>> {
        self.root.get(key, guard)
    }

    /// Remove an item from the map.
    #[inline]
    pub fn remove(&self, key: &K) {
        let guard = &epoch::pin();
        self.remove_with_guard(key, guard);
    }

    /// Remove an item from the map with an existing guard, saving on guard creation.
    #[inline]
    pub fn remove_with_guard(&self, key: &K, guard: &Guard) {
        self.root.remove(key, guard);
    }

    /// Check if the map contains a given key.
    #[inline]
    pub fn contains_key(&self, key: &K) -> bool {
        let guard = epoch::pin();
        self.root.contains_key(key, guard)
    }

    /// Iterate over all items in a map.
    #[inline]
    pub fn iter(&'a self) -> TableIter<'a, K, V> {
        let guard = Rc::new(epoch::pin());
        self.root.iter(guard)
    }

    /// Get the amount of elements in the map.
    #[inline]
    pub fn len(&self) -> usize {
        let guard = &epoch::pin();
        self.root.len(guard)
    }

    /// Check if the map is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Get an entry from the map.
    #[inline]
    pub fn entry(&'a self, key: K) -> Entry<'a, K, V> {
        let guard = epoch::pin();

        match self.get(&key) {
            None => Entry::Vacant(VacantEntry::new(guard, self, key)),
            Some(r) => Entry::Occupied(OccupiedEntry::new(guard, self, r, key)),
        }
    }

    /// Extend the map with an iterator.
    #[inline]
    pub fn extend<I: IntoIterator<Item = (K, V)>>(&self, iter: I) {
        let guard = &epoch::pin();

        for pair in iter {
            self.insert_with_guard(pair.0, pair.1, guard);
        }
    }
}

impl<'a, K: 'a + Hash + Eq, V: 'a> Default for NestedMap<K, V> {
    fn default() -> Self {
        Self::new()
    }
}

impl<'a, K: 'a + Hash + Eq, V: 'a> fmt::Debug for NestedMap<K, V> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "NestedMap {{}}")
    }
}