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
use crate::{is_main_thread, thread_id, Address, RefCounters};
use log::error;
use std::borrow::{Borrow, BorrowMut};
use std::fmt::{Debug, Formatter};
use std::{
    ops::{Deref, DerefMut},
    ptr::NonNull,
};

/// Weak reference. Doesn't affect reference counting.
/// It is better to check with `freed()` method before use because it
/// might contain pointer to deallocated object.
pub struct Weak<T: ?Sized> {
    pub(crate) address: usize,
    pub(crate) ptr: Option<NonNull<T>>,
}

unsafe impl<T: ?Sized> Send for Weak<T> {}
unsafe impl<T: ?Sized> Sync for Weak<T> {}

impl<T: ?Sized> Copy for Weak<T> {}

impl<T: ?Sized> Clone for Weak<T> {
    fn clone(&self) -> Self {
        Self {
            address: self.address,
            ptr: self.ptr,
        }
    }
}

impl<T: ?Sized> Weak<T> {
    pub const fn const_default() -> Self {
        Self {
            address: 0,
            ptr: None,
        }
    }

    pub fn from_ref(rf: &T) -> Self {
        let address = rf.address();
        assert!(
            RefCounters::exists(address),
            "Trying to get weak pointer for object which is not managed by reference counter."
        );
        let ptr = NonNull::new(rf as *const T as *mut T);
        assert!(ptr.is_some(), "Failed to get ptr from ref");
        Self { address, ptr }
    }

    pub fn addr(&self) -> usize {
        self.address
    }

    pub fn is_null(&self) -> bool {
        !self.is_ok()
    }

    pub fn is_ok(&self) -> bool {
        RefCounters::exists(self.address)
    }

    pub fn freed(&self) -> bool {
        self.ptr.is_some() && !RefCounters::exists(self.address)
    }

    pub fn get(&mut self) -> Option<&mut T> {
        if self.is_ok() {
            self.deref_mut().into()
        } else {
            None
        }
    }

    fn check(&self) {
        if !is_main_thread() {
            panic!(
                "Unsafe Weak pointer deref: {}. Thread is not Main. Thread id: {}",
                std::any::type_name::<T>(),
                thread_id()
            );
        }

        if self.ptr.is_none() {
            error!(
                "Defererencing never initialized weak pointer: {}",
                std::any::type_name::<T>()
            );
            // backtrace();
            panic!(
                "Defererencing never initialized weak pointer: {}",
                std::any::type_name::<T>()
            );
        }

        if !RefCounters::exists(self.address) {
            error!(
                "Defererencing already freed weak pointer: {}",
                std::any::type_name::<T>()
            );
            // backtrace();
            panic!(
                "Defererencing already freed weak pointer: {}",
                std::any::type_name::<T>()
            );
        }
    }
}

impl<T> Weak<T> {
    /// Create `Weak` without `Own` and leak memory.
    /// Used only for test purposes.
    pub unsafe fn leak(val: T) -> Self {

        let val = Box::new(val);
        let address = val.deref().address();
        let ptr = Box::leak(val) as *mut T;

        if address == 1 {
            panic!("Closure? Empty type?");
        }

        RefCounters::add_strong(address, ||{});

        Self {
            address,
            ptr: NonNull::new(ptr)
        }
    }
}

impl<T: ?Sized> Deref for Weak<T> {
    type Target = T;
    fn deref(&self) -> &T {
        self.check();
        unsafe { self.ptr.unwrap().as_ref() }
    }
}

impl<T: ?Sized> DerefMut for Weak<T> {
    fn deref_mut(&mut self) -> &mut T {
        self.check();
        unsafe { self.ptr.unwrap().as_mut() }
    }
}

impl<T: ?Sized> Borrow<T> for Weak<T> {
    fn borrow(&self) -> &T {
        self.deref()
    }
}

impl<T: ?Sized> BorrowMut<T> for Weak<T> {
    fn borrow_mut(&mut self) -> &mut T {
        self.deref_mut()
    }
}

impl<T: ?Sized> Default for Weak<T> {
    fn default() -> Self {
        Self {
            address: 0,
            ptr: None,
        }
    }
}

impl<T: ?Sized + Debug> Debug for Weak<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        self.deref().fmt(f)
    }
}

// TODO: Coerce
// impl<T, U> CoerceUnsized<Weak<U>> for Weak<T>
//     where
//         T: Unsize<U> + ?Sized,
//         U: ?Sized,
// {
// }

#[cfg(test)]
mod test {
    use std::ops::Deref;
    use crate::{set_current_thread_as_main, Strong, ToWeak, Weak};
    use serial_test::serial;

    #[derive(Default)]
    struct Sok {
        data: bool,
    }

    impl Sok {
        fn return_true(self: Weak<Self>) -> bool {
            !self.data
        }
    }

    #[test]
    #[serial]
    fn strong_to_weak() {
        set_current_thread_as_main();
        let strong: Strong<Sok> = Strong::new(Sok::default());
        assert!(strong.weak().return_true());
    }

    #[test]
    #[serial]
    fn leak_weak() {
        set_current_thread_as_main();
        let leaked = unsafe { Weak::leak(5) };
        dbg!(leaked.deref());
    }
}