grafix_toolbox/kit/policies/
types.rs

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
pub mod cached;
pub mod cached_str;
pub mod lazy;
pub mod memoized;
pub mod prefetch;

pub mod ext {
	#[derive(Debug)]
	pub struct TPtr<T> {
		ptr: usize,
		t: Dummy<T>,
	}
	impl<T: Send + Sync> TPtr<T> {
		pub unsafe fn new(t: &mut T) -> Self {
			let ptr = t as *mut T as usize;
			Self { ptr, t: Dummy }
		}
		pub fn get(&self) -> &'static T {
			unsafe { &*(self.ptr as *const T) }
		}
		pub fn get_mut(&mut self) -> &'static mut T {
			unsafe { &mut *(self.ptr as *mut T) }
		}
	}
	impl<T: Send + Sync> Copy for TPtr<T> {}
	impl<T: Send + Sync> Clone for TPtr<T> {
		fn clone(&self) -> Self {
			*self
		}
	}

	use std::marker::PhantomData as Dummy;
}

#[macro_export]
macro_rules! typed_ptr {
	($n: expr) => {{
			unsafe { TPtr::new($n) }
	}};
	($($n: expr),+) => {{
			unsafe { ($(TPtr::new($n),)+) }
	}};
}

#[macro_export]
macro_rules! LazyStatic {
	($t: ty, $b: block) => {{
		use std::sync::{Mutex, OnceLock};
		static S: OnceLock<Mutex<$t>> = OnceLock::new();
		S.get_or_init(|| Mutex::new($b)).lock().fail()
	}};
	($t: ty) => {
		LazyStatic!($t, { <$t>::default() })
	};
}

#[macro_export]
macro_rules! LocalStatic {
	($t: ty, $b: block) => {{
		use std::{cell::OnceCell, cell::Cell, mem::ManuallyDrop};
		thread_local!(static S: OnceCell<ManuallyDrop<Cell<$t>>> = Default::default());
		let r = S.with(|f| f.get_or_init(|| ManuallyDrop::new(Cell::new($b))).as_ptr());
		unsafe { &mut *r }
	}};
	($t: ty) => {
		LocalStatic!($t, { <$t>::default() })
	};
}