chashmap-async 0.1.0

Concurrent async hash maps with key-scoped locking
Documentation
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use crate::{CHashMap, MAX_LOAD_FACTOR_DENOM};
use std::cell::RefCell;
use std::sync::Arc;

use tokio::{task, test};

#[test]
async fn spam_insert() {
    let map = Arc::new(CHashMap::new());
    let mut joins = Vec::new();

    for t in 0..10 {
        let map = map.clone();
        joins.push(task::spawn(async move {
            for i in t * 1000..(t + 1) * 1000 {
                assert!(map.insert(i, !i).await.is_none());
                assert_eq!(map.insert(i, i).await.unwrap(), !i);
            }
        }));
    }

    for j in joins.drain(..) {
        j.await.unwrap();
    }

    for t in 0..5 {
        let map = map.clone();
        joins.push(task::spawn(async move {
            for i in t * 2000..(t + 1) * 2000 {
                assert_eq!(*map.get(&i).await.unwrap(), i);
            }
        }));
    }

    for j in joins {
        j.await.unwrap();
    }
}

#[test]
async fn spam_insert_new() {
    let m = Arc::new(CHashMap::new());
    let mut joins = Vec::new();

    for t in 0..10 {
        let m = m.clone();
        joins.push(task::spawn(async move {
            for i in t * 1000..(t + 1) * 1000 {
                m.insert_new(i, i).await;
            }
        }));
    }

    for join in joins.drain(..) {
        join.await.unwrap();
    }

    for t in 0..5 {
        let m = m.clone();
        joins.push(task::spawn(async move {
            for i in t * 2000..(t + 1) * 2000 {
                assert_eq!(*m.get(&i).await.unwrap(), i);
            }
        }));
    }

    for join in joins {
        join.await.unwrap();
    }
}

#[test]
async fn spam_upsert() {
    let m = Arc::new(CHashMap::new());
    let mut joins = Vec::new();

    for t in 0..10 {
        let m = m.clone();
        joins.push(task::spawn(async move {
            for i in t * 1000..(t + 1) * 1000 {
                m.upsert(i, || !i, |_| unreachable!()).await;
                m.upsert(i, || unreachable!(), |x| *x = !*x).await;
            }
        }));
    }

    for j in joins.drain(..) {
        j.await.unwrap();
    }

    for t in 0..5 {
        let m = m.clone();
        joins.push(task::spawn(async move {
            for i in t * 2000..(t + 1) * 2000 {
                assert_eq!(*m.get(&i).await.unwrap(), i);
            }
        }));
    }

    for j in joins {
        j.await.unwrap();
    }
}

#[test]
async fn spam_alter() {
    let m = Arc::new(CHashMap::new());
    let mut joins = Vec::new();

    for t in 0..10 {
        let m = m.clone();
        joins.push(task::spawn(async move {
            for i in t * 1000..(t + 1) * 1000 {
                m.alter(i, |x| async move {
                    assert!(x.is_none());
                    Some(!i)
                })
                .await;
                m.alter(i, |x| async move {
                    assert_eq!(x, Some(!i));
                    Some(!x.unwrap())
                })
                .await;
            }
        }));
    }

    for j in joins.drain(..) {
        j.await.unwrap();
    }

    for t in 0..5 {
        let m = m.clone();
        joins.push(task::spawn(async move {
            for i in t * 2000..(t + 1) * 2000 {
                assert_eq!(*m.get(&i).await.unwrap(), i);
                m.alter(i, |_| async { None }).await;
                assert!(m.get(&i).await.is_none());
            }
        }));
    }

    for j in joins {
        j.await.unwrap();
    }
}

#[test]
async fn lock_compete() {
    let m = Arc::new(CHashMap::new());

    m.insert("hey", "nah").await;

    let k = m.clone();
    let a = task::spawn(async move {
        *k.get_mut(&"hey").await.unwrap() = "hi";
    });
    let k = m.clone();
    let b = task::spawn(async move {
        *k.get_mut(&"hey").await.unwrap() = "hi";
    });

    a.await.unwrap();
    b.await.unwrap();

    assert_eq!(*m.get(&"hey").await.unwrap(), "hi");
}

