mirl 9.2.0

Miners Rust Lib - A massive collection of ever growing and changing functions, structs, and enums. Check the description for compatibility and toggleable features! (Most of the lib is controlled by flags/features so the lib can continue to be lightweight despite its size)
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "bitcode", derive(bitcode::Encode, bitcode::Decode))]
// #[cfg_attr(feature = "wincode", derive(wincode::SchemaWrite, wincode::SchemaRead))]
#[must_use = "It is expected that the return value of a `FoundValue` is used for something"]
/// A enum that will return the value it beholds when a ? is used - The opposite of [Option]
#[cfg_attr(feature = "c_compatible", repr(C))]
pub enum FoundValue<V> {
    #[default]
    /// The item was not found, continue execution
    NotFound,
    /// The item was found, exit the current function!
    Found(V),
}
impl<V> core::ops::Try for FoundValue<V> {
    type Output = ();
    type Residual = V;

    fn from_output((): ()) -> Self {
        Self::NotFound
    }

    fn branch(self) -> core::ops::ControlFlow<V, ()> {
        match self {
            Self::NotFound => core::ops::ControlFlow::Continue(()),
            Self::Found(v) => core::ops::ControlFlow::Break(v),
        }
    }
}
impl<V> Unwrap<V> for FoundValue<V> {
    fn unwrap(self) -> V {
        match self {
            Self::Found(val) => val,
            Self::NotFound => {
                panic!("called `Unwrap::unwrap()` on a `NotFound` value")
            }
        }
    }
    fn unwrap_or(self, default: V) -> V {
        match self {
            Self::Found(val) => val,
            Self::NotFound => default,
        }
    }
    unsafe fn unwrap_unchecked(self) -> V {
        match self {
            Self::Found(val) => val,
            Self::NotFound => core::hint::unreachable_unchecked(),
        }
    }
}
impl<V: Default> UnwrapDefault<V> for FoundValue<V> {
    fn unwrap_or_default(self) -> V {
        match self {
            Self::Found(val) => val,
            Self::NotFound => V::default(),
        }
    }
}

/// Convert to [`FoundValue`] which returns upon having a value instead of not having a value (opposite of [`Option`])
pub trait ToFoundValue<T> {
    /// Convert to [`FoundValue`] which returns upon having a value instead of not having a value (opposite of [`Option`])
    fn found_error(self) -> FoundValue<T>;
}
impl<T, E> ToFoundValue<E> for Result<T, E> {
    fn found_error(self) -> FoundValue<E> {
        match self {
            Self::Ok(_) => FoundValue::NotFound,
            Self::Err(val) => FoundValue::Found(val),
        }
    }
}
impl<E> ToFoundValue<E> for Option<E> {
    fn found_error(self) -> FoundValue<E> {
        match self {
            Self::None => FoundValue::NotFound,
            Self::Some(val) => FoundValue::Found(val),
        }
    }
}

impl<V> core::ops::FromResidual<V> for FoundValue<V> {
    fn from_residual(residual: V) -> Self {
        Self::Found(residual)
    }
}

impl<E> core::ops::FromResidual<Result<core::convert::Infallible, E>> for FoundValue<E> {
    fn from_residual(residual: Result<core::convert::Infallible, E>) -> Self {
        match residual {
            Err(e) => Self::Found(e),
        }
    }
}
impl<T> From<Option<T>> for FoundValue<T> {
    fn from(val: Option<T>) -> Self {
        val.map_or_else(|| Self::NotFound, |val| Self::Found(val))
    }
}
impl<T> FromPatch<Option<T>> for FoundValue<T> {
    fn from_value(val: Option<T>) -> Self {
        val.map_or_else(|| Self::NotFound, |val| Self::Found(val))
    }
}
impl<T> From<T> for FoundValue<T> {
    fn from(val: T) -> Self {
        Self::Found(val)
    }
}
impl<T> FromPatch<T> for FoundValue<T> {
    fn from_value(val: T) -> Self {
        Self::Found(val)
    }
}

/// Lists but copyable
#[cfg(feature = "std")]
pub mod copyable_list;

#[cfg(feature = "std")]
mod codec;
#[cfg(feature = "std")]
pub use codec::*;

/// Horizontal Arrow + Control behavior
#[cfg(feature = "std")]
pub mod skipping_text_type;

