-
Notifications
You must be signed in to change notification settings - Fork 662
Expand file tree
/
Copy pathhelpers.rs
More file actions
371 lines (312 loc) · 11 KB
/
helpers.rs
File metadata and controls
371 lines (312 loc) · 11 KB
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//! Random assortment of helpers I didn't know where to put.
use std::alloc::Allocator;
use std::cmp::Ordering;
use std::fmt::{Debug, Display};
use std::hash::Hash;
use std::io::Read;
use std::mem::{self, MaybeUninit};
use std::ops::{Bound, Range, RangeBounds};
use std::{fmt, ptr, slice, str};
use crate::apperr;
pub const KILO: usize = 1000;
pub const MEGA: usize = 1000 * 1000;
pub const GIGA: usize = 1000 * 1000 * 1000;
pub const KIBI: usize = 1024;
pub const MEBI: usize = 1024 * 1024;
pub const GIBI: usize = 1024 * 1024 * 1024;
pub struct MetricFormatter<T>(pub T);
impl fmt::Display for MetricFormatter<usize> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut value = self.0;
let mut suffix = "B";
if value >= GIGA {
value /= GIGA;
suffix = "GB";
} else if value >= MEGA {
value /= MEGA;
suffix = "MB";
} else if value >= KILO {
value /= KILO;
suffix = "kB";
}
write!(f, "{value}{suffix}")
}
}
/// A viewport coordinate type used throughout the application.
pub type CoordType = isize;
/// To avoid overflow issues because you're adding two [`CoordType::MAX`]
/// values together, you can use [`COORD_TYPE_SAFE_MAX`] instead.
///
/// It equates to half the bits contained in [`CoordType`], which
/// for instance is 32767 (0x7FFF) when [`CoordType`] is a [`i32`].
pub const COORD_TYPE_SAFE_MAX: CoordType = (1 << (CoordType::BITS / 2 - 1)) - 1;
/// A 2D point. Uses [`CoordType`].
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
pub struct Point {
pub x: CoordType,
pub y: CoordType,
}
impl Point {
pub const MIN: Self = Self { x: CoordType::MIN, y: CoordType::MIN };
pub const MAX: Self = Self { x: CoordType::MAX, y: CoordType::MAX };
}
impl PartialOrd<Self> for Point {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Point {
fn cmp(&self, other: &Self) -> Ordering {
self.y.cmp(&other.y).then(self.x.cmp(&other.x))
}
}
/// A 2D size. Uses [`CoordType`].
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
pub struct Size {
pub width: CoordType,
pub height: CoordType,
}
impl Size {
pub fn as_rect(&self) -> Rect {
Rect { left: 0, top: 0, right: self.width, bottom: self.height }
}
}
/// A 2D rectangle. Uses [`CoordType`].
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
pub struct Rect {
pub left: CoordType,
pub top: CoordType,
pub right: CoordType,
pub bottom: CoordType,
}
impl Rect {
/// Mimics CSS's `padding` property where `padding: a` is `a a a a`.
pub fn one(value: CoordType) -> Self {
Self { left: value, top: value, right: value, bottom: value }
}
/// Mimics CSS's `padding` property where `padding: a b` is `a b a b`,
/// and `a` is top/bottom and `b` is left/right.
pub fn two(top_bottom: CoordType, left_right: CoordType) -> Self {
Self { left: left_right, top: top_bottom, right: left_right, bottom: top_bottom }
}
/// Mimics CSS's `padding` property where `padding: a b c` is `a b c b`,
/// and `a` is top, `b` is left/right, and `c` is bottom.
pub fn three(top: CoordType, left_right: CoordType, bottom: CoordType) -> Self {
Self { left: left_right, top, right: left_right, bottom }
}
/// Is the rectangle empty?
pub fn is_empty(&self) -> bool {
self.left >= self.right || self.top >= self.bottom
}
/// Width of the rectangle.
pub fn width(&self) -> CoordType {
self.right - self.left
}
/// Height of the rectangle.
pub fn height(&self) -> CoordType {
self.bottom - self.top
}
/// Check if it contains a point.
pub fn contains(&self, point: Point) -> bool {
point.x >= self.left && point.x < self.right && point.y >= self.top && point.y < self.bottom
}
/// Intersect two rectangles.
pub fn intersect(&self, rhs: Self) -> Self {
let l = self.left.max(rhs.left);
let t = self.top.max(rhs.top);
let r = self.right.min(rhs.right);
let b = self.bottom.min(rhs.bottom);
// Ensure that the size is non-negative. This avoids bugs,
// because some height/width is negative all of a sudden.
let r = l.max(r);
let b = t.max(b);
Self { left: l, top: t, right: r, bottom: b }
}
}
/// [`std::cmp::minmax`] is unstable, as per usual.
pub fn minmax<T>(v1: T, v2: T) -> [T; 2]
where
T: Ord,
{
if v2 < v1 { [v2, v1] } else { [v1, v2] }
}
#[inline(always)]
#[allow(clippy::ptr_eq)]
fn opt_ptr<T>(a: Option<&T>) -> *const T {
unsafe { mem::transmute(a) }
}
/// Surprisingly, there's no way in Rust to do a `ptr::eq` on `Option<&T>`.
/// Uses `unsafe` so that the debug performance isn't too bad.
#[inline(always)]
#[allow(clippy::ptr_eq)]
pub fn opt_ptr_eq<T>(a: Option<&T>, b: Option<&T>) -> bool {
opt_ptr(a) == opt_ptr(b)
}
/// Creates a `&str` from a pointer and a length.
/// Exists, because `std::str::from_raw_parts` is unstable, par for the course.
///
/// # Safety
///
/// The given data must be valid UTF-8.
/// The given data must outlive the returned reference.
#[inline]
#[must_use]
pub const unsafe fn str_from_raw_parts<'a>(ptr: *const u8, len: usize) -> &'a str {
unsafe { str::from_utf8_unchecked(slice::from_raw_parts(ptr, len)) }
}
/// [`<[T]>::copy_from_slice`] panics if the two slices have different lengths.
/// This one just returns the copied amount.
pub fn slice_copy_safe<T: Copy>(dst: &mut [T], src: &[T]) -> usize {
let len = src.len().min(dst.len());
unsafe { ptr::copy_nonoverlapping(src.as_ptr(), dst.as_mut_ptr(), len) };
len
}
/// [`Vec::splice`] results in really bad assembly.
/// This doesn't. Don't use [`Vec::splice`].
pub trait ReplaceRange<T: Copy> {
fn replace_range<R: RangeBounds<usize>>(&mut self, range: R, src: &[T]);
}
impl<T: Copy, A: Allocator> ReplaceRange<T> for Vec<T, A> {
fn replace_range<R: RangeBounds<usize>>(&mut self, range: R, src: &[T]) {
let start = match range.start_bound() {
Bound::Included(&start) => start,
Bound::Excluded(start) => start + 1,
Bound::Unbounded => 0,
};
let end = match range.end_bound() {
Bound::Included(end) => end + 1,
Bound::Excluded(&end) => end,
Bound::Unbounded => usize::MAX,
};
vec_replace_impl(self, start..end, src);
}
}
fn vec_replace_impl<T: Copy, A: Allocator>(dst: &mut Vec<T, A>, range: Range<usize>, src: &[T]) {
unsafe {
let dst_len = dst.len();
let src_len = src.len();
let off = range.start.min(dst_len);
let del_len = range.end.saturating_sub(off).min(dst_len - off);
if del_len == 0 && src_len == 0 {
return; // nothing to do
}
let tail_len = dst_len - off - del_len;
let new_len = dst_len - del_len + src_len;
if src_len > del_len {
dst.reserve(src_len - del_len);
}
// NOTE: drop_in_place() is not needed here, because T is constrained to Copy.
// SAFETY: as_mut_ptr() must called after reserve() to ensure that the pointer is valid.
let ptr = dst.as_mut_ptr().add(off);
// Shift the tail.
if tail_len > 0 && src_len != del_len {
ptr::copy(ptr.add(del_len), ptr.add(src_len), tail_len);
}
// Copy in the replacement.
ptr::copy_nonoverlapping(src.as_ptr(), ptr, src_len);
dst.set_len(new_len);
}
}
/// [`Read`] but with [`MaybeUninit<u8>`] buffers.
pub fn file_read_uninit<T: Read>(
file: &mut T,
buf: &mut [MaybeUninit<u8>],
) -> apperr::Result<usize> {
unsafe {
let buf_slice = slice::from_raw_parts_mut(buf.as_mut_ptr() as *mut u8, buf.len());
let n = file.read(buf_slice)?;
Ok(n)
}
}
/// Turns a [`&[u8]`] into a [`&[MaybeUninit<T>]`].
#[inline(always)]
pub const fn slice_as_uninit_ref<T>(slice: &[T]) -> &[MaybeUninit<T>] {
unsafe { slice::from_raw_parts(slice.as_ptr() as *const MaybeUninit<T>, slice.len()) }
}
/// Turns a [`&mut [T]`] into a [`&mut [MaybeUninit<T>]`].
#[inline(always)]
pub const fn slice_as_uninit_mut<T>(slice: &mut [T]) -> &mut [MaybeUninit<T>] {
unsafe { slice::from_raw_parts_mut(slice.as_mut_ptr() as *mut MaybeUninit<T>, slice.len()) }
}
/// Helpers for ASCII string comparisons.
pub trait AsciiStringHelpers {
/// Tests if a string starts with a given ASCII prefix.
///
/// This function name really is a mouthful, but it's a combination
/// of [`str::starts_with`] and [`str::eq_ignore_ascii_case`].
fn starts_with_ignore_ascii_case(&self, prefix: &str) -> bool;
}
impl AsciiStringHelpers for str {
fn starts_with_ignore_ascii_case(&self, prefix: &str) -> bool {
// Casting to bytes first ensures we skip any UTF8 boundary checks.
// Since the comparison is ASCII, we don't need to worry about that.
let s = self.as_bytes();
let p = prefix.as_bytes();
p.len() <= s.len() && s[..p.len()].eq_ignore_ascii_case(p)
}
}
pub enum StackStringError {
ContentTooLong,
}
impl Debug for StackStringError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "desirable content is too long to fit in the string.")
}
}
#[derive(Clone, Copy)]
pub struct StackString<const N: usize> {
length: usize,
data: [u8; N],
}
impl<const N: usize> StackString<N> {
pub fn new(src: &str) -> Result<Self, StackStringError> {
let bytes = src.bytes().collect::<Vec<u8>>();
if bytes.len() > N {
return Err(StackStringError::ContentTooLong);
}
let mut data = [0u8; N];
// Horrible mem copy
// TODO: Fix ASAP
unsafe {
let chunk = std::slice::from_raw_parts_mut(data.as_mut_ptr(), bytes.len());
chunk.copy_from_slice(&bytes);
}
Ok(Self { length: bytes.len(), data })
}
pub fn as_str(&self) -> &str {
self.as_ref()
}
}
impl<const N: usize> AsRef<str> for StackString<N> {
fn as_ref(&self) -> &str {
// SAFETY: We constructed the string
unsafe { std::str::from_utf8_unchecked(&self.data[0..self.length]) }
}
}
impl<const N: usize> PartialEq for StackString<N> {
fn eq(&self, other: &Self) -> bool {
self.as_str() == other.as_str()
}
fn ne(&self, other: &Self) -> bool {
self.as_str() != other.as_str()
}
}
impl<const N: usize> Eq for StackString<N> {}
impl<const N: usize> Hash for StackString<N> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.as_str().hash(state);
}
}
impl<const N: usize> Display for StackString<N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
<str as Display>::fmt(self.as_str(), f)
}
}
impl<const N: usize> Debug for StackString<N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
<str as Debug>::fmt(self.as_str(), f)
}
}
pub type SmolString = StackString<16>;