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
//! The [`CloneConMap`][crate::CloneConMap] type and its helpers.

use std::borrow::Borrow;
use std::collections::hash_map::RandomState;
use std::fmt::{Debug, Formatter, Result as FmtResult};
use std::hash::{BuildHasher, Hash};
use std::iter::FromIterator;
use std::marker::PhantomData;

#[cfg(feature = "rayon")]
use rayon::iter::{FromParallelIterator, IntoParallelIterator, ParallelExtend, ParallelIterator};

use crate::existing_or_new::ExistingOrNew;
use crate::raw::config::Config;
use crate::raw::{self, Raw};

#[derive(Clone)]
struct CloneMapPayload<K, V>((K, V));

impl<K, V> Borrow<K> for CloneMapPayload<K, V> {
    fn borrow(&self) -> &K {
        let &(ref k, _) = &self.0;
        k
    }
}

struct CloneMapConfig<K, V>(PhantomData<(K, V)>);

impl<K, V> Config for CloneMapConfig<K, V>
where
    K: Clone + Hash + Eq + 'static,
    V: Clone + 'static,
{
    type Payload = CloneMapPayload<K, V>;
    type Key = K;
}

/// The iterator of the [`CloneConMap`].
///
/// See the [`iter`][CloneConMap::iter] method for details.
pub struct Iter<'a, K, V, S>
where
    K: Clone + Hash + Eq + 'static,
    V: Clone + 'static,
{
    inner: raw::iterator::Iter<'a, CloneMapConfig<K, V>, S>,
}

impl<'a, K, V, S> Iterator for Iter<'a, K, V, S>
where
    K: Clone + Hash + Eq + 'static,
    V: Clone + 'static,
{
    type Item = (K, V);
    fn next(&mut self) -> Option<(K, V)> {
        self.inner.next().map(|p| (p.0).clone())
    }
}

/// A concurrent map that clones its elements.
///
/// This flavour stores the data as `(K, V)` tuples; it clones
/// independently both the elements (to be intended as the key and the
/// value) of the tuple. The return values of its functions are clones
/// of the stored values. This makes this data structure suitable for
/// types cheap to clone.
///
/// Iteration returns cloned copies of its elements. The
/// [`FromIterator`] and [`Extend`] traits accept tuples as arguments.
/// Furthermore, the [`Extend`] is also implemented for shared
/// references (to allow extending the same map concurrently from
/// multiple threads).
///
/// # Examples
///
/// ```rust
/// use contrie::CloneConMap;
/// use crossbeam_utils::thread;
///
/// let map = CloneConMap::new();
///
/// thread::scope(|s| {
///     s.spawn(|_| {
///         map.insert("hello", 1);
///     });
///     s.spawn(|_| {
///         map.insert("world", 2);
///     });
/// }).unwrap();
/// assert_eq!(1, map.get("hello").unwrap().1);
/// assert_eq!(2, map.get("world").unwrap().1);
/// ```
///
/// ```rust
/// use contrie::clonemap::{CloneConMap};
///
/// let map_1: CloneConMap<usize, Vec<usize>> = CloneConMap::new();
///
/// map_1.insert(42, vec![1, 2, 3]);
/// map_1.insert(43, vec![1, 2, 3, 4]);
///
/// assert_eq!(3, map_1.get(&42).unwrap().1.len());
/// assert_eq!(4, map_1.get(&43).unwrap().1.len());
/// assert_eq!(None, map_1.get(&44));
///
/// let map_2 = CloneConMap::new();
/// map_2.insert(44, map_1.get(&43).unwrap().1);
/// assert_eq!(4, map_2.get(&44).unwrap().1.len());
/// ```
pub struct CloneConMap<K, V, S = RandomState>
where
    K: Clone + Hash + Eq + 'static,
    V: Clone + 'static,
{
    raw: Raw<CloneMapConfig<K, V>, S>,
}

impl<K, V> CloneConMap<K, V>
where
    K: Clone + Hash + Eq + 'static,
    V: Clone + 'static,
{
    /// Creates a new empty map.
    pub fn new() -> Self {
        Self::with_hasher(RandomState::default())
    }
}