#[test]
async fn simultanous_reserve() {
    let m = Arc::new(CHashMap::new());
    let mut joins = Vec::new();

    m.insert(1, 2).await;
    m.insert(3, 6).await;
    m.insert(8, 16).await;

    for _ in 0..10 {
        let m = m.clone();
        joins.push(task::spawn(async move {
            m.reserve(1000).await;
        }));
    }

    for j in joins {
        j.await.unwrap()
    }

    assert_eq!(*m.get(&1).await.unwrap(), 2);
    assert_eq!(*m.get(&3).await.unwrap(), 6);
    assert_eq!(*m.get(&8).await.unwrap(), 16);
}

#[test]
async fn create_capacity_zero() {
    let m = CHashMap::with_capacity(0);

    assert!(m.insert(1, 1).await.is_none());

    assert!(m.contains_key(&1).await);
    assert!(!m.contains_key(&0).await);
}

#[test]
async fn insert() {
    let m = CHashMap::new();
    assert_eq!(m.len(), 0);
    assert!(m.insert(1, 2).await.is_none());
    assert_eq!(m.len(), 1);
    assert!(m.insert(2, 4).await.is_none());
    assert_eq!(m.len(), 2);
    assert_eq!(*m.get(&1).await.unwrap(), 2);
    assert_eq!(*m.get(&2).await.unwrap(), 4);
}

#[test]
async fn upsert() {
    let m = CHashMap::new();
    assert_eq!(m.len(), 0);
    m.upsert(1, || 2, |_| unreachable!()).await;
    assert_eq!(m.len(), 1);
    m.upsert(2, || 4, |_| unreachable!()).await;
    assert_eq!(m.len(), 2);
    assert_eq!(*m.get(&1).await.unwrap(), 2);
    assert_eq!(*m.get(&2).await.unwrap(), 4);
}

#[test]
async fn upsert_update() {
    let m = CHashMap::new();
    m.insert(1, 2).await;
    m.upsert(1, || unreachable!(), |x| *x += 2).await;
    m.insert(2, 3).await;
    m.upsert(2, || unreachable!(), |x| *x += 3).await;
    assert_eq!(*m.get(&1).await.unwrap(), 4);
    assert_eq!(*m.get(&2).await.unwrap(), 6);
}

#[test]
async fn alter_string() {
    let m = CHashMap::new();
    assert_eq!(m.len(), 0);
    m.alter(1, |_| async { Some(String::new()) }).await;
    assert_eq!(m.len(), 1);
    m.alter(1, |x| async {
        let mut x = x.unwrap();
        x.push('a');
        Some(x)
    })
    .await;
    assert_eq!(m.len(), 1);
    assert_eq!(&*m.get(&1).await.unwrap(), "a");
}

#[test]
async fn clear() {
    let map = CHashMap::new();
    assert!(map.insert(1, 2).await.is_none());
    assert!(map.insert(2, 4).await.is_none());
    assert_eq!(map.len(), 2);

    let transfer = map.clear().await;
    assert_eq!(transfer.len(), 2);
    assert_eq!(*transfer.get(&1).await.unwrap(), 2);
    assert_eq!(*transfer.get(&2).await.unwrap(), 4);

    assert!(map.is_empty());
    assert_eq!(map.len(), 0);

    assert_eq!(map.get(&1).await, None);
    assert_eq!(map.get(&2).await, None);
}

#[test]
async fn clear_with_retain() {
    let m = CHashMap::new();
    assert!(m.insert(1, 2).await.is_none());
    assert!(m.insert(2, 4).await.is_none());
    assert_eq!(m.len(), 2);

    m.retain(|_, _| false).await;

    assert!(m.is_empty());
    assert_eq!(m.len(), 0);

    assert_eq!(m.get(&1).await, None);
    assert_eq!(m.get(&2).await, None);
}

#[test]
async fn retain() {
    let map = CHashMap::new();
    map.insert(1, 8).await;
    map.insert(2, 9).await;
    map.insert(3, 4).await;
    map.insert(4, 7).await;
    map.insert(5, 2).await;
    map.insert(6, 5).await;
    map.insert(7, 2).await;
    map.insert(8, 3).await;

    map.retain(|key, val| key & 1 == 0 && val & 1 == 1).await;

    assert_eq!(map.len(), 4);

    for (key, val) in map {
        assert_eq!(key & 1, 0);
        assert_eq!(val & 1, 1);
    }
}

