weak-map 0.1.2

BTreeMap with weak references
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
//! `BTreeMap` with weak references.

use alloc::collections::btree_map;
use core::{
    borrow::Borrow,
    fmt,
    iter::FusedIterator,
    sync::atomic::{AtomicUsize, Ordering},
};

use crate::{StrongRef, WeakRef};

#[derive(Default)]
struct OpsCounter(AtomicUsize);

const OPS_THRESHOLD: usize = 1000;

impl OpsCounter {
    #[inline]
    const fn new() -> Self {
        Self(AtomicUsize::new(0))
    }

    #[inline]
    fn add(&self, ops: usize) {
        self.0.fetch_add(ops, Ordering::Relaxed);
    }

    #[inline]
    fn bump(&self) {
        self.add(1);
    }

    #[inline]
    fn reset(&mut self) {
        *self.0.get_mut() = 0;
    }

    #[inline]
    fn get(&self) -> usize {
        self.0.load(Ordering::Relaxed)
    }

    #[inline]
    fn reach_threshold(&self) -> bool {
        self.get() >= OPS_THRESHOLD
    }
}

impl Clone for OpsCounter {
    #[inline]
    fn clone(&self) -> Self {
        Self(AtomicUsize::new(self.get()))
    }
}

/// Alias for `BTreeMap<K, V>`.
pub type StrongMap<K, V> = btree_map::BTreeMap<K, V>;

/// A B-Tree map that stores weak references to values.
#[derive(Clone)]
pub struct WeakMap<K, V> {
    inner: btree_map::BTreeMap<K, V>,
    ops: OpsCounter,
}

impl<K, V> WeakMap<K, V> {
    /// Makes a new, empty `WeakMap`.
    ///
    /// Does not allocate anything on its own.
    #[inline]
    pub const fn new() -> Self {
        Self {
            inner: btree_map::BTreeMap::new(),
            ops: OpsCounter::new(),
        }
    }
}

impl<K, V> Default for WeakMap<K, V> {
    fn default() -> Self {
        Self::new()
    }
}

impl<K, V> From<btree_map::BTreeMap<K, V>> for WeakMap<K, V> {
    #[inline]
    fn from(inner: btree_map::BTreeMap<K, V>) -> Self {
        Self {
            inner,
            ops: OpsCounter::new(),
        }
    }
}

impl<K, V> From<WeakMap<K, V>> for btree_map::BTreeMap<K, V> {
    #[inline]
    fn from(map: WeakMap<K, V>) -> Self {
        map.inner
    }
}

impl<K, V> WeakMap<K, V> {
    /// Clears the map, removing all elements.
    #[inline]
    pub fn clear(&mut self) {
        self.inner.clear();
        self.ops.reset();
    }

    /// Returns the number of elements in the underlying map.
    #[must_use]
    pub fn raw_len(&self) -> usize {
        self.inner.len()
    }

    /// Gets an iterator over the entries of the map, sorted by key.
    #[inline]
    pub fn iter(&self) -> Iter<'_, K, V> {
        self.ops.add(self.inner.len());
        Iter(self.inner.iter())
    }

    /// Gets an iterator over the keys of the map, in sorted order.
    #[inline]
    pub fn keys(&self) -> Keys<'_, K, V> {
        Keys(self.iter())
    }

    /// Creates a consuming iterator visiting all the keys, in sorted order.
    /// The map cannot be used after calling this.
    #[inline]
    pub fn into_keys(self) -> IntoKeys<K, V> {
        IntoKeys(IntoIter(self.inner.into_iter()))
    }

    /// Gets an iterator over the values of the map, in order by key.
    #[inline]
    pub fn values(&self) -> Values<'_, K, V> {
        Values(self.iter())
    }

    /// Creates a consuming iterator visiting all the values, in order by key.
    /// The map cannot be used after calling this.
    #[inline]
    pub fn into_values(self) -> IntoValues<K, V> {
        IntoValues(IntoIter(self.inner.into_iter()))
    }
}