impl<K, V, S> CloneConMap<K, V, S>
where
    K: Clone + Hash + Eq + 'static,
    V: Clone + 'static,
    S: BuildHasher,
{
    /// Inserts a new element as a tuple `(key, value)`.
    ///
    /// Any previous element with the same key is replaced and returned.
    pub fn insert(&self, key: K, value: V) -> Option<(K, V)> {
        let pin = crossbeam_epoch::pin();
        self.raw
            .insert(CloneMapPayload((key, value)), &pin)
            .map(|p| p.0.clone())
    }

    /// Looks up or inserts an element as a tuple `(key, value)`.
    ///
    /// It looks up an element. If it isn't present, the provided one is
    /// inserted instead. Either way, an element is returned.
    pub fn get_or_insert(&self, key: K, value: V) -> ExistingOrNew<(K, V)> {
        self.get_or_insert_with(key, || value)
    }

    /// Looks up or inserts a newly created element.
    ///
    /// It looks up an element. If it isn't present, the provided
    /// closure is used to create a new one insert it. Either way, an
    /// element is returned.
    ///
    /// # Quirks
    ///
    /// Due to races in case of concurrent accesses, the closure may be
    /// called even if the value is not subsequently inserted and an
    /// existing element is returned. This should be relatively rare
    /// (another thread must insert the new element between this method
    /// observes an empty slot and manages to insert the new element).
    pub fn get_or_insert_with<F>(&self, key: K, create: F) -> ExistingOrNew<(K, V)>
    where
        F: FnOnce() -> V,
    {
        let pin = crossbeam_epoch::pin();

        self.raw
            .get_or_insert_with(
                key,
                |key| {
                    let value: V = create();
                    CloneMapPayload((key, value))
                },
                &pin,
            )
            .map(|payload| (payload.0).clone())
    }

    /// Looks up or inserts a default value of an element.
    ///
    /// This is like [get_or_insert_with][CloneConMap::get_or_insert_with],
    /// but a default value is used instead of manually providing a
    /// closure.
    pub fn get_or_insert_default(&self, key: K) -> ExistingOrNew<(K, V)>
    where
        V: Default,
    {
        self.get_or_insert_with(key, V::default)
    }
}

impl<K, V, S> CloneConMap<K, V, S>
where
    K: Clone + Hash + Eq,
    V: Clone,
    S: BuildHasher,
{
    /// Creates a new empty map, but with the provided hasher implementation.
    pub fn with_hasher(hasher: S) -> Self {
        Self {
            raw: Raw::with_hasher(hasher),
        }
    }

    /// Looks up an element.
    pub fn get<Q>(&self, key: &Q) -> Option<(K, V)>
    where
        Q: ?Sized + Eq + Hash,
        K: Borrow<Q>,
    {
        let pin = crossbeam_epoch::pin();
        self.raw.get(key, &pin).map(|r| (r.0).clone())
    }

    /// Removes an element identified by the given key, returning it.
    pub fn remove<Q>(&self, key: &Q) -> Option<(K, V)>
    where
        Q: ?Sized + Eq + Hash,
        K: Borrow<Q>,
    {
        let pin = crossbeam_epoch::pin();
        self.raw.remove(key, &pin).map(|r| (r.0).clone())
    }
}

impl<K, V, S> CloneConMap<K, V, S>
where
    K: Clone + Hash + Eq,
    V: Clone,
{
    /// Checks if the map is currently empty.
    ///
    /// Note that due to the nature of concurrent map, this is
    /// inherently racy ‒ another thread may add or remove elements
    /// between you call this method and act based on the result.
    pub fn is_empty(&self) -> bool {
        self.raw.is_empty()
    }

    /// Returns an iterator through the elements of the map.
    pub fn iter(&self) -> Iter<K, V, S> {
        Iter {
            inner: raw::iterator::Iter::new(&self.raw),
        }
    }
}

impl<K, V> Default for CloneConMap<K, V>
where
    K: Clone + Hash + Eq,
    V: Clone,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<K, V, S> Debug for CloneConMap<K, V, S>
where
    K: Debug + Clone + Hash + Eq,
    V: Debug + Clone,
{
    fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
        fmt.debug_map().entries(self.iter()).finish()
    }
}

impl<K, V, S> Clone for CloneConMap<K, V, S>
where
    K: Clone + Hash + Eq,
    V: Clone,
    S: Clone + BuildHasher,
{
    fn clone(&self) -> Self {
        let builder = self.raw.hash_builder().clone();
        let mut new = Self::with_hasher(builder);
        new.extend(self);
        new
    }
}

