1 use std::rc::Weak as RcWeak;
2 use std::sync::Weak;
3 
4 use crate::RefCnt;
5 
6 unsafe impl<T> RefCnt for Weak<T> {
7     type Base = T;
as_ptr(me: &Self) -> *mut T8     fn as_ptr(me: &Self) -> *mut T {
9         Weak::as_raw(me) as *mut T
10     }
into_ptr(me: Self) -> *mut T11     fn into_ptr(me: Self) -> *mut T {
12         Weak::into_raw(me) as *mut T
13     }
from_ptr(ptr: *const T) -> Self14     unsafe fn from_ptr(ptr: *const T) -> Self {
15         Weak::from_raw(ptr)
16     }
17 }
18 
19 unsafe impl<T> RefCnt for RcWeak<T> {
20     type Base = T;
as_ptr(me: &Self) -> *mut T21     fn as_ptr(me: &Self) -> *mut T {
22         RcWeak::as_raw(me) as *mut T
23     }
into_ptr(me: Self) -> *mut T24     fn into_ptr(me: Self) -> *mut T {
25         RcWeak::into_raw(me) as *mut T
26     }
from_ptr(ptr: *const T) -> Self27     unsafe fn from_ptr(ptr: *const T) -> Self {
28         RcWeak::from_raw(ptr)
29     }
30 }
31 
32 #[cfg(test)]
33 mod tests {
34     use std::sync::{Arc, Weak};
35 
36     use crate::ArcSwapWeak;
37 
38     // Convert to weak, push it through the shared and pull it out again.
39     #[test]
there_and_back()40     fn there_and_back() {
41         let data = Arc::new("Hello");
42         let shared = ArcSwapWeak::new(Arc::downgrade(&data));
43         assert_eq!(1, Arc::strong_count(&data));
44         assert_eq!(1, Arc::weak_count(&data));
45         let weak = shared.load();
46         assert_eq!("Hello", *weak.upgrade().unwrap());
47         assert!(Arc::ptr_eq(&data, &weak.upgrade().unwrap()));
48     }
49 
50     // Replace a weak pointer with a NULL one
51     #[test]
reset()52     fn reset() {
53         let data = Arc::new("Hello");
54         let shared = ArcSwapWeak::new(Arc::downgrade(&data));
55         assert_eq!(1, Arc::strong_count(&data));
56         assert_eq!(1, Arc::weak_count(&data));
57 
58         // An empty weak (eg. NULL)
59         shared.store(Weak::new());
60         assert_eq!(1, Arc::strong_count(&data));
61         assert_eq!(0, Arc::weak_count(&data));
62 
63         let weak = shared.load();
64         assert!(weak.upgrade().is_none());
65     }
66 
67     // Destroy the underlying data while the weak is still stored inside. Should make it go
68     // NULL-ish
69     #[test]
destroy()70     fn destroy() {
71         let data = Arc::new("Hello");
72         let shared = ArcSwapWeak::new(Arc::downgrade(&data));
73 
74         drop(data);
75         let weak = shared.load();
76         assert!(weak.upgrade().is_none());
77     }
78 }
79