mudssky_utils 1.0.0

A comprehensive Rust utility library providing common functionality for everyday programming tasks
Documentation
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
//! Number utility functions similar to JavaScript number methods
//!
//! This module provides utility functions for working with numbers
//! that are commonly available in JavaScript but not natively in Rust.

/// Error type for number operations
#[derive(Debug, Clone, PartialEq)]
pub enum NumberUtilsError {
    /// Invalid number format
    InvalidFormat(String),
    /// Number out of range
    OutOfRange(String),
    /// Division by zero
    DivisionByZero,
}

impl std::fmt::Display for NumberUtilsError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            NumberUtilsError::InvalidFormat(msg) => write!(f, "Invalid format: {msg}"),
            NumberUtilsError::OutOfRange(msg) => write!(f, "Out of range: {msg}"),
            NumberUtilsError::DivisionByZero => write!(f, "Division by zero"),
        }
    }
}

impl std::error::Error for NumberUtilsError {}

/// Check if a number is finite
/// Similar to JavaScript's Number.isFinite()
///
/// # Examples
///
/// ```rust
/// use mudssky_utils::number_utils::is_finite;
///
/// assert!(is_finite(42.0));
/// assert!(is_finite(-42.0));
/// assert!(!is_finite(f64::INFINITY));
/// assert!(!is_finite(f64::NEG_INFINITY));
/// assert!(!is_finite(f64::NAN));
/// ```
pub fn is_finite(n: f64) -> bool {
    n.is_finite()
}

/// Check if a number is NaN
/// Similar to JavaScript's Number.isNaN()
///
/// # Examples
///
/// ```rust
/// use mudssky_utils::number_utils::is_nan;
///
/// assert!(!is_nan(42.0));
/// assert!(!is_nan(f64::INFINITY));
/// assert!(is_nan(f64::NAN));
/// assert!(is_nan(0.0 / 0.0));
/// ```
pub fn is_nan(n: f64) -> bool {
    n.is_nan()
}

/// Check if a number is an integer
/// Similar to JavaScript's Number.isInteger()
///
/// # Examples
///
/// ```rust
/// use mudssky_utils::number_utils::is_integer;
///
/// assert!(is_integer(42.0));
/// assert!(is_integer(-42.0));
/// assert!(is_integer(0.0));
/// assert!(!is_integer(42.5));
/// assert!(!is_integer(f64::NAN));
/// assert!(!is_integer(f64::INFINITY));
/// ```
pub fn is_integer(n: f64) -> bool {
    n.is_finite() && n.fract() == 0.0
}

/// Check if a number is a safe integer
/// Similar to JavaScript's Number.isSafeInteger()
///
/// # Examples
///
/// ```rust
/// use mudssky_utils::number_utils::is_safe_integer;
///
/// assert!(is_safe_integer(42.0));
/// assert!(is_safe_integer(-42.0));
/// assert!(is_safe_integer(9007199254740991.0)); // MAX_SAFE_INTEGER
/// assert!(!is_safe_integer(9007199254740992.0)); // MAX_SAFE_INTEGER + 1
/// assert!(!is_safe_integer(42.5));
/// ```
pub fn is_safe_integer(n: f64) -> bool {
    const MAX_SAFE_INTEGER: f64 = 9007199254740991.0; // 2^53 - 1
    is_integer(n) && n.abs() <= MAX_SAFE_INTEGER
}

/// Parse a string to a float
/// Similar to JavaScript's parseFloat()
///
/// # Examples
///
/// ```rust
/// use mudssky_utils::number_utils::parse_float;
///
/// assert_eq!(parse_float("42.5"), Ok(42.5));
/// assert_eq!(parse_float("42"), Ok(42.0));
/// assert_eq!(parse_float("42.5abc"), Ok(42.5));
/// assert!(parse_float("abc").is_err());
/// ```
pub fn parse_float(s: &str) -> Result<f64, NumberUtilsError> {
    let trimmed = s.trim();
    if trimmed.is_empty() {
        return Err(NumberUtilsError::InvalidFormat("Empty string".to_string()));
    }

    // Find the longest valid number prefix
    let mut end_idx = 0;
    let mut has_dot = false;
    let mut has_e = false;
    let chars: Vec<char> = trimmed.chars().collect();

    // Handle optional sign
    if !chars.is_empty() && (chars[0] == '+' || chars[0] == '-') {
        end_idx = 1;
    }

    while end_idx < chars.len() {
        let ch = chars[end_idx];
        match ch {
            '0'..='9' => end_idx += 1,
            '.' if !has_dot && !has_e => {
                has_dot = true;
                end_idx += 1;
            }
            'e' | 'E' if !has_e && end_idx > 0 => {
                has_e = true;
                end_idx += 1;
                // Handle optional sign after e/E
                if end_idx < chars.len() && (chars[end_idx] == '+' || chars[end_idx] == '-') {
                    end_idx += 1;
                }
            }
            _ => break,
        }
    }

    if end_idx == 0 || (end_idx == 1 && (chars[0] == '+' || chars[0] == '-')) {
        return Err(NumberUtilsError::InvalidFormat(
            "No valid number found".to_string(),
        ));
    }

    let number_str: String = chars[0..end_idx].iter().collect();
    number_str
        .parse::<f64>()
        .map_err(|_| NumberUtilsError::InvalidFormat(format!("Cannot parse: {number_str}")))
}

