xref: /DragonOS/kernel/src/libs/lock_free_flags.rs (revision 45626c859f95054b76d8b59afcbd24c6b235026f)
1 use core::{cell::UnsafeCell, fmt::Debug};
2 
3 /// 一个无锁的标志位
4 ///
5 /// 可与bitflags配合使用,以实现无锁的标志位
6 ///
7 /// ## Safety
8 ///
9 /// 由于标识位的修改是无锁,且不保证原子性,因此需要使用者自行在别的机制中,确保
10 /// 哪怕标识位的值是老的,执行动作也不会有问题(或者有状态恢复机制)。
11 pub struct LockFreeFlags<T> {
12     inner: UnsafeCell<T>,
13 }
14 
15 impl<T> LockFreeFlags<T> {
16     pub unsafe fn new(inner: T) -> Self {
17         Self {
18             inner: UnsafeCell::new(inner),
19         }
20     }
21 
22     pub fn get_mut(&self) -> &mut T {
23         unsafe {
24             (self.inner.get().as_ref().unwrap() as *const T as *mut T)
25                 .as_mut()
26                 .unwrap()
27         }
28     }
29 
30     pub fn get(&self) -> &T {
31         unsafe { self.inner.get().as_ref().unwrap() }
32     }
33 }
34 
35 unsafe impl<T: Sync> Sync for LockFreeFlags<T> {}
36 unsafe impl<T: Send> Send for LockFreeFlags<T> {}
37 
38 impl<T: Clone> Clone for LockFreeFlags<T> {
39     fn clone(&self) -> Self {
40         unsafe { Self::new(self.get().clone()) }
41     }
42 }
43 
44 impl<T: Debug> Debug for LockFreeFlags<T> {
45     fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
46         f.debug_struct("LockFreeFlags")
47             .field("inner", self.get())
48             .finish()
49     }
50 }
51