thread_local! { static DROP_VECTOR: RefCell<Vec<isize>> = RefCell::new(Vec::new()) }

#[derive(Hash, PartialEq, Eq)]
struct Dropable {
    k: usize,
}

impl Dropable {
    fn new(k: usize) -> Dropable {
        DROP_VECTOR.with(|slot| {
            slot.borrow_mut()[k] += 1;
        });

        Dropable { k }
    }
}

impl Drop for Dropable {
    fn drop(&mut self) {
        DROP_VECTOR.with(|slot| {
            slot.borrow_mut()[self.k] -= 1;
        });
    }
}

impl Clone for Dropable {
    fn clone(&self) -> Dropable {
        Dropable::new(self.k)
    }
}

#[test]
async fn drops() {
    DROP_VECTOR.with(|slot| {
        *slot.borrow_mut() = vec![0; 200];
    });

    {
        let m = CHashMap::new();

        DROP_VECTOR.with(|v| {
            for i in 0..200 {
                assert_eq!(v.borrow()[i], 0);
            }
        });

        for i in 0..100 {
            let d1 = Dropable::new(i);
            let d2 = Dropable::new(i + 100);
            m.insert(d1, d2).await;
        }

        DROP_VECTOR.with(|v| {
            for i in 0..200 {
                assert_eq!(v.borrow()[i], 1);
            }
        });

        for i in 0..50 {
            let k = Dropable::new(i);
            let v = m.remove(&k).await;

            assert!(v.is_some());

            DROP_VECTOR.with(|v| {
                assert_eq!(v.borrow()[i], 1);
                assert_eq!(v.borrow()[i + 100], 1);
            });
        }

        DROP_VECTOR.with(|v| {
            for i in 0..50 {
                assert_eq!(v.borrow()[i], 0);
                assert_eq!(v.borrow()[i + 100], 0);
            }

            for i in 50..100 {
                assert_eq!(v.borrow()[i], 1);
                assert_eq!(v.borrow()[i + 100], 1);
            }
        });
    }

    DROP_VECTOR.with(|v| {
        for i in 0..200 {
            assert_eq!(v.borrow()[i], 0);
        }
    });
}

#[test]
async fn move_iter_drops() {
    DROP_VECTOR.with(|v| {
        *v.borrow_mut() = vec![0; 200];
    });

    let hm = {
        let hm = CHashMap::new();

        DROP_VECTOR.with(|v| {
            for i in 0..200 {
                assert_eq!(v.borrow()[i], 0);
            }
        });

        for i in 0..100 {
            let d1 = Dropable::new(i);
            let d2 = Dropable::new(i + 100);
            hm.insert(d1, d2).await;
        }

        DROP_VECTOR.with(|v| {
            for i in 0..200 {
                assert_eq!(v.borrow()[i], 1);
            }
        });

        hm
    };

    // By the way, ensure that cloning doesn't screw up the dropping.
    // TODO: reimplement Clone
    //drop(hm.clone());

    {
        let mut half = hm.into_iter().take(50);

        DROP_VECTOR.with(|v| {
            for i in 0..200 {
                assert_eq!(v.borrow()[i], 1);
            }
        });

        for _ in half.by_ref() {}

        DROP_VECTOR.with(|v| {
            let nk = (0..100).filter(|&i| v.borrow()[i] == 1).count();

            let nv = (0..100).filter(|&i| v.borrow()[i + 100] == 1).count();

            assert_eq!(nk, 50);
            assert_eq!(nv, 50);
        });
    };

    DROP_VECTOR.with(|v| {
        for i in 0..200 {
            assert_eq!(v.borrow()[i], 0);
        }
    });
}

#[test]
async fn empty_pop() {
    let map: CHashMap<isize, bool> = CHashMap::new();
    assert_eq!(map.remove(&0).await, None);
}

