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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
use crate::uniform_allocator::UniformAllocator;
use crate::util;
use crate::util::sharedptr_null;
use crate::util::UniformAllocExt;
use crate::util::UniformDeallocExt;
use ccl_crossbeam_epoch::{self as epoch, Atomic, Guard, Owned, Shared};
use rand::prelude::*;
use std::hash::Hash;
use std::mem;
use std::ops::Deref;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use crate::util::UnsafeOption;
use std::rc::Rc;

const TABLE_SIZE: usize = 96;

pub struct Entry<K: Hash + Eq, V> {
    pub key: K,
    pub value: V,
}

pub enum Bucket<K: Hash + Eq, V> {
    Leaf(u8, Entry<K, V>),
    Branch(u8, Table<K, V>),
}

impl<K: Hash + Eq, V> Bucket<K, V> {
    #[inline]
    fn key_ref(&self) -> &K {
        if let Bucket::Leaf(_, entry) = self {
            &entry.key
        } else {
            panic!("bucket unvalid key get")
        }
    }

    #[inline]
    fn tag(&self) -> u8 {
        match self {
            Bucket::Leaf(tag, _) => *tag,
            Bucket::Branch(tag, _) => *tag,
        }
    }
}

pub struct Table<K: Hash + Eq, V> {
    nonce: u8,
    buckets: Box<[Atomic<Bucket<K, V>>; TABLE_SIZE]>,
    allocator: Arc<UniformAllocator<Bucket<K, V>>>,
}

pub struct TableRef<'a, K: Hash + Eq, V> {
    guard: Option<epoch::Guard>,
    ptr: &'a Entry<K, V>,
}

impl<'a, K: Hash + Eq, V> Drop for TableRef<'a, K, V> {
    #[inline]
    fn drop(&mut self) {
        let guard = self.guard.take();
        mem::drop(guard);
    }
}

impl<'a, K: Hash + Eq, V> TableRef<'a, K, V> {
    #[inline]
    pub fn key(&self) -> &K {
        &self.ptr.key
    }

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

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

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

impl<K: Hash + Eq, V> Drop for Table<K, V> {
    #[inline]
    fn drop(&mut self) {
        self.buckets.iter().for_each(|ptr| {
            let ptr = unsafe { ptr.load(Ordering::Relaxed, epoch::unprotected()) };
            if !ptr.is_null() {
                unsafe {
                    ptr.uniform_dealloc(&self.allocator, ptr.deref().tag() as usize);
                }
            }
        });
    }
}

impl<'a, K: 'a + Hash + Eq, V: 'a> Table<K, V> {
    #[inline]
    pub fn allocator(&self) -> &UniformAllocator<Bucket<K, V>> {
        &self.allocator
    }

    #[inline]
    fn with_two_entries(
        allocator: Arc<UniformAllocator<Bucket<K, V>>>,
        entry_1: Shared<'a, Bucket<K, V>>,
        entry_2: Shared<'a, Bucket<K, V>>,
    ) -> Self {
        let mut table = Self::empty(allocator);
        let entry_1_pos = unsafe {
            util::hash_with_nonce(entry_1.as_ref().unsafe_unwrap().key_ref(), table.nonce) as usize
                % TABLE_SIZE
        };
        let entry_2_pos = unsafe {
            util::hash_with_nonce(entry_2.as_ref().unsafe_unwrap().key_ref(), table.nonce) as usize
                % TABLE_SIZE
        };

        if entry_1_pos != entry_2_pos {
            table.buckets[entry_1_pos].store(entry_1, Ordering::Relaxed);
            table.buckets[entry_2_pos].store(entry_2, Ordering::Relaxed);
        } else {
            let tag: u8 = rand::thread_rng().gen();
            table.buckets[entry_1_pos] = Atomic::uniform_alloc(
                &table.allocator,
                tag as usize,
                Bucket::Branch(
                    tag,
                    Table::with_two_entries(table.allocator.clone(), entry_1, entry_2),
                ),
            );
        }

        table
    }

    #[inline]
    pub fn empty(allocator: Arc<UniformAllocator<Bucket<K, V>>>) -> Self {
        Self {
            nonce: rand::thread_rng().gen(),
            buckets: unsafe { Box::new(mem::zeroed()) },
            allocator,
        }
    }

