Skip to main content

grafix_toolbox/kit/policies/func/
faster.rs

1use crate::lib::*;
2
3pub trait CharAsStr {
4	fn as_str(&self) -> STR;
5}
6impl CharAsStr for char {
7	fn as_str(&self) -> STR {
8		LocalStatic!(HashMap<char, Str>).entry(*self).or_insert_with(|| self.to_string().into())
9	}
10}
11
12pub trait UnwrapValid<R> {
13	fn valid(self) -> R;
14}
15pub trait ValidOption<R> {
16	fn as_valid(&self) -> &R;
17	fn mut_valid(&mut self) -> &mut R;
18}
19impl<R> ValidOption<R> for Option<R> {
20	#[inline(always)]
21	fn as_valid(&self) -> &R {
22		self.as_ref().valid()
23	}
24	#[inline(always)]
25	fn mut_valid(&mut self) -> &mut R {
26		self.as_mut().valid()
27	}
28}
29impl<R> UnwrapValid<R> for Option<R> {
30	#[inline(always)]
31	fn valid(self) -> R {
32		#[cfg(debug_assertions)]
33		{
34			self.explain_err(|| "Invalid").fail()
35		}
36		#[cfg(not(debug_assertions))]
37		{
38			unsafe { self.unwrap_unchecked() }
39		}
40	}
41}
42impl<R, E: Display> UnwrapValid<R> for Result<R, E> {
43	#[inline(always)]
44	fn valid(self) -> R {
45		#[cfg(debug_assertions)]
46		{
47			self.explain_err(|| "Invalid").fail()
48		}
49		#[cfg(not(debug_assertions))]
50		{
51			unsafe { self.unwrap_unchecked() }
52		}
53	}
54}
55
56pub trait FasterIndex<T> {
57	fn last_idx(&self) -> usize;
58	fn at<I>(&self, idx: I) -> &T
59	where
60		usize: Cast<I>;
61	fn at_mut<I>(&mut self, idx: I) -> &mut T
62	where
63		usize: Cast<I>;
64}
65impl<T> FasterIndex<T> for [T] {
66	fn last_idx(&self) -> usize {
67		self.len().max(1) - 1
68	}
69	#[inline(always)]
70	fn at<I>(&self, idx: I) -> &T
71	where
72		usize: Cast<I>,
73	{
74		let i = usize(idx);
75		#[cfg(debug_assertions)]
76		{
77			&self[i]
78		}
79		#[cfg(not(debug_assertions))]
80		{
81			unsafe { self.get_unchecked(i) }
82		}
83	}
84	#[inline(always)]
85	fn at_mut<I>(&mut self, idx: I) -> &mut T
86	where
87		usize: Cast<I>,
88	{
89		let i = usize(idx);
90		#[cfg(debug_assertions)]
91		{
92			&mut self[i]
93		}
94		#[cfg(not(debug_assertions))]
95		{
96			unsafe { self.get_unchecked_mut(i) }
97		}
98	}
99}