#[test]
#[ignore]
async fn lots_of_insertions() {
    let map = CHashMap::new();

    // Try this a few times to make sure we never screw up the hashmap's internal state.
    for _ in 0..10 {
        assert!(map.is_empty());

        for i in 1..1001 {
            assert!(map.insert(i, i).await.is_none());

            for j in 1..i + 1 {
                let r = map.get(&j).await;
                assert_eq!(*r.unwrap(), j);
            }

            for j in i + 1..1001 {
                let r = map.get(&j).await;
                assert_eq!(r, None);
            }
        }

        for i in 1001..2001 {
            assert!(!map.contains_key(&i).await);
        }

        // remove forwards
        for i in 1..1001 {
            assert!(map.remove(&i).await.is_some());

            for j in 1..i + 1 {
                assert!(!map.contains_key(&j).await);
            }

            for j in i + 1..1001 {
                assert!(map.contains_key(&j).await);
            }
        }

        for i in 1..1001 {
            assert!(!map.contains_key(&i).await);
        }

        for i in 1..1001 {
            assert!(map.insert(i, i).await.is_none());
        }

        // remove backwards
        for i in (1..1001).rev() {
            assert!(map.remove(&i).await.is_some());

            for j in i..1001 {
                assert!(!map.contains_key(&j).await);
            }

            for j in 1..i {
                assert!(map.contains_key(&j).await);
            }
        }
    }
}

#[test]
async fn find_mut() {
    let map = CHashMap::new();
    assert!(map.insert(1, 12).await.is_none());
    assert!(map.insert(2, 8).await.is_none());
    assert!(map.insert(5, 14).await.is_none());
    let new = 100;
    match map.get_mut(&5).await {
        None => panic!("Entry is empty"),
        Some(mut x) => *x = new,
    }
    assert_eq!(*map.get(&5).await.unwrap(), new);
}

#[test]
async fn insert_overwrite() {
    let map = CHashMap::new();
    assert_eq!(map.len(), 0);
    assert!(map.insert(1, 2).await.is_none());
    assert_eq!(map.len(), 1);
    assert_eq!(*map.get(&1).await.unwrap(), 2);
    assert_eq!(map.len(), 1);
    assert!(!map.insert(1, 3).await.is_none());
    assert_eq!(map.len(), 1);
    assert_eq!(*map.get(&1).await.unwrap(), 3);
}

#[test]
async fn insert_conflicts() {
    let map = CHashMap::with_capacity(4);
    assert!(map.insert(1, 2).await.is_none());
    assert!(map.insert(5, 3).await.is_none());
    assert!(map.insert(9, 4).await.is_none());
    assert_eq!(*map.get(&9).await.unwrap(), 4);
    assert_eq!(*map.get(&5).await.unwrap(), 3);
    assert_eq!(*map.get(&1).await.unwrap(), 2);
}

#[test]
async fn conflict_remove() {
    let map = CHashMap::with_capacity(4);
    assert!(map.insert(1, 2).await.is_none());
    assert_eq!(*map.get(&1).await.unwrap(), 2);
    assert!(map.insert(5, 3).await.is_none());
    assert_eq!(*map.get(&1).await.unwrap(), 2);
    assert_eq!(*map.get(&5).await.unwrap(), 3);
    assert!(map.insert(9, 4).await.is_none());
    assert_eq!(*map.get(&1).await.unwrap(), 2);
    assert_eq!(*map.get(&5).await.unwrap(), 3);
    assert_eq!(*map.get(&9).await.unwrap(), 4);
    assert!(map.remove(&1).await.is_some());
    assert_eq!(*map.get(&9).await.unwrap(), 4);
    assert_eq!(*map.get(&5).await.unwrap(), 3);
}

#[test]
async fn is_empty() {
    let map = CHashMap::with_capacity(4);
    assert!(map.insert(1, 2).await.is_none());
    assert!(!map.is_empty());
    assert!(map.remove(&1).await.is_some());
    assert!(map.is_empty());
}

#[test]
async fn pop() {
    let map = CHashMap::new();
    map.insert(1, 2).await;
    assert_eq!(map.remove(&1).await, Some(2));
    assert_eq!(map.remove(&1).await, None);
}