#[cfg(feature = "keycodes")]
#[cfg(feature = "std")]
/// A few lines of helper code for easier keybind handling time
pub mod keybinds;

#[cfg(feature = "std")]
use core::hash::Hasher;

#[cfg(feature = "std")]
/// Combine 2 strings
pub fn concatenate<A: AsRef<str>, B: AsRef<str>>(a: A, b: B) -> String {
    let mut result = String::from(a.as_ref());
    result.push_str(b.as_ref());
    result
}
#[cfg(feature = "std")]
/// Hash a value
pub fn hash_value<T: core::hash::Hash>(value: &T) -> u64 {
    let mut s = std::hash::DefaultHasher::new();
    value.hash(&mut s);
    s.finish()
}
#[cfg_attr(feature = "bitcode", derive(bitcode::Encode, bitcode::Decode))]
#[cfg_attr(
    feature = "wincode",
    derive(wincode::SchemaWrite, wincode::SchemaRead)
)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy)]
/// Convert from one ratio to another
#[cfg_attr(feature = "c_compatible", repr(C))]
pub struct RatioConverter2D<T: IntoPatch<F>, F: IntoPatch<T> + Copy> {
    ratio: (F, F),
    inverse_ratio: (F, F),
    phantom: core::marker::PhantomData<T>,
}
use crate::prelude::{FromPatch, IntoPatch, Unwrap, UnwrapDefault};
#[allow(clippy::missing_const_for_fn)]
const impl<
        T: [const] core::ops::Add<Output = T>
            + [const] core::ops::Sub<Output = T>
            + [const] core::ops::Mul<Output = T>
            + [const] core::ops::Div<Output = T>
            + Copy
            + [const] IntoPatch<F>,
        F: [const] IntoPatch<T>
            + [const] core::ops::Add<Output = F>
            + [const] core::ops::Sub<Output = F>
            + [const] core::ops::Mul<Output = F>
            + [const] core::ops::Div<Output = F>
            + Copy,
    > RatioConverter2D<T, F>
{
    /// Create a new ratio
    #[must_use]
    pub fn new(smaller: (T, T), bigger: (T, T)) -> Self {
        Self {
            ratio: (
                (smaller.0).into_value() / (bigger.0).into_value(),
                (smaller.1).into_value() / (bigger.1).into_value(),
            ),
            inverse_ratio: (
                (bigger.0).into_value() / (smaller.0).into_value(),
                (bigger.1).into_value() / (smaller.1).into_value(),
            ),
            phantom: core::marker::PhantomData,
        }
    }
    /// Convert a value from the smaller ratio to the bigger ratio
    pub fn smaller_to_bigger(&self, value: (T, T)) -> (T, T) {
        (
            ((value.0).into_value() * self.inverse_ratio.0).into_value(),
            ((value.1).into_value() * self.inverse_ratio.1).into_value(),
        )
    }
    /// Convert a value from the bigger ratio to the smaller ratio
    pub fn bigger_to_smaller(&self, value: (T, T)) -> (T, T) {
        (
            ((value.0).into_value() * self.ratio.0).into_value(),
            ((value.1).into_value() * self.ratio.1).into_value(),
        )
    }
}

/// A windows only section for misc function
#[cfg(target_os = "windows")]
#[cfg(feature = "system")]
#[cfg(feature = "std")]
pub mod windows {
    // use windows::Win32::System::Diagnostics::Debug::GetThreadContext;
    // use windows::Win32::System::Memory::{
    //     VirtualQuery, MEMORY_BASIC_INFORMATION,
    // };

