Skip to main content

weak_table/
traits.rs

1//! Traits for describing strong and weak pointers and their use as elements and keys.
2//!
3//! These traits provide mechanisms for converting between weak and strong pointers
4//! ([`WeakElement`](trait.WeakElement.html)) and for dereferencing strong pointers
5//! ([`WeakKey`](trait.WeakKey.html)). Implementations of these traits are provided for
6//! `std::rc::Weak` and `std::sync::Weak`. If you would like to use your own pointer type
7//! as a weak element, you need to implement `WeakElement` for your weak pointer type; to use it
8//! as a weak key, implement `WeakKey` as well.
9
10use crate::compat::*;
11
12/// Interface for elements that can be stored in weak hash tables.
13///
14/// This trait applies to the weak version of a reference-counted pointer; it can be used to
15/// convert a weak pointer into a strong pointer and back. For example, the impl for
16/// `std::rc::Weak<T>` defines the `Strong` associated type as `std::rc::Rc<T>`. Then method
17/// `new` can be used to downgrade an `Rc<T>` to a `Weak<T>`, and method `view` can be used to
18/// upgrade a `Weak<T>` into an `Rc<T>`, if it's still alive. If we think of the weak pointer as
19/// what is stored, then the strong pointer is a temporary view of it.
20pub trait WeakElement {
21    /// The type at which a weak element can be viewed.
22    ///
23    /// For example, for `std::rc::Weak<T>`, this will be `std::rc::Rc<T>`.
24    type Strong;
25
26    /// Constructs a weak pointer from a strong pointer.
27    ///
28    /// This is usually implemented by a `downgrade` method.
29    fn new(view: &Self::Strong) -> Self;
30
31    /// Acquires a strong pointer from a weak pointer.
32    ///
33    /// This is usually implemented by an `upgrade` method.
34    fn view(&self) -> Option<Self::Strong>;
35
36    /// Is the given weak element expired?
37    ///
38    /// The default implemention checks whether a strong pointer can be obtained via `view`.
39    fn is_expired(&self) -> bool {
40        self.view().is_none()
41    }
42
43    /// Clones a strong pointer.
44    ///
45    /// The default implementation uses `new` and `view`; you should override it.
46    fn clone(view: &Self::Strong) -> Self::Strong
47    where
48        Self: Sized,
49    {
50        Self::new(view).view().expect("WeakElement::clone")
51    }
52}
53
54/// Interface for elements that can act as keys in weak hash tables.
55///
56/// To use an element as a weak hash map key or weak hash set element), the hash table
57/// needs to be able to view the actual key values to hash and compare them. This trait
58/// provides the necessary mechanism.
59pub trait WeakKey: WeakElement {
60    /// The underlying key type.
61    ///
62    /// For example, for `std::rc::Weak<T>`, this will be `T`.
63    type Key: ?Sized + Eq + Hash;
64
65    /// Allows borrowing a view of the key, via a callback.
66    ///
67    /// Rather than returning a borrowed reference to the actual key, this method passes a
68    /// reference to the key to a callback with an implicit higher-order lifetime bound. This is
69    /// necessary to get the lifetimes right in cases where the key is not actually store in the
70    /// strong pointer.
71    fn with_key<F, R>(view: &Self::Strong, f: F) -> R
72    where
73        F: FnOnce(&Self::Key) -> R;
74
75    /// Hashes the key `view` into the given `Hasher`.
76    #[inline]
77    fn hash<H: Hasher>(view: &Self::Strong, h: &mut H) {
78        Self::with_key(view, |k| k.hash(h));
79    }
80
81    /// Returns whether the key `view` equals the given `key`.
82    #[inline]
83    fn equals<Q>(view: &Self::Strong, key: &Q) -> bool
84    where
85        Q: ?Sized + Eq,
86        Self::Key: Borrow<Q>,
87    {
88        Self::with_key(view, |k| k.borrow() == key)
89    }
90}
91
92impl<T: ?Sized> WeakElement for rc::Weak<T> {
93    type Strong = rc::Rc<T>;
94
95    fn new(view: &Self::Strong) -> Self {
96        rc::Rc::<T>::downgrade(view)
97    }
98
99    fn view(&self) -> Option<Self::Strong> {
100        self.upgrade()
101    }
102
103    fn clone(view: &Self::Strong) -> Self::Strong {
104        view.clone()
105    }
106}
107
108impl<T: ?Sized + Eq + Hash> WeakKey for rc::Weak<T> {
109    type Key = T;
110
111    #[inline]
112    fn with_key<F, R>(view: &Self::Strong, f: F) -> R
113    where
114        F: FnOnce(&Self::Key) -> R,
115    {
116        f(view)
117    }
118}
119
120impl<T: ?Sized> WeakElement for sync::Weak<T> {
121    type Strong = sync::Arc<T>;
122
123    fn new(view: &Self::Strong) -> Self {
124        sync::Arc::<T>::downgrade(view)
125    }
126
127    fn view(&self) -> Option<Self::Strong> {
128        self.upgrade()
129    }
130
131    fn clone(view: &Self::Strong) -> Self::Strong {
132        view.clone()
133    }
134}
135
136impl<T: ?Sized + Eq + Hash> WeakKey for sync::Weak<T> {
137    type Key = T;
138
139    #[inline]
140    fn with_key<F, R>(view: &Self::Strong, f: F) -> R
141    where
142        F: FnOnce(&Self::Key) -> R,
143    {
144        f(view)
145    }
146}