#[test]
async fn find() {
    let m = CHashMap::new();
    assert!(m.get(&1).await.is_none());
    m.insert(1, 2).await;
    let lock = m.get(&1).await;
    match lock {
        None => panic!("Entry is empty"),
        Some(v) => assert_eq!(*v, 2),
    }
}

#[test]
async fn known_size_with_capacity_matches_shrink() {
    for i in 0..(MAX_LOAD_FACTOR_DENOM * 4) {
        // Setup a map where we know the number of entries we will store
        let map = CHashMap::with_capacity(i);
        let original_capacity = map.capacity().await;
        let buckets = map.buckets().await;
        assert!(
            i <= original_capacity,
            "Expected {} <= {} for {} buckets",
            i,
            original_capacity,
            buckets
        );
        for j in 0..i {
            map.insert(j, j).await;
        }

        // Make sure inserting didn't increase capacity given we already knew
        // number of entries planned on map construction
        let grown_capacity = map.capacity().await;
        assert_eq!(original_capacity, grown_capacity, " for {} inserts", i);

        // Shrink it and check that capacity is the same
        map.shrink_to_fit().await;
        let shrunken_capacity = map.capacity().await;
        assert_eq!(
            shrunken_capacity, original_capacity,
            "Expected {} == {} ",
            shrunken_capacity, shrunken_capacity
        );
    }
}

#[test]
async fn shrink_to_fit_after_insert() {
    for i in 0..(MAX_LOAD_FACTOR_DENOM * 4) {
        // Setup
        let map = CHashMap::new();
        for j in 0..i {
            map.insert(j, j).await;
        }
        let original_capacity = map.capacity().await;

        // Test
        map.shrink_to_fit().await;
        let shrunken_capacity = map.capacity().await;
        assert!(
            shrunken_capacity <= original_capacity,
            "Unexpected capacity after shrink given {} inserts. Expected {} <= {}",
            i,
            shrunken_capacity,
            original_capacity
        );
    }
}

#[test]
async fn reserve_shrink_to_fit() {
    let map = CHashMap::new();
    map.insert(0, 0).await;
    map.remove(&0).await;
    assert!(map.capacity().await >= map.len());
    for i in 0..128 {
        map.insert(i, i).await;
    }
    map.reserve(256).await;

    let usable_cap = map.capacity().await;
    for i in 128..(128 + 256) {
        map.insert(i, i).await;
        assert_eq!(map.capacity().await, usable_cap);
    }

    for i in 100..(128 + 256) {
        assert_eq!(map.remove(&i).await, Some(i));
    }
    map.shrink_to_fit().await;

    assert_eq!(map.len(), 100);
    assert!(!map.is_empty());
    assert!(map.capacity().await >= map.len());

    for i in 0..100 {
        assert_eq!(map.remove(&i).await, Some(i));
    }
    map.shrink_to_fit().await;
    map.insert(0, 0).await;

    assert_eq!(map.len(), 1);
    assert!(map.capacity().await >= map.len());
    assert_eq!(map.remove(&0).await, Some(0));
}

#[test]
async fn from_iter() {
    let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];

    let map: CHashMap<_, _> = xs.iter().cloned().collect();

    for &(k, v) in &xs {
        assert_eq!(*map.get(&k).await.unwrap(), v);
    }
}

#[test]
async fn capacity_not_less_than_len() {
    let a = CHashMap::new();
    let mut item = 0;

    for _ in 0..116 {
        a.insert(item, 0).await;
        item += 1;
    }

    assert!(a.capacity().await > a.len());

    let free = a.capacity().await - a.len();
    for _ in 0..free {
        a.insert(item, 0).await;
        item += 1;
    }

    assert_eq!(a.len(), a.capacity().await);

    // Insert at capacity should cause allocation.
    a.insert(item, 0).await;
    assert!(a.capacity().await > a.len());
}

#[test]
async fn insert_into_map_full_of_free_buckets() {
    let m = CHashMap::with_capacity(1);
    for i in 0..100 {
        m.insert(i, 0).await;
        m.remove(&i).await;
    }
}

#[test]
async fn lookup_borrowed() {
    let m = CHashMap::with_capacity(1);
    m.insert("v".to_owned(), "value").await;
    m.get("v").await.unwrap();
}