    use windows::Win32::System::Memory::{
        VirtualQuery, MEMORY_BASIC_INFORMATION,
    };
    #[allow(trivial_casts)]
    #[allow(clippy::ref_as_ptr)]
    /// Check the stack use
    ///
    /// # Errors
    pub fn get_actual_stack_info() {
        unsafe {
            let current_sp = (&0 as *const i32).cast::<std::ffi::c_void>(); // &0 as *const i32 as *const std::ffi::c_void
            let mut mbi = MEMORY_BASIC_INFORMATION::default();

            // Query the memory region containing current stack pointer
            VirtualQuery(
                Some(current_sp),
                &raw mut mbi,
                std::mem::size_of::<MEMORY_BASIC_INFORMATION>(),
            );

            let region_base = mbi.BaseAddress as usize;
            let region_size = mbi.RegionSize;
            let current_addr = current_sp as usize;

            println!("Memory region base:   0x{region_base:x}");
            println!("Memory region size:   {} MB", region_size / 1024 / 1024);
            println!("Current SP:           0x{current_addr:x}");
            println!(
                "Offset in region:     {} KB",
                (current_addr - region_base) / 1024
            );

            // Stack grows downward, so distance from top of region
            let used_from_top = (region_base + region_size) - current_addr;
            println!("Used from region top: {} KB", used_from_top / 1024);
        }
    }
}

#[macro_export]
/// Create a compile time warning using deprecation
macro_rules! compile_warn {
    ($msg:expr) => {
        #[allow(dead_code)]
        fn deprecated_container() {
            #[deprecated(note = $msg)]
            const fn deprecated_trigger() {}
            let _ = deprecated_trigger;
        }
    };
}
#[must_use]
#[cfg(feature = "std")]
/// Get the name of the type of the inputted variable
pub fn type_name_of_val<T>(_: &T) -> &'static str {
    std::any::type_name::<T>()
}

// /// Check if 2 objects are the same
// #[cfg(feature = "std")]
// pub const trait Comparable {
//     /// Convert self to `&dyn std::any::Any`
//     fn compare_as_any(&self) -> &dyn std::any::Any;
//     /// Check if this and another object are the same
//     fn is_same(&self, other: &dyn Comparable) -> bool;
// }
// #[cfg(feature = "std")]
// impl<T: 'static + PartialEq> Comparable for T {
//     fn compare_as_any(&self) -> &dyn std::any::Any {
//         self
//     }

//     fn is_same(&self, other: &dyn Comparable) -> bool {
//         // Try to downcast `other` to Foo
//         other.compare_as_any().downcast_ref::<Self>() == Some(self)
//     }
// }
// impl<T: PartialEq> Comparable for T {
//     fn is_same(&self, other: &Self) -> bool {
//         self == other
//     }
// }

// impl<T: core::hash::Hash> Comparable for T {
//     fn is_same(&self, other: &Self) -> bool {
//         let mut own_hasher = std::hash::DefaultHasher::new();
//         let mut other_hasher = std::hash::DefaultHasher::new();
//         self.hash(&mut own_hasher);
//         other.hash(&mut other_hasher);
//         own_hasher == other_hasher
//     }
// }
#[cfg_attr(feature = "bitcode", derive(bitcode::Encode, bitcode::Decode))]
// #[cfg_attr(feature = "wincode", derive(wincode::SchemaWrite, wincode::SchemaRead))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
/// Choose between 2 values
#[cfg_attr(feature = "c_compatible", repr(C))]
pub enum TwoOptions<O1, O2> {
    /// Select the first of 2 options
    Option1(O1),
    /// Select the second of 2 options
    Option2(O2),
}

/// I am already aware it is unsafe, just let me unwrap it!
pub const trait EasyUnwrapUnchecked<T> {
    /// I am already aware it is unsafe, just let me unwrap it!
    fn easy_unwrap_unchecked(self) -> T;
}

impl<T> EasyUnwrapUnchecked<T> for Option<T> {
    fn easy_unwrap_unchecked(self) -> T {
        unsafe { self.unwrap_unchecked() }
    }
}
impl<T, E> EasyUnwrapUnchecked<T> for Result<T, E> {
    fn easy_unwrap_unchecked(self) -> T {
        unsafe { self.unwrap_unchecked() }
    }
}

#[cfg(feature = "std")]
/// A standardized map format
mod map_extension;
#[cfg(feature = "std")]
pub use map_extension::*;

mod scrollable_container;
pub use scrollable_container::*;

#[cfg(feature = "std")]
mod clone_any;
#[cfg(feature = "std")]
pub use clone_any::*;

#[macro_export]
/// Usage: `impl_empty_trait!(std::sync::Send for Struct1 Struct2 Struct3)`
macro_rules! impl_empty_trait {
    ($name:ident for $($t:ty),* $(,)?) => {
        $(
            impl $name for $t {}
        )*
    };
}

