erg_common 0.6.35

A common components library of Erg
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
use std::fmt;
use std::hash::{Hash, Hasher};
use std::thread::ThreadId;
// use std::rc::Rc;
pub use parking_lot::{
    MappedRwLockReadGuard, MappedRwLockWriteGuard, RwLock, RwLockReadGuard, RwLockWriteGuard,
};
use std::cell::RefCell;
use std::ops::Deref;
use std::sync::Arc;
use std::time::Duration;

use thread_local::ThreadLocal;

const GET_TIMEOUT: Duration = Duration::from_secs(4);
const SET_TIMEOUT: Duration = Duration::from_secs(8);

#[derive(Debug)]
pub struct BorrowInfo {
    location: Option<&'static std::panic::Location<'static>>,
    thread_name: String,
}

impl std::fmt::Display for BorrowInfo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.location {
            Some(location) => write!(
                f,
                "{}:{}, thread: {}",
                location.file(),
                location.line(),
                self.thread_name
            ),
            None => write!(f, "unknown, thread: {}", self.thread_name),
        }
    }
}

impl BorrowInfo {
    pub fn new(location: Option<&'static std::panic::Location<'static>>) -> Self {
        Self {
            location,
            thread_name: std::thread::current()
                .name()
                .unwrap_or("unknown")
                .to_string(),
        }
    }
}

#[derive(Debug)]
pub struct Shared<T: ?Sized> {
    data: Arc<RwLock<T>>,
    #[cfg(any(feature = "backtrace", feature = "debug"))]
    last_borrowed_at: Arc<RwLock<BorrowInfo>>,
    #[cfg(any(feature = "backtrace", feature = "debug"))]
    last_mut_borrowed_at: Arc<RwLock<BorrowInfo>>,
    lock_thread_id: Arc<RwLock<Vec<ThreadId>>>,
}

impl<T: PartialEq> PartialEq for Shared<T>
where
    RwLock<T>: PartialEq,
{
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.data == other.data
    }
}

impl<T: ?Sized> Clone for Shared<T> {
    fn clone(&self) -> Shared<T> {
        Self {
            data: Arc::clone(&self.data),
            #[cfg(any(feature = "backtrace", feature = "debug"))]
            last_borrowed_at: self.last_borrowed_at.clone(),
            #[cfg(any(feature = "backtrace", feature = "debug"))]
            last_mut_borrowed_at: self.last_mut_borrowed_at.clone(),
            lock_thread_id: self.lock_thread_id.clone(),
        }
    }
}

impl<T: Eq> Eq for Shared<T> where RwLock<T>: Eq {}

impl<T: Hash> Hash for Shared<T> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.borrow().hash(state);
    }
}

impl<T: Default> Default for Shared<T> {
    fn default() -> Self {
        Self::new(Default::default())
    }
}

impl<T: fmt::Display> fmt::Display for Shared<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.borrow().fmt(f)
    }
}

impl<T> Shared<T> {
    pub fn new(t: T) -> Self {
        Self {
            data: Arc::new(RwLock::new(t)),
            #[cfg(any(feature = "backtrace", feature = "debug"))]
            last_borrowed_at: Arc::new(RwLock::new(BorrowInfo::new(None))),
            #[cfg(any(feature = "backtrace", feature = "debug"))]
            last_mut_borrowed_at: Arc::new(RwLock::new(BorrowInfo::new(None))),
            lock_thread_id: Arc::new(RwLock::new(vec![])),
        }
    }

    #[inline]
    pub fn into_inner(self) -> T {
        let mutex = match Arc::try_unwrap(self.data) {
            Ok(mutex) => mutex,
            Err(_rc) => panic!("unwrapping failed"),
        };
        RwLock::into_inner(mutex)
    }
}

impl<T: ?Sized> Shared<T> {
    #[track_caller]
    fn wait_until_unlocked(&self) {
        let mut timeout = GET_TIMEOUT;
        loop {
            let lock_thread = self.lock_thread_id.try_read_for(GET_TIMEOUT).unwrap();
            if lock_thread.is_empty() || lock_thread.last() == Some(&std::thread::current().id()) {
                break;
            }
            std::thread::sleep(Duration::from_millis(1));
            timeout -= Duration::from_millis(1);
            if timeout == Duration::from_secs(0) {
                panic!("timeout");
            }
        }
    }