impl<K, V> WeakMap<K, V>
where
    K: Ord,
    V: WeakRef,
{
    /// Cleans up the map by removing expired values.
    ///
    /// Usually you don't need to call this manually, as it is called
    /// automatically when the number of operations reaches a threshold.
    #[inline]
    pub fn cleanup(&mut self) {
        self.ops.reset();
        self.inner.retain(|_, v| !v.is_expired());
    }

    #[inline]
    fn try_bump(&mut self) {
        self.ops.bump();
        if self.ops.reach_threshold() {
            self.cleanup();
        }
    }

    /// Returns the number of elements in the map, excluding expired values.
    ///
    /// This is a linear operation, as it iterates over all elements in the map.
    ///
    /// The returned value may be less than the result of [`Self::raw_len`].
    #[inline]
    pub fn len(&self) -> usize {
        self.iter().count()
    }

    /// Returns `true` if the map contains no valid elements.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Retains only the elements specified by the predicate.
    #[inline]
    pub fn retain<F>(&mut self, mut f: F)
    where
        F: FnMut(&K, V::Strong) -> bool,
    {
        self.ops.reset();
        self.inner.retain(|k, v| {
            if let Some(v) = v.upgrade() {
                f(k, v)
            } else {
                false
            }
        });
    }

    /// Returns a reference to the value corresponding to the key.
    ///
    /// The key may be any borrowed form of the map's key type, but the ordering
    /// on the borrowed form *must* match the ordering on the key type.
    pub fn get<Q>(&self, key: &Q) -> Option<V::Strong>
    where
        K: Borrow<Q>,
        Q: Ord + ?Sized,
    {
        self.ops.bump();
        self.inner.get(key).and_then(V::upgrade)
    }

    /// Returns the key-value pair corresponding to the supplied key. This is
    /// potentially useful:
    /// - for key types where non-identical keys can be considered equal;
    /// - for getting the `&K` stored key value from a borrowed `&Q` lookup key; or
    /// - for getting a reference to a key with the same lifetime as the collection.
    ///
    /// The supplied key may be any borrowed form of the map's key type, but the ordering
    /// on the borrowed form *must* match the ordering on the key type.
    pub fn get_key_value<Q>(&self, key: &Q) -> Option<(&K, V::Strong)>
    where
        K: Borrow<Q>,
        Q: Ord + ?Sized,
    {
        self.ops.bump();
        self.inner
            .get_key_value(key)
            .and_then(|(k, v)| v.upgrade().map(|v| (k, v)))
    }

    /// Returns `true` if the map contains a value for the specified key.
    ///
    /// The key may be any borrowed form of the map's key type, but the ordering
    /// on the borrowed form *must* match the ordering on the key type.
    pub fn contains_key<Q>(&self, key: &Q) -> bool
    where
        K: Borrow<Q>,
        Q: Ord + ?Sized,
    {
        self.ops.bump();
        self.inner.get(key).is_some_and(|v| !v.is_expired())
    }

    /// Inserts a key-value pair into the map.
    ///
    /// If the map did not have this key present, `None` is returned.
    ///
    /// If the map did have this key present, the value is updated, and the old
    /// value is returned. The key is not updated, though; this matters for
    /// types that can be `==` without being identical. See the [module-level
    /// documentation] for more.
    ///
    /// [module-level documentation]: https://doc.rust-lang.org/std/collections/index.html#insert-and-complex-keys
    pub fn insert(&mut self, key: K, value: &V::Strong) -> Option<V::Strong> {
        self.try_bump();
        self.inner
            .insert(key, V::Strong::downgrade(value))
            .and_then(|v| v.upgrade())
    }

    /// Removes a key from the map, returning the value at the key if the key
    /// was previously in the map.
    ///
    /// The key may be any borrowed form of the map's key type, but the ordering
    /// on the borrowed form *must* match the ordering on the key type.
    pub fn remove<Q>(&mut self, key: &Q) -> Option<V::Strong>
    where
        K: Borrow<Q>,
        Q: Ord + ?Sized,
    {
        self.try_bump();
        self.inner.remove(key).and_then(|v| v.upgrade())
    }

    /// Removes a key from the map, returning the stored key and value if the key
    /// was previously in the map.
    ///
    /// The key may be any borrowed form of the map's key type, but the ordering
    /// on the borrowed form *must* match the ordering on the key type.
    pub fn remove_entry<Q>(&mut self, key: &Q) -> Option<(K, V::Strong)>
    where
        K: Borrow<Q>,
        Q: Ord + ?Sized,
    {
        self.try_bump();
        self.inner
            .remove_entry(key)
            .and_then(|(k, v)| v.upgrade().map(|v| (k, v)))
    }

    /// Gets a mutable iterator over the entries of the map, sorted by key.
    #[inline]
    pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
        self.ops.add(self.inner.len());
        if self.ops.reach_threshold() {
            self.cleanup();
        }
        IterMut(self.inner.iter_mut())
    }

    /// Upgrade this `WeakMap` to a `StrongMap`.
    pub fn upgrade(&self) -> StrongMap<K, V::Strong>
    where
        K: Clone,
    {
        self.ops.bump();
        let mut map = StrongMap::new();
        for (key, value) in self.iter() {
            map.insert(key.clone(), value);
        }
        map
    }
}