    #[inline]
    pub fn get(&'a self, key: &K, guard: Guard) -> Option<TableRef<'a, K, V>> {
        let fake_guard = unsafe { epoch::unprotected() };
        let key_pos = util::hash_with_nonce(key, self.nonce) as usize % TABLE_SIZE;

        let bucket_shared: Shared<'a, Bucket<K, V>> =
            self.buckets[key_pos].load(Ordering::Relaxed, fake_guard);

        if bucket_shared.is_null() {
            None
        } else {
            let bucket_ref = unsafe { bucket_shared.deref() };

            match bucket_ref {
                Bucket::Leaf(_, entry) => {
                    if &entry.key == key {
                        Some(TableRef {
                            guard: Some(guard),
                            ptr: entry,
                        })
                    } else {
                        None
                    }
                }

                Bucket::Branch(_, table) => table.get(key, guard),
            }
        }
    }

    #[inline]
    pub fn contains_key(&'a self, key: &K, guard: Guard) -> bool {
        self.get(key, guard).is_some()
    }

    #[inline]
    pub fn insert(&self, entry: Owned<Bucket<K, V>>, guard: &Guard) {
        let key_pos = util::hash_with_nonce(entry.key_ref(), self.nonce) as usize % TABLE_SIZE;
        let bucket = &self.buckets[key_pos];

        let mut entry = Some(entry);

        match bucket.compare_and_set(
            sharedptr_null(),
            unsafe { entry.unsafe_take().unsafe_unwrap() },
            Ordering::Release,
            guard,
        ) {
            Ok(_) => {}

            Err(err) => {
                entry = Some(err.new);
                let actual = err.current;
                let actual_ref = unsafe { actual.as_ref().expect("insert1 null") };

                let entry = unsafe { entry.unsafe_take().unsafe_unwrap() };
                match actual_ref {
                    Bucket::Branch(_, ref table) => table.insert(entry, guard),
                    Bucket::Leaf(actual_tag, ref old_entry) => {
                        if entry.key_ref() == &old_entry.key {
                            bucket.store(entry, Ordering::Release);
                            unsafe {
                                guard.defer_unchecked(|| {
                                    actual.uniform_dealloc(&self.allocator, *actual_tag as usize);
                                })
                            }
                        } else {
                            let tag: u8 = rand::thread_rng().gen();

                            let new_table = Owned::uniform_alloc(
                                &self.allocator,
                                tag as usize,
                                Bucket::Branch(
                                    tag,
                                    Table::with_two_entries(
                                        self.allocator.clone(),
                                        actual,
                                        entry.into_shared(guard),
                                    ),
                                ),
                            );
                            bucket.store(new_table, Ordering::Release);
                        }
                    }
                }
            }
        }
    }

    #[inline]
    pub fn remove(&self, key: &K, guard: &Guard) {
        let key_pos = util::hash_with_nonce(key, self.nonce) as usize % TABLE_SIZE;

        let bucket_sharedptr = self.buckets[key_pos].load(Ordering::Acquire, guard);

        if let Some(bucket_ref) = unsafe { bucket_sharedptr.as_ref() } {
            match bucket_ref {
                Bucket::Branch(_, table) => table.remove(key, guard),
                Bucket::Leaf(tag, _) => {
                    let res = self.buckets[key_pos].compare_and_set(
                        bucket_sharedptr,
                        sharedptr_null(),
                        Ordering::Release,
                        guard,
                    );

                    if res.is_ok() {
                        unsafe {
                            guard.defer_unchecked(|| {
                                bucket_sharedptr.uniform_dealloc(&self.allocator, *tag as usize);
                            })
                        };
                    }
                }
            }
        }
    }

    #[inline]
    pub fn iter(&'a self, guard: Rc<Guard>) -> TableIter<'a, K, V> {
        TableIter {
            table: self,
            idx: 0,
            guard,
            current_subiter: Box::new(None),
        }
    }

    #[inline]
    pub fn len(&self, guard: &'a Guard) -> usize {
        let mut l = 0;
        let mut idx = 0;

        while idx < TABLE_SIZE {
            let bucket_shared: Shared<'a, Bucket<K, V>> =
                self.buckets[idx].load(Ordering::Relaxed, guard);

            if let Some(r) = unsafe { bucket_shared.as_ref() } {
                match r {
                    Bucket::Leaf(_, _) => l += 1,
                    Bucket::Branch(_, table) => l += table.len(guard),
                }
            }

            idx += 1;
        }

        l
    }
}

pub struct TableIter<'a, K: Hash + Eq, V> {
    table: &'a Table<K, V>,
    idx: usize,
    guard: Rc<Guard>,
    current_subiter: Box<Option<TableIter<'a, K, V>>>,
}

impl<'a, K: Hash + Eq, V> Iterator for TableIter<'a, K, V> {
    type Item = TableRef<'a, K, V>;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        // Check if we contains a iterator to a subtable.
        if let Some(subiter) = &mut *self.current_subiter {
            // Fetch element from subiter. If it's Some we return it.
            // If it isn't we discard the iterator.
            if let Some(v) = subiter.next() {
                return Some(v);
            } else {
                // Discard iterator.
                *self.current_subiter = None;
            }
        }

        loop {
            // We have checked every entry in the table and none is left.
            if self.idx == TABLE_SIZE {
                return None;
            }

            if let Some(bucket_ref) = unsafe { self.table.buckets[self.idx].load(Ordering::Relaxed, epoch::unprotected()).as_ref() } {
                self.idx += 1;

                match bucket_ref {
                    Bucket::Leaf(_, entry) => {
                        return Some(TableRef {
                            guard: Some(epoch::pin()),
                            ptr: entry,
                        });
                    }

                    Bucket::Branch(_, table) => {
                        *self.current_subiter = Some(table.iter(self.guard.clone()));
                        return self.next();
                    }
                }
            } else {
                self.idx += 1;
            }
        }
    }
}