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
// Not generally a fan of ai written code in most cases but when the 1 in a million prompt hits they produce some pretty workin' code
use core::ops::{
    Add,
    //AddAssign,
    Div,
    //DivAssign,
    Mul,
    //MulAssign,
    Sub,
    //SubAssign,
};

use crate::{
    math::{ConstOne, ConstZero},
    // prelude::TryFromPatch,
};

#[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))]
/// A type that represents a uniform range from 0.0 to 1.0 using any unsigned integer type
/// The internal value is stored as an unsigned integer where 0 represents 0.0 and MAX represents 1.0
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "c_compatible", repr(C))]
pub struct UniformRange<T: Copy + core::fmt::Debug> {
    value: T,
    //_phantom: core::marker::PhantomData<T>,
}

#[allow(unused_imports)]
use crate::extensions::*;

impl<T> UniformRange<T>
where
    T: TryIntoPatch<f64>
        + Copy
        + ConstZero
        + ConstOne
        + PartialOrd
        + Add<Output = T>
        + Sub<Output = T>
        + Mul<Output = T>
        + core::fmt::Debug
        + Div<Output = T>,
    f64: TryIntoPatch<T>,
{
    #[must_use]
    /// Create a new `UnitRange` with value 0.0
    pub const fn zero() -> Self {
        Self {
            value: T::ZERO,
            //_phantom: core::marker::PhantomData,
        }
    }

    #[must_use]
    /// Create a new `UnitRange` with value 1.0
    pub fn one() -> Self {
        Self {
            value: Self::max_value(),
            //_phantom: core::marker::PhantomData,
        }
    }

    #[must_use]
    /// Create a new `UnitRange` from a raw integer value
    pub const fn from_raw(value: T) -> Self {
        Self {
            value,
            //_phantom: core::marker::PhantomData,
        }
    }

    #[must_use]
    /// Create a new `UnitRange` from a float value (0.0 to 1.0)
    ///
    /// # Panics
    /// If T doesn't support being cast from f64
    pub fn from_f64(f: f64) -> Option<Self> {
        let clamped = f.clamp(0.0, 1.0);
        let max_val: f64 = (Self::max_value()).try_into_value()?;
        let scaled = (clamped * max_val).round();
        let value: T = (scaled).try_into_value()?;
        Some(Self {
            value,
            //_phantom: core::marker::PhantomData,
        })
    }
    #[must_use]
    #[allow(clippy::cast_lossless)]
    /// Create a new `UnitRange` from a float value (0.0 to 1.0)
    pub fn from_f32(f: f32) -> Option<Self> {
        Self::from_f64(f as f64)
    }
    #[must_use]
    #[allow(clippy::cast_lossless)]
    /// Create a new `UnitRange` from a float value (0.0 to 1.0)
    pub fn from_f16(f: f16) -> Option<Self> {
        Self::from_f64(f as f64)
    }
    #[must_use]
    /// Get the raw integer value
    pub const fn raw(&self) -> T {
        self.value
    }

    #[must_use]
    /// Convert to f64 (0.0 to 1.0)
    pub fn to_f64(&self) -> Option<f64> {
        let val: f64 = (self.value).try_into_value()?;
        let max_val: f64 = (Self::max_value()).try_into_value()?;
        Some(val / max_val)
    }
    #[must_use]
    #[allow(clippy::cast_possible_truncation)]
    /// Convert to f32 (0.0 to 1.0)
    pub fn to_f32(&self) -> Option<f32> {
        self.to_f64().and_then(f32::try_from_value)
    }
    #[must_use]
    /// Get the maximum value for the underlying type
    #[allow(arithmetic_overflow)]
    fn max_value() -> T {
        // We need to compute the maximum value for the unsigned type
        // For unsigned types, this is typically 2^n - 1
        let zero = T::ZERO;
        let one = T::ONE;

        // Find the max by bit shifting or using a more direct approach
        // This is a bit tricky generically, so we'll use NumCast with known max values
        // if std::mem::size_of::<T>() == 1 {
        //     NumCast::from(u8::MAX).unwrap()
        // } else if std::mem::size_of::<T>() == 2 {
        //     NumCast::from(u16::MAX).unwrap()
        // } else if std::mem::size_of::<T>() == 4 {
        //     NumCast::from(u32::MAX).unwrap()
        // } else if std::mem::size_of::<T>() == 8 {
        //     NumCast::from(u64::MAX).unwrap()
        // } else if std::mem::size_of::<T>() == 16 {
        //     NumCast::from(u128::MAX).unwrap()
        // } else
        {
            // Fallback: try to compute max value
            let mut max_val = zero;
            let mut temp = one;

            // Simple approach: keep doubling until we wrap around
            loop {
                let next = temp + temp;
                if next < temp {
                    // Overflow detected
                    break;
                }
                temp = next;
            }

            // Now find the exact max by adding smaller increments
            while temp + one >= temp {
                max_val = temp;
                temp = temp + one;
            }

            max_val
        }
    }
    #[must_use]
    /// Saturating addition
    pub fn saturating_add(self, other: Self) -> Self {
        let max_val = Self::max_value();
        let result = if self.value > max_val - other.value {
            max_val
        } else {
            self.value + other.value
        };
        Self::from_raw(result)
    }
    #[must_use]
    /// Saturating subtraction
    pub fn saturating_sub(self, other: Self) -> Self {
        let result = if self.value < other.value {
            T::ZERO
        } else {
            self.value - other.value
        };
        Self::from_raw(result)
    }
}

