Skip to main content

ts_native_math/
lib.rs

1use std::os::raw::{c_double, c_char, c_ulong};
2use std::ffi::CStr;
3
4#[no_mangle]
5pub extern "C" fn js_math_sin(x: c_double) -> c_double {
6    x.sin()
7}
8
9#[no_mangle]
10pub extern "C" fn js_math_cos(x: c_double) -> c_double {
11    x.cos()
12}
13
14#[no_mangle]
15pub extern "C" fn js_math_tan(x: c_double) -> c_double {
16    x.tan()
17}
18
19#[no_mangle]
20pub extern "C" fn js_math_sqrt(x: c_double) -> c_double {
21    if x < 0.0 { 0.0 } else { x.sqrt() }
22}
23
24#[no_mangle]
25pub extern "C" fn js_math_pow(base: c_double, exp: c_double) -> c_double {
26    base.powf(exp)
27}
28
29#[no_mangle]
30pub extern "C" fn js_math_abs(x: c_double) -> c_double {
31    x.abs()
32}
33
34#[no_mangle]
35pub extern "C" fn js_math_floor(x: c_double) -> c_double {
36    x.floor()
37}
38
39#[no_mangle]
40pub extern "C" fn js_math_ceil(x: c_double) -> c_double {
41    x.ceil()
42}
43
44#[no_mangle]
45pub extern "C" fn js_math_round(x: c_double) -> c_double {
46    x.round()
47}
48
49#[no_mangle]
50pub extern "C" fn js_math_min(a: c_double, b: c_double) -> c_double {
51    a.min(b)
52}
53
54#[no_mangle]
55pub extern "C" fn js_math_max(a: c_double, b: c_double) -> c_double {
56    a.max(b)
57}
58
59#[no_mangle]
60pub extern "C" fn js_parse_int(str_ptr: *const c_char) -> c_double {
61    if str_ptr.is_null() {
62        return 0.0;
63    }
64    let c_str = unsafe { CStr::from_ptr(str_ptr) };
65    if let Ok(s) = c_str.to_str() {
66        s.trim().parse::<i64>().unwrap_or(0) as c_double
67    } else {
68        0.0
69    }
70}
71
72#[no_mangle]
73pub extern "C" fn js_parse_float(str_ptr: *const c_char) -> c_double {
74    if str_ptr.is_null() {
75        return 0.0;
76    }
77    let c_str = unsafe { CStr::from_ptr(str_ptr) };
78    if let Ok(s) = c_str.to_str() {
79        s.trim().parse::<f64>().unwrap_or(0.0)
80    } else {
81        0.0
82    }
83}
84
85#[no_mangle]
86pub extern "C" fn js_console_log(value: c_ulong) {
87    println!("[log] {:?}", value);
88}
89
90#[no_mangle]
91pub extern "C" fn js_console_error(value: c_ulong) {
92    eprintln!("[error] {:?}", value);
93}