windjammer_runtime/
math.rs

1//! Mathematical functions
2//!
3//! Windjammer's `std::math` module maps to these functions.
4
5/// Absolute value
6pub fn abs_i64(x: i64) -> i64 {
7    x.abs()
8}
9
10pub fn abs_f64(x: f64) -> f64 {
11    x.abs()
12}
13
14/// Power
15pub fn pow_f64(base: f64, exp: f64) -> f64 {
16    base.powf(exp)
17}
18
19pub fn pow_i32(base: i32, exp: u32) -> i32 {
20    base.pow(exp)
21}
22
23/// Square root
24pub fn sqrt(x: f64) -> f64 {
25    x.sqrt()
26}
27
28/// Ceiling
29pub fn ceil(x: f64) -> f64 {
30    x.ceil()
31}
32
33/// Floor
34pub fn floor(x: f64) -> f64 {
35    x.floor()
36}
37
38/// Round
39pub fn round(x: f64) -> f64 {
40    x.round()
41}
42
43/// Minimum
44pub fn min_i64(a: i64, b: i64) -> i64 {
45    a.min(b)
46}
47
48pub fn min_f64(a: f64, b: f64) -> f64 {
49    a.min(b)
50}
51
52/// Maximum
53pub fn max_i64(a: i64, b: i64) -> i64 {
54    a.max(b)
55}
56
57pub fn max_f64(a: f64, b: f64) -> f64 {
58    a.max(b)
59}
60
61/// Trigonometric functions
62pub fn sin(x: f64) -> f64 {
63    x.sin()
64}
65
66pub fn cos(x: f64) -> f64 {
67    x.cos()
68}
69
70pub fn tan(x: f64) -> f64 {
71    x.tan()
72}
73
74/// Constants
75pub const PI: f64 = std::f64::consts::PI;
76pub const E: f64 = std::f64::consts::E;
77
78#[cfg(test)]
79mod tests {
80    use super::*;
81
82    #[test]
83    fn test_abs() {
84        assert_eq!(abs_i64(-5), 5);
85        assert_eq!(abs_f64(-2.5), 2.5);
86    }
87
88    #[test]
89    fn test_sqrt() {
90        assert_eq!(sqrt(4.0), 2.0);
91        assert_eq!(sqrt(9.0), 3.0);
92    }
93
94    #[test]
95    fn test_round() {
96        assert_eq!(round(3.7), 4.0);
97        assert_eq!(round(3.2), 3.0);
98    }
99
100    #[test]
101    fn test_min_max() {
102        assert_eq!(min_i64(5, 10), 5);
103        assert_eq!(max_i64(5, 10), 10);
104    }
105}