// Arithmetic operations
impl<T> Add for UniformRange<T>
where
    T: Copy
        + ConstZero
        + ConstOne
        + core::fmt::Debug
        + PartialOrd
        + Add<Output = T>
        + Sub<Output = T>
        + Mul<Output = T>
        + Div<Output = T>
        + TryIntoPatch<f64>,
    f64: TryIntoPatch<T>,
{
    type Output = Self;

    fn add(self, rhs: Self) -> Self::Output {
        self.saturating_add(rhs)
    }
}

impl<T> Sub for UniformRange<T>
where
    T: TryIntoPatch<f64>
        + Copy
        + ConstZero
        + ConstOne
        + PartialOrd
        + core::fmt::Debug
        + Add<Output = T>
        + Sub<Output = T>
        + Mul<Output = T>
        + Div<Output = T>,
    f64: TryIntoPatch<T>,
{
    type Output = Self;

    fn sub(self, rhs: Self) -> Self::Output {
        self.saturating_sub(rhs)
    }
}

// impl<T> Mul for UniformRange<T>
// where
//     T: Unsigned
//         + TryFromPatch<f64>
//         + Copy
//         + Zero
//         + One
//         + PartialOrd
//         + Add<Output = T>
//         + Sub<Output = T>
//         + Mul<Output = T>
//         + Div<Output = T>,
//     f64: TryFromPatch<T>,
//     Self: TryFromPatch<f64>,
// {
//     type Output = Self;

//     fn mul(self, rhs: Self) -> Option<Self::Output> {
//         // Convert to f64, multiply, then convert back
//         let result = self.to_f64() * rhs.to_f64();
//         Self::try_from_value(result)
//     }
// }

// impl<T> Div for UniformRange<T>
// where
//     T: Unsigned
//         + NumCast
//         + Copy
//         + Zero
//         + One
//         + PartialOrd
//         + Add<Output = T>
//         + Sub<Output = T>
//         + Mul<Output = T>
//         + Div<Output = T>,
// {
//     type Output = Self;

//     fn div(self, rhs: Self) -> Self::Output {
//         if rhs.value == T::zero() {
//             return Self::ONE; // Division by zero gives max value (1.0)
//         }

//         // Convert to f64, divide, then convert back
//         let result = self.to_f64() / rhs.to_f64();
//         Self::from_f64(result)
//     }
// }

// // Assignment operations
// impl<T> AddAssign for UniformRange<T>
// where
//     T: Unsigned
//         + NumCast
//         + Copy
//         + Zero
//         + One
//         + PartialOrd
//         + Add<Output = T>
//         + Sub<Output = T>
//         + Mul<Output = T>
//         + Div<Output = T>,
// {
//     fn add_assign(&mut self, rhs: Self) {
//         *self = *self + rhs;
//     }
// }

// impl<T> SubAssign for UniformRange<T>
// where
//     T: Unsigned
//         + NumCast
//         + Copy
//         + Zero
//         + One
//         + PartialOrd
//         + Add<Output = T>
//         + Sub<Output = T>
//         + Mul<Output = T>
//         + Div<Output = T>,
// {
//     fn sub_assign(&mut self, rhs: Self) {
//         *self = *self - rhs;
//     }
// }