impl<K, V> PartialEq for WeakMap<K, V>
where
    K: Ord,
    V: WeakRef,
{
    fn eq(&self, other: &Self) -> bool {
        self.iter().all(|(key, value)| {
            other
                .get(key)
                .is_some_and(|v| V::Strong::ptr_eq(&value, &v))
        })
    }
}

impl<K, V> Eq for WeakMap<K, V>
where
    K: Ord,
    V: WeakRef,
{
}

impl<K, V> fmt::Debug for WeakMap<K, V>
where
    K: fmt::Debug,
    V: WeakRef,
    V::Strong: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_map().entries(self.iter()).finish()
    }
}

impl<'a, K, V> FromIterator<(K, &'a V::Strong)> for WeakMap<K, V>
where
    K: Ord,
    V: WeakRef,
{
    #[inline]
    fn from_iter<T: IntoIterator<Item = (K, &'a V::Strong)>>(iter: T) -> Self {
        let iter = iter.into_iter();
        let mut map = WeakMap::new();
        for (key, value) in iter {
            map.insert(key, value);
        }
        map
    }
}

impl<K, V, const N: usize> From<[(K, &V::Strong); N]> for WeakMap<K, V>
where
    K: Ord,
    V: WeakRef,
{
    #[inline]
    fn from(array: [(K, &V::Strong); N]) -> Self {
        array.into_iter().collect()
    }
}

impl<K, V> From<&StrongMap<K, V::Strong>> for WeakMap<K, V>
where
    K: Ord + Clone,
    V: WeakRef,
{
    fn from(value: &StrongMap<K, V::Strong>) -> Self {
        let mut map = WeakMap::new();
        for (key, value) in value.iter() {
            map.insert(key.clone(), value);
        }
        map
    }
}

/// An iterator over the entries of a `WeakMap`.
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct Iter<'a, K, V>(btree_map::Iter<'a, K, V>);

impl<'a, K, V> Iterator for Iter<'a, K, V>
where
    V: WeakRef,
{
    type Item = (&'a K, V::Strong);

    fn next(&mut self) -> Option<Self::Item> {
        for (key, value) in self.0.by_ref() {
            if let Some(value) = value.upgrade() {
                return Some((key, value));
            }
        }
        None
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        (0, Some(self.0.len()))
    }
}

impl<K, V> FusedIterator for Iter<'_, K, V> where V: WeakRef {}

impl<K, V> Default for Iter<'_, K, V> {
    fn default() -> Self {
        Iter(btree_map::Iter::default())
    }
}

impl<K, V> Clone for Iter<'_, K, V> {
    fn clone(&self) -> Self {
        Iter(self.0.clone())
    }
}

impl<K, V> fmt::Debug for Iter<'_, K, V>
where
    K: fmt::Debug,
    V: WeakRef,
    V::Strong: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.clone()).finish()
    }
}

impl<'a, K, V> IntoIterator for &'a WeakMap<K, V>
where
    V: WeakRef,
{
    type IntoIter = Iter<'a, K, V>;
    type Item = (&'a K, V::Strong);

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

/// A mutable iterator over the entries of a `BTreeMap`.
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct IterMut<'a, K, V>(btree_map::IterMut<'a, K, V>);

impl<'a, K, V> Iterator for IterMut<'a, K, V> {
    type Item = (&'a K, &'a mut V);

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        (0, Some(self.0.len()))
    }
}

impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {}

impl<K, V> FusedIterator for IterMut<'_, K, V> {}

impl<K, V> Default for IterMut<'_, K, V> {
    fn default() -> Self {
        IterMut(btree_map::IterMut::default())
    }
}

impl<'a, K, V> IntoIterator for &'a mut WeakMap<K, V>
where
    K: Ord,
    V: WeakRef,
{
    type IntoIter = IterMut<'a, K, V>;
    type Item = (&'a K, &'a mut V);

    fn into_iter(self) -> Self::IntoIter {
        self.iter_mut()
    }
}

/// An iterator over the keys of a `WeakMap`.
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct Keys<'a, K, V>(Iter<'a, K, V>);