/// Parse a string to an integer with specified radix
/// Similar to JavaScript's parseInt()
///
/// # Examples
///
/// ```rust
/// use mudssky_utils::number_utils::parse_int;
///
/// assert_eq!(parse_int("42", 10), Ok(42));
/// assert_eq!(parse_int("101", 2), Ok(5));
/// assert_eq!(parse_int("ff", 16), Ok(255));
/// assert_eq!(parse_int("42abc", 10), Ok(42));
/// assert!(parse_int("abc", 10).is_err());
/// ```
pub fn parse_int(s: &str, radix: u32) -> Result<i64, NumberUtilsError> {
    if !(2..=36).contains(&radix) {
        return Err(NumberUtilsError::InvalidFormat(
            "Radix must be between 2 and 36".to_string(),
        ));
    }

    let trimmed = s.trim();
    if trimmed.is_empty() {
        return Err(NumberUtilsError::InvalidFormat("Empty string".to_string()));
    }

    let chars: Vec<char> = trimmed.chars().collect();
    let mut start_idx = 0;
    let mut is_negative = false;

    // Handle optional sign
    if !chars.is_empty() {
        match chars[0] {
            '-' => {
                is_negative = true;
                start_idx = 1;
            }
            '+' => start_idx = 1,
            _ => {}
        }
    }

    // Find the longest valid number prefix
    let mut end_idx = start_idx;
    while end_idx < chars.len() {
        let ch = chars[end_idx];
        let digit_value = match ch {
            '0'..='9' => (ch as u32) - ('0' as u32),
            'a'..='z' => (ch as u32) - ('a' as u32) + 10,
            'A'..='Z' => (ch as u32) - ('A' as u32) + 10,
            _ => break,
        };

        if digit_value >= radix {
            break;
        }
        end_idx += 1;
    }

    if end_idx == start_idx {
        return Err(NumberUtilsError::InvalidFormat(
            "No valid digits found".to_string(),
        ));
    }

    let number_str: String = chars[start_idx..end_idx].iter().collect();
    let result = i64::from_str_radix(&number_str, radix)
        .map_err(|_| NumberUtilsError::InvalidFormat(format!("Cannot parse: {number_str}")))?;

    Ok(if is_negative { -result } else { result })
}

/// Convert number to fixed decimal places
/// Similar to JavaScript's Number.prototype.toFixed()
///
/// # Examples
///
/// ```rust
/// use mudssky_utils::number_utils::to_fixed;
///
/// assert_eq!(to_fixed(42.12345, 2), "42.12");
/// assert_eq!(to_fixed(42.0, 2), "42.00");
/// assert_eq!(to_fixed(42.999, 2), "43.00");
/// ```
pub fn to_fixed(n: f64, digits: usize) -> String {
    if digits > 100 {
        return format!("{n:.100}");
    }
    format!("{n:.digits$}")
}

/// Convert number to exponential notation
/// Similar to JavaScript's Number.prototype.toExponential()
///
/// # Examples
///
/// ```rust
/// use mudssky_utils::number_utils::to_exponential;
///
/// assert_eq!(to_exponential(42.0, Some(2)), "4.20e1");
/// assert_eq!(to_exponential(0.00042, Some(2)), "4.20e-4");
/// ```
pub fn to_exponential(n: f64, fraction_digits: Option<usize>) -> String {
    match fraction_digits {
        Some(digits) => {
            let digits = digits.min(100);
            format!("{n:.digits$e}")
        }
        None => format!("{n:e}"),
    }
}