#[cfg(feature = "std")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
/// A ticker, regulate the timing of an application
#[cfg_attr(feature = "c_compatible", repr(C))]
pub struct Ticker {
    /// 1/fps
    pub target_delta_time: std::time::Duration,
    /// The last time this struct got ticked
    pub last_frame: std::time::Instant,
    /// When the next frame should start
    pub next_frame: std::time::Instant,
    /// The current delta time -> Time between frame starts/ends
    pub delta_time: std::time::Duration,
}
#[cfg(feature = "std")]
impl Ticker {
    #[must_use]
    /// Create a new ticker, holds invalid data until ticked once
    ///
    /// # Errors
    /// When fps it too high/negative to fit into [`std::time::Duration`]
    pub fn new(fps: f64) -> Option<Self> {
        Some(Self {
            target_delta_time: std::time::Duration::try_from_secs_f64(
                1.0 / fps,
            )
            .ok()?,
            last_frame: std::time::Instant::now(),
            next_frame: std::time::Instant::now(),
            delta_time: std::time::Duration::new(0, 0),
        })
    }
    /// Tick the Ticker
    ///
    /// If the frame took too long, the next frame will be skipped
    /// If there is still time left, it will sleep until the desired frame time
    pub fn tick(&mut self) {
        let now = std::time::Instant::now();
        self.delta_time = now - self.last_frame;
        self.last_frame = now;
        if now > self.next_frame {
            self.next_frame = now + self.target_delta_time;
        } else {
            std::thread::sleep(self.next_frame - now);
            self.next_frame += self.target_delta_time;
        }
    }
    #[must_use]
    /// Get the delta time, use [`as_secs_f32`](std::time::Duration::as_secs_f32) or [`as_secs_64`](std::time::Duration::as_secs_f64) on that duration
    pub const fn get_delta_time(&self) -> std::time::Duration {
        self.delta_time
    }
    /// Get the delta time and the fps of the last tick
    #[must_use]
    pub const fn get_delta_time_and_fps_f32(&self) -> (f32, f32) {
        let delta = self.delta_time.as_secs_f32();
        (delta, 1.0 / delta)
    }
    /// Get the delta time and the fps of the last tick
    #[must_use]
    pub const fn get_delta_time_and_fps_f64(&self) -> (f64, f64) {
        let delta = self.delta_time.as_secs_f64();
        (delta, 1.0 / delta)
    }
}
#[cfg(feature = "std")]
/// A scene - A collection of shapes and positions
pub mod scene;
#[cfg(feature = "std")]
#[must_use]
/// Convert the given bytes into as much human readable text as possible
pub fn bytes_to_mixed_string(bytes: &[u8]) -> String {
    let mut out = String::new();
    let mut i = 0;

    while i < bytes.len() {
        match std::str::from_utf8(&bytes[i..]) {
            Ok(s) => {
                out.push_str(s);
                break;
            }
            Err(e) => {
                let valid = e.valid_up_to();
                if valid > 0 {
                    out.push_str(
                        std::str::from_utf8(&bytes[i..i + valid])
                            .easy_unwrap_unchecked(),
                    );
                    i += valid;
                } else {
                    out.push_str(&format!("\\x{:02X}", bytes[i]));
                    i += 1;
                }
            }
        }
    }

    out
}
/// Create a list of bools based on a string with 1s and 0s
#[cfg(feature = "std")]
#[must_use]
pub fn bit_str_to_bits(bit_str: &str) -> Option<Vec<bool>> {
    bit_str
        .chars()
        .map(|x| match x {
            '0' => Some(false),
            '1' => Some(true),
            _ => None,
        })
        .collect()
}

/// Extra buffer functions that need improvement before proper placement
#[cfg(feature = "std")]
pub mod buffer_extension {
    use crate::Buffer;
    /// Create a buffer from a bitmask sequence
    ///
    /// # Errors
    /// When the given dimensions don't match
    pub fn buffer_from_bitmask(
        mask: &[bool],
        size: (usize, usize),
        color_0: u32,
        color_1: u32,
    ) -> Result<Buffer, String> {
        let mut new = Vec::with_capacity(mask.len());
        for i in mask {
            if *i {
                new.push(color_1);
            } else {
                new.push(color_0);
            }
        }
        Buffer::new(size, new)
    }
}