impl<'a, K, V> Iterator for Keys<'a, K, V>
where
    V: WeakRef,
{
    type Item = &'a K;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next().map(|(key, _)| key)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
}

impl<K, V> FusedIterator for Keys<'_, K, V> where V: WeakRef {}

impl<K, V> Default for Keys<'_, K, V> {
    fn default() -> Self {
        Keys(Iter::default())
    }
}

impl<K, V> Clone for Keys<'_, K, V> {
    fn clone(&self) -> Self {
        Keys(self.0.clone())
    }
}

impl<K, V> fmt::Debug for Keys<'_, K, V>
where
    K: fmt::Debug,
    V: WeakRef,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.clone()).finish()
    }
}

/// An iterator over the values of a `WeakMap`.
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct Values<'a, K, V>(Iter<'a, K, V>);

impl<K, V> Iterator for Values<'_, K, V>
where
    V: WeakRef,
{
    type Item = V::Strong;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next().map(|(_, value)| value)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
}

impl<K, V> FusedIterator for Values<'_, K, V> where V: WeakRef {}

impl<K, V> Default for Values<'_, K, V> {
    fn default() -> Self {
        Values(Iter::default())
    }
}

impl<K, V> Clone for Values<'_, K, V> {
    fn clone(&self) -> Self {
        Values(self.0.clone())
    }
}

impl<K, V> fmt::Debug for Values<'_, K, V>
where
    V: WeakRef,
    V::Strong: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.clone()).finish()
    }
}

/// An owning iterator over the entries of a `WeakMap`.
pub struct IntoIter<K, V>(btree_map::IntoIter<K, V>);

impl<K, V> Iterator for IntoIter<K, V>
where
    V: WeakRef,
{
    type Item = (K, V::Strong);

    fn next(&mut self) -> Option<Self::Item> {
        for (key, value) in self.0.by_ref() {
            if let Some(value) = value.upgrade() {
                return Some((key, value));
            }
        }
        None
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (0, Some(self.0.len()))
    }
}

impl<K, V> FusedIterator for IntoIter<K, V> where V: WeakRef {}

impl<K, V> Default for IntoIter<K, V> {
    fn default() -> Self {
        IntoIter(btree_map::IntoIter::default())
    }
}

impl<K, V> IntoIterator for WeakMap<K, V>
where
    V: WeakRef,
{
    type IntoIter = IntoIter<K, V>;
    type Item = (K, V::Strong);

    fn into_iter(self) -> Self::IntoIter {
        IntoIter(self.inner.into_iter())
    }
}

/// An owning iterator over the keys of a `WeakMap`.
pub struct IntoKeys<K, V>(IntoIter<K, V>);

impl<K, V> Iterator for IntoKeys<K, V>
where
    V: WeakRef,
{
    type Item = K;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next().map(|(key, _)| key)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
}

impl<K, V> FusedIterator for IntoKeys<K, V> where V: WeakRef {}

impl<K, V> Default for IntoKeys<K, V> {
    fn default() -> Self {
        IntoKeys(IntoIter::default())
    }
}

/// An owning iterator over the values of a `WeakMap`.`
pub struct IntoValues<K, V>(IntoIter<K, V>);

impl<K, V> Iterator for IntoValues<K, V>
where
    V: WeakRef,
{
    type Item = V::Strong;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next().map(|(_, value)| value)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
}

impl<K, V> FusedIterator for IntoValues<K, V> where V: WeakRef {}

impl<K, V> Default for IntoValues<K, V> {
    fn default() -> Self {
        IntoValues(IntoIter::default())
    }
}

#[cfg(test)]
mod tests {
    use alloc::sync::{Arc, Weak};

    use super::*;

    #[test]
    fn test_basic() {
        let mut map = WeakMap::<u32, Weak<&str>>::new();

        let elem1 = Arc::new("1");
        map.insert(1, &elem1);

        {
            let elem2 = Arc::new("2");
            map.insert(2, &elem2);
        }

        assert_eq!(map.len(), 1);
        assert_eq!(map.get(&1), Some(elem1));
        assert_eq!(map.get(&2), None);
    }

    #[test]
    fn test_cleanup() {
        let mut map = WeakMap::<usize, Weak<usize>>::new();

        for i in 0..OPS_THRESHOLD * 10 {
            let elem = Arc::new(i);
            map.insert(i, &elem);
        }

        assert_eq!(map.len(), 0);
        assert_eq!(map.raw_len(), 1);
    }
}