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
use crate::uses::{ops::*, Cast};

pub type CowStr = std::borrow::Cow<'static, str>;
pub type Res<T> = Result<T, String>;
pub type Str = &'static str;

#[macro_export]
macro_rules! map_enum {
	($i: expr, $v: pat, $m: expr) => {
		if let $v = $i {
			Some($m)
		} else {
			None
		}
	};
}

pub trait Utf8Len {
	fn utf8_len(&self) -> usize;
	fn len_at_char(&self, i: usize) -> usize;
}
impl Utf8Len for &str {
	fn utf8_len(&self) -> usize {
		self.chars().count()
	}
	fn len_at_char(&self, i: usize) -> usize {
		self.char_indices().skip(i).next().map_or_else(|| self.len(), |(i, _)| i)
	}
}

pub trait LastIdx {
	fn last_idx(&self) -> usize;
}
impl LastIdx for &str {
	fn last_idx(&self) -> usize {
		self.len().max(1) - 1
	}
}
impl<T> LastIdx for &[T] {
	fn last_idx(&self) -> usize {
		self.len().max(1) - 1
	}
}
impl<T> LastIdx for Vec<T> {
	fn last_idx(&self) -> usize {
		self.as_slice().last_idx()
	}
}

pub trait OrAssignment {
	fn or_def(self, with: bool) -> Self;
	fn or_val(self, with: bool, v: Self) -> Self;
}
impl<T: Default> OrAssignment for T {
	#[inline(always)]
	fn or_def(self, with: bool) -> Self {
		if with {
			self
		} else {
			Self::default()
		}
	}
	#[inline(always)]
	fn or_val(self, with: bool, v: Self) -> Self {
		if with {
			self
		} else {
			v
		}
	}
}

pub trait LerpMix: Cast<f32> {
	fn mix<M>(self, a: M, r: Self) -> Self
	where
		f32: Cast<M>;
}
impl<T: Cast<f32> + Copy + Add<Output = T> + Mul<Output = T>> LerpMix for T {
	fn mix<M>(self, a: M, r: Self) -> Self
	where
		f32: Cast<M>,
	{
		let a = f32::to(a);
		self * Self::to(1. - a) + r * Self::to(a)
	}
}

pub trait ResizeDefault {
	fn resize_def(&mut self, size: usize);
}
impl<T: Default> ResizeDefault for Vec<T> {
	fn resize_def(&mut self, size: usize) {
		if self.len() <= size {
			self.reserve(size);
			for _ in 0..size - self.len() {
				self.push(T::default());
			}
		} else {
			self.truncate(size);
		}
	}
}

pub trait Retain_Mut<T> {
	fn retain_mut<F>(&mut self, f: F)
	where
		F: FnMut(&mut T) -> bool;
}
impl<T> Retain_Mut<T> for Vec<T> {
	fn retain_mut<F>(&mut self, mut f: F)
	where
		F: FnMut(&mut T) -> bool,
	{
		let len = self.len();
		let mut del = 0;
		{
			let v = &mut **self;

			for i in 0..len {
				if !f(&mut v[i]) {
					del += 1;
				} else if del > 0 {
					v.swap(i - del, i);
				}
			}
		}
		if del > 0 {
			self.truncate(len - del);
		}
	}
}