impl<'a, K, V, S> IntoIterator for &'a CloneConMap<K, V, S>
where
    K: Clone + Hash + Eq,
    V: Clone,
{
    type Item = (K, V);
    type IntoIter = Iter<'a, K, V, S>;
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'a, K, V, S> Extend<(K, V)> for &'a CloneConMap<K, V, S>
where
    K: Clone + Hash + Eq,
    V: Clone,
    S: BuildHasher,
{
    fn extend<T>(&mut self, iter: T)
    where
        T: IntoIterator<Item = (K, V)>,
    {
        for (k, v) in iter {
            self.insert(k, v);
        }
    }
}

impl<K, V, S> Extend<(K, V)> for CloneConMap<K, V, S>
where
    K: Clone + Hash + Eq,
    V: Clone,
    S: BuildHasher,
{
    fn extend<T>(&mut self, iter: T)
    where
        T: IntoIterator<Item = (K, V)>,
    {
        let mut me: &CloneConMap<_, _, _> = self;
        me.extend(iter);
    }
}

impl<K, V> FromIterator<(K, V)> for CloneConMap<K, V>
where
    K: Clone + Hash + Eq,
    V: Clone,
{
    fn from_iter<T>(iter: T) -> Self
    where
        T: IntoIterator<Item = (K, V)>,
    {
        let mut me = CloneConMap::new();
        me.extend(iter);
        me
    }
}

#[cfg(feature = "rayon")]
impl<K, V, S> ParallelExtend<(K, V)> for CloneConMap<K, V, S>
where
    K: Clone + Hash + Eq + Send + Sync,
    S: BuildHasher + Sync,
    V: Clone + Send + Sync,
{
    fn par_extend<T>(&mut self, par_iter: T)
    where
        T: IntoParallelIterator<Item = (K, V)>,
    {
        par_iter.into_par_iter().for_each(|(k, v)| {
            self.insert(k.clone(), v.clone());
        });
    }
}

#[cfg(feature = "rayon")]
impl<'a, K, V, S> ParallelExtend<(K, V)> for &'a CloneConMap<K, V, S>
where
    K: Clone + Hash + Eq + Send + Sync,
    S: BuildHasher + Sync,
    V: Clone + Send + Sync,
{
    fn par_extend<T>(&mut self, par_iter: T)
    where
        T: IntoParallelIterator<Item = (K, V)>,
    {
        par_iter.into_par_iter().for_each(|(k, v)| {
            self.insert(k.clone(), v.clone());
        });
    }
}

#[cfg(feature = "rayon")]
impl<K, V> FromParallelIterator<(K, V)> for CloneConMap<K, V>
where
    K: Clone + Hash + Eq + Send + Sync,
    V: Clone + Send + Sync,
{
    fn from_par_iter<T>(par_iter: T) -> Self
    where
        T: IntoParallelIterator<Item = (K, V)>,
    {
        let mut me = CloneConMap::new();
        me.par_extend(par_iter);
        me
    }
}

#[cfg(test)]
mod tests {
    use crossbeam_utils::thread;
    use std::rc::Rc;

    #[cfg(feature = "rayon")]
    use rayon::prelude::*;

    use super::*;
    use crate::raw::tests::NoHasher;
    use crate::raw::LEVEL_CELLS;

    const TEST_THREADS: usize = 4;
    const TEST_BATCH: usize = 10000;
    const TEST_BATCH_SMALL: usize = 100;
    const TEST_REP: usize = 20;

    #[test]
    fn create_destroy() {
        let map: CloneConMap<String, usize> = CloneConMap::new();
        drop(map);
    }

    #[test]
    fn debug_formatting() {
        let map: CloneConMap<&str, &str> = CloneConMap::new();
        map.insert("hello", "world");
        assert_eq!("{\"hello\": \"world\"}".to_owned(), format!("{:?}", map));
    }

    #[test]
    fn lookup_empty() {
        let map: CloneConMap<String, usize> = CloneConMap::new();
        assert!(map.get("hello").is_none());
    }

    #[test]
    fn insert_lookup() {
        let map = CloneConMap::new();
        assert!(map.insert("hello", "world").is_none());
        assert!(map.get("world").is_none());
        let found = map.get("hello").unwrap();
        assert_eq!(("hello", "world"), found);
    }

    #[test]
    fn insert_overwrite_lookup() {
        let map = CloneConMap::new();
        assert!(map.insert("hello", "world").is_none());
        let old = map.insert("hello", "universe").unwrap();
        assert_eq!(("hello", "world"), old);
        let found = map.get("hello").unwrap();
        assert_eq!(("hello", "universe"), found);
    }

    // Insert a lot of things, to make sure we have multiple levels.
    #[test]
    fn insert_many() {
        let map = CloneConMap::new();
        for i in 0..TEST_BATCH * LEVEL_CELLS {
            assert!(map.insert(i, i).is_none());
        }

        for i in 0..TEST_BATCH * LEVEL_CELLS {
            assert_eq!(i, map.get(&i).unwrap().1);
        }
    }

    #[test]
    fn par_insert_many() {
        for _ in 0..TEST_REP {
            let map: CloneConMap<usize, usize> = CloneConMap::new();
            thread::scope(|s| {
                for t in 0..TEST_THREADS {
                    let map = &map;
                    s.spawn(move |_| {
                        for i in 0..TEST_BATCH {
                            let num = t * TEST_BATCH + i;
                            assert!(map.insert(num, num).is_none());
                        }
                    });
                }
            })
            .unwrap();

            for i in 0..TEST_BATCH * TEST_THREADS {
                assert_eq!(map.get(&i).unwrap().1, i);
            }
        }
    }

    #[test]
    fn par_get_many() {
        for _ in 0..TEST_REP {
            let map = CloneConMap::new();
            for i in 0..TEST_BATCH * TEST_THREADS {
                assert!(map.insert(i, i).is_none());
            }
            thread::scope(|s| {
                for t in 0..TEST_THREADS {
                    let map = &map;
                    s.spawn(move |_| {
                        for i in 0..TEST_BATCH {
                            let num = t * TEST_BATCH + i;
                            assert_eq!(map.get(&num).unwrap().1, num);
                        }
                    });
                }
            })
            .unwrap();
        }
    }

    #[test]
    fn collisions() {
        let map = CloneConMap::with_hasher(NoHasher);
        // While their hash is the same under the hasher, they don't kick each other out.
        for i in 0..TEST_BATCH_SMALL {
            assert!(map.insert(i, i).is_none());
        }
        // And all are present.
        for i in 0..TEST_BATCH_SMALL {
            assert_eq!(i, map.get(&i).unwrap().1);
        }
        // But reusing the key kicks the other one out.
        for i in 0..TEST_BATCH_SMALL {
            assert_eq!(i, map.insert(i, i + 1).unwrap().1);
            assert_eq!(i + 1, map.get(&i).unwrap().1);
        }
    }

    #[test]
    fn get_or_insert_empty() {
        let map = CloneConMap::new();
        let val = map.get_or_insert("hello", 42);
        assert_eq!(42, val.1);
        assert_eq!("hello", val.0);
        assert!(val.is_new());
    }

    #[test]
    fn get_or_insert_existing() {
        let map = CloneConMap::new();
        assert!(map.insert("hello", 42).is_none());
        let val = map.get_or_insert("hello", 0);
        // We still have the original
        assert_eq!(42, val.1);
        assert_eq!("hello", val.0);
        assert!(!val.is_new());
    }

    #[test]
    fn get_or_insert_existing_with_counter() {
        let map = CloneConMap::new();
        assert!(map.insert("hello", Rc::new(42)).is_none());
        let val = map.get_or_insert("hello", Rc::new(0));
        // We still have the original
        assert_eq!(&42, val.1.borrow());
        assert_eq!("hello", val.0);
        assert_eq!(2, Rc::strong_count(&val.1));
        let val = map.get_or_insert("hello", Rc::new(0));
        assert_eq!(3, Rc::strong_count(&val.1));
        assert!(!val.is_new());
    }

    fn get_or_insert_many_inner<H: BuildHasher>(map: CloneConMap<usize, usize, H>, len: usize) {
        for i in 0..len {
            let val = map.get_or_insert(i, i);
            assert_eq!(i, val.0);
            assert_eq!(i, val.1);
            assert!(val.is_new());
        }

        for i in 0..len {
            let val = map.get_or_insert(i, 0);
            assert_eq!(i, val.0);
            assert_eq!(i, val.1);
            assert!(!val.is_new());
        }
    }

    #[test]
    fn get_or_insert_many() {
        get_or_insert_many_inner(CloneConMap::new(), TEST_BATCH);
    }

    #[test]
    fn get_or_insert_collision() {
        get_or_insert_many_inner(CloneConMap::with_hasher(NoHasher), TEST_BATCH_SMALL);
    }

    #[test]
    fn simple_remove() {
        let map = CloneConMap::new();
        assert!(map.remove(&42).is_none());
        assert!(map.insert(42, "hello").is_none());
        assert_eq!("hello", map.get(&42).unwrap().1);
        assert_eq!("hello", map.remove(&42).unwrap().1);
        assert!(map.get(&42).is_none());
        assert!(map.is_empty());
        assert!(map.remove(&42).is_none());
        assert!(map.is_empty());
    }

    fn remove_many_inner<H: BuildHasher>(mut map: CloneConMap<usize, usize, H>, len: usize) {
        for i in 0..len {
            assert!(map.insert(i, i).is_none());
        }
        for i in 0..len {
            assert_eq!(i, map.get(&i).unwrap().1);
            assert_eq!(i, map.remove(&i).unwrap().1);
            assert!(map.get(&i).is_none());
            map.raw.assert_pruned();
        }

        assert!(map.is_empty());
    }

    #[test]
    fn remove_many() {
        remove_many_inner(CloneConMap::new(), TEST_BATCH);
    }

    #[test]
    fn remove_many_collision() {
        remove_many_inner(CloneConMap::with_hasher(NoHasher), TEST_BATCH_SMALL);
    }

    #[test]
    fn collision_remove_one_left() {
        let mut map = CloneConMap::with_hasher(NoHasher);
        map.insert(1, 1);
        map.insert(2, 2);

        map.raw.assert_pruned();

        assert!(map.remove(&2).is_some());
        map.raw.assert_pruned();

        assert!(map.remove(&1).is_some());

        map.raw.assert_pruned();
        assert!(map.is_empty());
    }

    #[test]
    fn remove_par() {
        let mut map = CloneConMap::new();
        for i in 0..TEST_THREADS * TEST_BATCH {
            map.insert(i, i);
        }

        thread::scope(|s| {
            for t in 0..TEST_THREADS {
                let map = &map;
                s.spawn(move |_| {
                    for i in 0..TEST_BATCH {
                        let num = t * TEST_BATCH + i;
                        let val = map.remove(&num).unwrap();
                        assert_eq!(num, val.1);
                        assert_eq!(num, val.0);
                    }
                });
            }
        })
        .unwrap();

        map.raw.assert_pruned();
        assert!(map.is_empty());
    }

    fn iter_test_inner<S: BuildHasher>(map: CloneConMap<usize, usize, S>) {
        for i in 0..TEST_BATCH_SMALL {
            assert!(map.insert(i, i).is_none());
        }

        let mut extracted = map.iter().map(|v| v.1).collect::<Vec<_>>();
        extracted.sort();
        let expected = (0..TEST_BATCH_SMALL).collect::<Vec<_>>();
        assert_eq!(expected, extracted);
    }

    #[test]
    fn iter() {
        let map = CloneConMap::new();
        iter_test_inner(map);
    }

    #[test]
    fn iter_collision() {
        let map = CloneConMap::with_hasher(NoHasher);
        iter_test_inner(map);
    }

    #[test]
    fn collect() {
        let map = (0..TEST_BATCH_SMALL)
            .map(|i| (i, i))
            .collect::<CloneConMap<_, _>>();

        let mut extracted = map
            .iter()
            .map(|n| {
                assert_eq!(n.0, n.1);
                n.1
            })
            .collect::<Vec<_>>();

        extracted.sort();
        let expected = (0..TEST_BATCH_SMALL).collect::<Vec<_>>();
        assert_eq!(expected, extracted);
    }

    #[test]
    fn par_extend() {
        let map = CloneConMap::new();
        thread::scope(|s| {
            for t in 0..TEST_THREADS {
                let mut map = &map;
                s.spawn(move |_| {
                    let start = t * TEST_BATCH_SMALL;
                    let iter = (start..start + TEST_BATCH_SMALL).map(|i| (i, i));
                    map.extend(iter);
                });
            }
        })
        .unwrap();

        let mut extracted = map
            .iter()
            .map(|n| {
                assert_eq!(n.0, n.1);
                n.1
            })
            .collect::<Vec<_>>();

        extracted.sort();
        let expected = (0..TEST_THREADS * TEST_BATCH_SMALL).collect::<Vec<_>>();
        assert_eq!(expected, extracted);
    }

    #[cfg(feature = "rayon")]
    #[test]
    fn rayon_extend() {
        let mut map = CloneConMap::new();
        map.par_extend((0..TEST_BATCH_SMALL).into_par_iter().map(|i| (i, i)));

        let mut extracted = map
            .iter()
            .map(|n| {
                assert_eq!(n.0, n.1);
                n.1
            })
            .collect::<Vec<_>>();
        extracted.sort();

        let expected = (0..TEST_BATCH_SMALL).collect::<Vec<_>>();
        assert_eq!(expected, extracted);
    }

    #[cfg(feature = "rayon")]
    #[test]
    fn rayon_from_par_iter() {
        let map = CloneConMap::from_par_iter((0..TEST_BATCH_SMALL).into_par_iter().map(|i| (i, i)));
        let mut extracted = map
            .iter()
            .map(|n| {
                assert_eq!(n.0, n.1);
                n.1
            })
            .collect::<Vec<_>>();
        extracted.sort();

        let expected = (0..TEST_BATCH_SMALL).collect::<Vec<_>>();
        assert_eq!(expected, extracted);
    }
}