rhai/tests/float.rs

97 lines
2.3 KiB
Rust
Raw Normal View History

#![cfg(not(feature = "no_float"))]
use rhai::{Engine, EvalAltResult, FLOAT};
2020-03-24 09:57:35 +01:00
const EPSILON: FLOAT = 0.000_000_000_1;
2017-11-03 17:58:51 +01:00
#[test]
fn test_float() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new();
2017-11-03 17:58:51 +01:00
2022-12-30 18:07:39 +01:00
assert!(engine.eval::<bool>("let x = 0.0; let y = 1.0; x < y")?);
assert!(!engine.eval::<bool>("let x = 0.0; let y = 1.0; x > y")?);
assert!(!engine
.eval::<bool>("let x = 0.; let y = 1.; x > y")
.unwrap());
2020-03-24 09:57:35 +01:00
assert!((engine.eval::<FLOAT>("let x = 9.9999; x")? - 9.9999 as FLOAT).abs() < EPSILON);
2020-03-02 15:11:56 +01:00
Ok(())
2017-11-03 17:58:51 +01:00
}
2021-02-11 12:20:30 +01:00
#[test]
fn test_float_scientific() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new();
assert!(engine.eval::<bool>("123.456 == 1.23456e2")?);
assert!(engine.eval::<bool>("123.456 == 1.23456e+2")?);
assert!(engine.eval::<bool>("123.456 == 123456e-3")?);
Ok(())
}
2020-09-23 06:00:03 +02:00
#[test]
fn test_float_parse() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new();
assert!((engine.eval::<FLOAT>(r#"parse_float("9.9999")"#)? - 9.9999 as FLOAT).abs() < EPSILON);
Ok(())
}
2017-11-03 17:58:51 +01:00
#[test]
#[cfg(not(feature = "no_object"))]
2020-05-28 08:08:21 +02:00
fn test_struct_with_float() -> Result<(), Box<EvalAltResult>> {
2017-11-03 17:58:51 +01:00
#[derive(Clone)]
struct TestStruct {
2020-11-01 08:48:48 +01:00
x: FLOAT,
2017-11-03 17:58:51 +01:00
}
impl TestStruct {
fn update(&mut self) {
2020-11-01 08:48:48 +01:00
self.x += 5.789;
2017-11-03 17:58:51 +01:00
}
2020-11-01 08:48:48 +01:00
fn get_x(&mut self) -> FLOAT {
2017-11-03 17:58:51 +01:00
self.x
}
2020-11-01 08:48:48 +01:00
fn set_x(&mut self, new_x: FLOAT) {
2017-11-03 17:58:51 +01:00
self.x = new_x;
}
2020-03-19 06:52:10 +01:00
fn new() -> Self {
2020-10-19 08:26:15 +02:00
Self { x: 1.0 }
2017-11-03 17:58:51 +01:00
}
}
let mut engine = Engine::new();
engine.register_type::<TestStruct>();
engine.register_get_set("x", TestStruct::get_x, TestStruct::set_x);
engine.register_fn("update", TestStruct::update);
engine.register_fn("new_ts", TestStruct::new);
2020-03-24 09:57:35 +01:00
assert!(
(engine.eval::<FLOAT>("let ts = new_ts(); ts.update(); ts.x")? - 6.789).abs() < EPSILON
);
2020-03-24 09:57:35 +01:00
assert!(
(engine.eval::<FLOAT>("let ts = new_ts(); ts.x = 10.1001; ts.x")? - 10.1001).abs()
< EPSILON
);
2020-03-02 15:11:56 +01:00
Ok(())
2017-11-03 17:58:51 +01:00
}
2020-05-28 08:08:21 +02:00
#[test]
fn test_float_func() -> Result<(), Box<EvalAltResult>> {
let mut engine = Engine::new();
engine.register_fn("sum", |x: FLOAT, y: FLOAT, z: FLOAT, w: FLOAT| {
x + y + z + w
});
assert_eq!(engine.eval::<FLOAT>("sum(1.0, 2.0, 3.0, 4.0)")?, 10.0);
Ok(())
}