/// Convert number to precision notation
/// Similar to JavaScript's Number.prototype.toPrecision()
///
/// # Examples
///
/// ```rust
/// use mudssky_utils::number_utils::to_precision;
///
/// assert_eq!(to_precision(42.12345, Some(4)), "42.12");
/// assert_eq!(to_precision(0.00042, Some(2)), "4.2e-4");
/// ```
pub fn to_precision(n: f64, precision: Option<usize>) -> String {
    match precision {
        Some(p) if p > 0 => {
            let p = p.min(100);
            if n == 0.0 {
                return "0".repeat(p);
            }

            let abs_n = n.abs();
            let log10 = abs_n.log10().floor() as i32;

            if log10 >= 0 && log10 < p as i32 {
                // Use fixed notation
                let decimal_places = (p as i32 - log10 - 1).max(0) as usize;
                format!("{n:.decimal_places$}")
                    .trim_end_matches('0')
                    .trim_end_matches('.')
                    .to_string()
            } else {
                // Use exponential notation
                format!("{n:.precision$e}", precision = p - 1)
            }
        }
        _ => n.to_string(),
    }
}

/// Get the maximum safe integer value
/// Similar to JavaScript's Number.MAX_SAFE_INTEGER
///
/// # Examples
///
/// ```rust
/// use mudssky_utils::number_utils::max_safe_integer;
///
/// assert_eq!(max_safe_integer(), 9007199254740991.0);
/// ```
pub fn max_safe_integer() -> f64 {
    9007199254740991.0 // 2^53 - 1
}

/// Get the minimum safe integer value
/// Similar to JavaScript's Number.MIN_SAFE_INTEGER
///
/// # Examples
///
/// ```rust
/// use mudssky_utils::number_utils::min_safe_integer;
///
/// assert_eq!(min_safe_integer(), -9007199254740991.0);
/// ```
pub fn min_safe_integer() -> f64 {
    -9007199254740991.0 // -(2^53 - 1)
}

/// Get positive infinity
/// Similar to JavaScript's Number.POSITIVE_INFINITY
///
/// # Examples
///
/// ```rust
/// use mudssky_utils::number_utils::positive_infinity;
///
/// assert_eq!(positive_infinity(), f64::INFINITY);
/// ```
pub fn positive_infinity() -> f64 {
    f64::INFINITY
}

/// Get negative infinity
/// Similar to JavaScript's Number.NEGATIVE_INFINITY
///
/// # Examples
///
/// ```rust
/// use mudssky_utils::number_utils::negative_infinity;
///
/// assert_eq!(negative_infinity(), f64::NEG_INFINITY);
/// ```
pub fn negative_infinity() -> f64 {
    f64::NEG_INFINITY
}

/// Clamp a number between min and max values
/// Similar to CSS clamp() function
///
/// # Examples
///
/// ```rust
/// use mudssky_utils::number_utils::clamp;
///
/// assert_eq!(clamp(5.0, 1.0, 10.0), 5.0);
/// assert_eq!(clamp(0.0, 1.0, 10.0), 1.0);
/// assert_eq!(clamp(15.0, 1.0, 10.0), 10.0);
/// ```
pub fn clamp(value: f64, min: f64, max: f64) -> f64 {
    if value < min {
        min
    } else if value > max {
        max
    } else {
        value
    }
}

/// Linear interpolation between two values
/// Common in animations and graphics
///
/// # Examples
///
/// ```rust
/// use mudssky_utils::number_utils::lerp;
///
/// assert_eq!(lerp(0.0, 10.0, 0.5), 5.0);
/// assert_eq!(lerp(0.0, 10.0, 0.0), 0.0);
/// assert_eq!(lerp(0.0, 10.0, 1.0), 10.0);
/// ```
pub fn lerp(start: f64, end: f64, t: f64) -> f64 {
    start + (end - start) * t
}

/// Map a value from one range to another
/// Common in data visualization and scaling
///
/// # Examples
///
/// ```rust
/// use mudssky_utils::number_utils::map_range;
///
/// assert_eq!(map_range(5.0, 0.0, 10.0, 0.0, 100.0), 50.0);
/// assert_eq!(map_range(0.0, 0.0, 10.0, 0.0, 100.0), 0.0);
/// assert_eq!(map_range(10.0, 0.0, 10.0, 0.0, 100.0), 100.0);
/// ```
pub fn map_range(value: f64, in_min: f64, in_max: f64, out_min: f64, out_max: f64) -> f64 {
    (value - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
}