    #[inline]
    #[track_caller]
    pub fn borrow(&self) -> RwLockReadGuard<'_, T> {
        self.wait_until_unlocked();
        let res = self.data.try_read_for(GET_TIMEOUT).unwrap_or_else(|| {
            #[cfg(any(feature = "backtrace", feature = "debug"))]
            {
                panic!(
                    "Shared::borrow: already borrowed at {}, mutably borrowed at {:?}",
                    self.last_borrowed_at.try_read_for(GET_TIMEOUT).unwrap(),
                    self.last_mut_borrowed_at.try_read_for(GET_TIMEOUT).unwrap()
                )
            }
            #[cfg(not(any(feature = "backtrace", feature = "debug")))]
            {
                panic!("Shared::borrow: already borrowed")
            }
        });
        #[cfg(any(feature = "backtrace", feature = "debug"))]
        {
            *self.last_borrowed_at.try_write_for(GET_TIMEOUT).unwrap() =
                BorrowInfo::new(Some(std::panic::Location::caller()));
        }
        res
    }

    #[inline]
    #[track_caller]
    pub fn borrow_mut(&self) -> RwLockWriteGuard<'_, T> {
        self.wait_until_unlocked();
        let res = self.data.try_write_for(SET_TIMEOUT).unwrap_or_else(|| {
            #[cfg(any(feature = "backtrace", feature = "debug"))]
            {
                panic!(
                    "Shared::borrow_mut: already borrowed at {}, mutabbly borrowed at {}",
                    self.last_borrowed_at.try_read_for(SET_TIMEOUT).unwrap(),
                    self.last_mut_borrowed_at.try_read_for(SET_TIMEOUT).unwrap()
                )
            }
            #[cfg(not(any(feature = "backtrace", feature = "debug")))]
            {
                panic!("Shared::borrow_mut: already borrowed")
            }
        });
        #[cfg(any(feature = "backtrace", feature = "debug"))]
        {
            let caller = std::panic::Location::caller();
            *self.last_borrowed_at.try_write_for(SET_TIMEOUT).unwrap() =
                BorrowInfo::new(Some(caller));
            *self
                .last_mut_borrowed_at
                .try_write_for(SET_TIMEOUT)
                .unwrap() = BorrowInfo::new(Some(caller));
        }
        res
    }

    /// Lock the data and deny access from other threads.
    /// Locking can be done any number of times and will not be available until unlocked the same number of times.
    pub fn inter_thread_lock(&self) {
        let mut lock_thread = self.lock_thread_id.try_write_for(GET_TIMEOUT).unwrap();
        loop {
            if lock_thread.is_empty() || lock_thread.last() == Some(&std::thread::current().id()) {
                break;
            }
            drop(lock_thread);
            lock_thread = self.lock_thread_id.try_write_for(GET_TIMEOUT).unwrap();
        }
        lock_thread.push(std::thread::current().id());
    }

    #[track_caller]
    pub fn inter_thread_unlock(&self) {
        let mut lock_thread = self.lock_thread_id.try_write_for(GET_TIMEOUT).unwrap();
        loop {
            if lock_thread.is_empty() {
                panic!("not locked");
            } else if lock_thread.last() == Some(&std::thread::current().id()) {
                break;
            }
            drop(lock_thread);
            lock_thread = self.lock_thread_id.try_write_for(GET_TIMEOUT).unwrap();
        }
        lock_thread.pop();
    }

    pub fn inter_thread_unlock_using_id(&self, id: ThreadId) {
        let mut lock_thread = self.lock_thread_id.try_write_for(GET_TIMEOUT).unwrap();
        loop {
            if lock_thread.is_empty() {
                panic!("not locked");
            } else if lock_thread.last() == Some(&id)
                || lock_thread.last() == Some(&std::thread::current().id())
            {
                break;
            }
            drop(lock_thread);
            lock_thread = self.lock_thread_id.try_write_for(GET_TIMEOUT).unwrap();
        }
        lock_thread.pop();
    }

    pub fn get_mut(&mut self) -> Option<&mut T> {
        Arc::get_mut(&mut self.data).map(|mutex| mutex.get_mut())
    }

    pub fn as_ptr(&self) -> *mut T {
        RwLock::data_ptr(&self.data)
    }

    pub fn try_borrow(&self) -> Option<RwLockReadGuard<'_, T>> {
        self.data.try_read()
    }

    pub fn try_borrow_mut(&self) -> Option<RwLockWriteGuard<'_, T>> {
        self.data.try_write()
    }

    pub fn try_borrow_for(&self, timeout: Duration) -> Option<RwLockReadGuard<'_, T>> {
        self.data.try_read_for(timeout)
    }

    pub fn try_borrow_mut_for(&self, timeout: Duration) -> Option<RwLockWriteGuard<'_, T>> {
        self.data.try_write_for(timeout)
    }

    /// # Safety
    /// don't call this except you need to handle cyclic references.
    pub unsafe fn force_unlock_write(&self) {
        self.data.force_unlock_write();
    }
}