// impl<T> MulAssign for UniformRange<T>
// where
//     T: Unsigned
//         + NumCast
//         + Copy
//         + Zero
//         + One
//         + PartialOrd
//         + Add<Output = T>
//         + Sub<Output = T>
//         + Mul<Output = T>
//         + Div<Output = T>,
// {
//     fn mul_assign(&mut self, rhs: Self) {
//         *self = *self * rhs;
//     }
// }

// impl<T> DivAssign for UniformRange<T>
// where
//     T: Unsigned
//         + NumCast
//         + Copy
//         + Zero
//         + One
//         + PartialOrd
//         + Add<Output = T>
//         + Sub<Output = T>
//         + Mul<Output = T>
//         + Div<Output = T>,
// {
//     fn div_assign(&mut self, rhs: Self) {
//         *self = *self / rhs;
//     }
// }

impl<T> core::fmt::Display for UniformRange<T>
where
    T: TryIntoPatch<f64>
        + Copy
        + ConstZero
        + ConstOne
        + PartialOrd
        + core::fmt::Debug
        + Add<Output = T>
        + Sub<Output = T>
        + Mul<Output = T>
        + Div<Output = T>,
    f64: TryIntoPatch<T>,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{:.6?}", self.to_f64())
    }
}

impl<T> core::fmt::Debug for UniformRange<T>
where
    T: TryIntoPatch<f64>
        + Copy
        + ConstZero
        + ConstOne
        + PartialOrd
        + core::fmt::Debug
        + Add<Output = T>
        + Sub<Output = T>
        + Mul<Output = T>
        + Div<Output = T>,
    f64: TryIntoPatch<T>,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "UnitRange(raw: {:?}, value: {:.6?})",
            self.value,
            self.to_f64()
        )
    }
}

/// Unit range with u8 storage - 256 values, lowest precision, smallest memory footprint.
pub type UnitRangeU8 = UniformRange<u8>;

/// Unit range with u16 storage - 65K values, moderate precision, good balance for most uses.
pub type UnitRangeU16 = UniformRange<u16>;

/// Unit range with u32 storage - 4.3B values, high precision for fine-grained control.
pub type UnitRangeU32 = UniformRange<u32>;

/// Unit range with u64 storage - 18.4Q values, maximum precision for scientific computing.
pub type UnitRangeU64 = UniformRange<u64>;

/// Unit range with u128 storage - 340 undecillion values, go ahead.
pub type UnitRangeU128 = UniformRange<u128>;

/// Unit range with usize storage - platform-dependent precision (32-bit or 64-bit).
pub type UnitRangeUsize = UniformRange<usize>;

// #[cfg(test)]
// mod tests {
//     use super::*;

//     #[test]
//     fn test_basic_functionality() {
//         let zero = UnitRangeU8::ZERO;
//         let one = UnitRangeU8::ONE;
//         let half = UnitRangeU8::from_f64(0.5);

//         assert_eq!(zero.to_f64(), 0.0);
//         assert_eq!(one.to_f64(), 1.0);
//         assert!((half.to_f64() - 0.5).abs() < 0.01);
//     }

//     #[test]
//     fn test_arithmetic() {
//         let a = UnitRangeU8::from_f64(0.3);
//         let b = UnitRangeU8::from_f64(0.4);

//         let sum = a + b;
//         let diff = a - b;
//         let product = a * b;
//         let quotient = a / b;

//         assert!((sum.to_f64() - 0.7).abs() < 0.01);
//         assert!(diff.to_f64() < 0.01); // Should be close to 0 due to saturating sub
//         assert!((product.to_f64() - 0.12).abs() < 0.01);
//         assert!((quotient.to_f64() - 0.75).abs() < 0.01);
//     }

//     #[test]
//     fn test_different_types() {
//         let u8_val = UnitRangeU8::from_f64(0.5);
//         let u16_val = UnitRangeU16::from_f64(0.5);
//         let u32_val = UnitRangeU32::from_f64(0.5);

//         // u16 should have more precision than u8
//         assert!(
//             (u16_val.to_f64() - 0.5).abs() <= (u8_val.to_f64() - 0.5).abs()
//         );
//         assert!(
//             (u32_val.to_f64() - 0.5).abs() <= (u16_val.to_f64() - 0.5).abs()
//         );
//     }

//     #[test]
//     fn test_saturation() {
//         let max = UnitRangeU8::ONE;
//         let small = UnitRangeU8::from_f64(0.1);

//         let saturated_add = max + small;
//         let saturated_sub = small - max;

//         assert_eq!(saturated_add.to_f64(), 1.0);
//         assert_eq!(saturated_sub.to_f64(), 0.0);
//     }
// }