impl<T: Clone> Shared<T> {
    #[inline]
    pub fn clone_inner(&self) -> T {
        self.borrow().clone()
    }
}

/// Thread-local objects that can be shared among threads.
/// The initial value can be shared globally, but the changes are not reflected in other threads.
/// Otherwise, this behaves as a `RefCell`.
#[derive(Clone)]
pub struct Forkable<T: Send + Clone> {
    data: Arc<ThreadLocal<RefCell<T>>>,
    init: Arc<T>,
    #[cfg(any(feature = "backtrace", feature = "debug"))]
    last_borrowed_at: Arc<ThreadLocal<RefCell<BorrowInfo>>>,
    #[cfg(any(feature = "backtrace", feature = "debug"))]
    last_mut_borrowed_at: Arc<ThreadLocal<RefCell<BorrowInfo>>>,
}

impl<T: fmt::Debug + Send + Clone> fmt::Debug for Forkable<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.deref().fmt(f)
    }
}

impl<T: fmt::Display + Send + Clone> fmt::Display for Forkable<T>
where
    RefCell<T>: fmt::Display,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.deref().fmt(f)
    }
}

impl<T: Send + Clone> Deref for Forkable<T> {
    type Target = RefCell<T>;
    fn deref(&self) -> &Self::Target {
        self.data
            .get_or(|| RefCell::new(self.init.clone().as_ref().clone()))
    }
}

impl<T: Send + Clone> Forkable<T> {
    pub fn new(init: T) -> Self {
        Self {
            data: Arc::new(ThreadLocal::new()),
            init: Arc::new(init),
            #[cfg(any(feature = "backtrace", feature = "debug"))]
            last_borrowed_at: Arc::new(ThreadLocal::new()),
            #[cfg(any(feature = "backtrace", feature = "debug"))]
            last_mut_borrowed_at: Arc::new(ThreadLocal::new()),
        }
    }

    pub fn update_init(&mut self) {
        let clone = self.clone_inner();
        // NG: self.init = Arc::new(clone);
        *self = Self::new(clone);
    }

    pub fn clone_inner(&self) -> T {
        self.deref().borrow().clone()
    }

    #[track_caller]
    pub fn borrow(&self) -> std::cell::Ref<'_, T> {
        match self.deref().try_borrow() {
            Ok(res) => {
                #[cfg(any(feature = "backtrace", feature = "debug"))]
                {
                    *self
                        .last_borrowed_at
                        .get_or(|| RefCell::new(BorrowInfo::new(None)))
                        .borrow_mut() = BorrowInfo::new(Some(std::panic::Location::caller()));
                }
                res
            }
            Err(err) => {
                #[cfg(any(feature = "backtrace", feature = "debug"))]
                {
                    panic!(
                        "Forkable::borrow: already borrowed at {}, mutably borrowed at {} ({err})",
                        self.last_borrowed_at
                            .get_or(|| RefCell::new(BorrowInfo::new(None)))
                            .borrow(),
                        self.last_mut_borrowed_at
                            .get_or(|| RefCell::new(BorrowInfo::new(None)))
                            .borrow()
                    )
                }
                #[cfg(not(any(feature = "backtrace", feature = "debug")))]
                {
                    panic!("Forkable::borrow: {err}")
                }
            }
        }
    }

    #[track_caller]
    pub fn borrow_mut(&self) -> std::cell::RefMut<'_, T> {
        match self.deref().try_borrow_mut() {
            Ok(res) => {
                #[cfg(any(feature = "backtrace", feature = "debug"))]
                {
                    let caller = std::panic::Location::caller();
                    *self
                        .last_borrowed_at
                        .get_or(|| RefCell::new(BorrowInfo::new(None)))
                        .borrow_mut() = BorrowInfo::new(Some(caller));
                    *self
                        .last_mut_borrowed_at
                        .get_or(|| RefCell::new(BorrowInfo::new(None)))
                        .borrow_mut() = BorrowInfo::new(Some(caller));
                }
                res
            }
            Err(err) => {
                #[cfg(any(feature = "backtrace", feature = "debug"))]
                {
                    panic!(
                        "Forkable::borrow_mut: already borrowed at {}, mutably borrowed at {} ({err})",
                        self.last_borrowed_at
                            .get_or(|| RefCell::new(BorrowInfo::new(None)))
                            .borrow(),
                        self.last_mut_borrowed_at
                            .get_or(|| RefCell::new(BorrowInfo::new(None)))
                            .borrow()
                    )
                }
                #[cfg(not(any(feature = "backtrace", feature = "debug")))]
                {
                    panic!("Forkable::borrow_mut: {err}")
                }
            }
        }
    }
}