Trap elapsed error when timestamp is later than now.

This commit is contained in:
Stephen Chung 2020-10-09 12:51:26 +08:00
parent 7ede299aae
commit a4b674d015
2 changed files with 9 additions and 3 deletions

View File

@ -16,8 +16,8 @@ use num_traits::float::Float;
use crate::stdlib::{format, string::String}; use crate::stdlib::{format, string::String};
#[inline(always)] #[inline(always)]
pub fn make_err(msg: String) -> Box<EvalAltResult> { pub fn make_err(msg: impl Into<String>) -> Box<EvalAltResult> {
EvalAltResult::ErrorArithmetic(msg, Position::none()).into() EvalAltResult::ErrorArithmetic(msg.into(), Position::none()).into()
} }
macro_rules! gen_arithmetic_functions { macro_rules! gen_arithmetic_functions {

View File

@ -34,7 +34,11 @@ mod time_functions {
pub fn elapsed(timestamp: &mut Instant) -> Result<Dynamic, Box<EvalAltResult>> { pub fn elapsed(timestamp: &mut Instant) -> Result<Dynamic, Box<EvalAltResult>> {
#[cfg(not(feature = "no_float"))] #[cfg(not(feature = "no_float"))]
{ {
Ok((timestamp.elapsed().as_secs_f64() as FLOAT).into()) if *timestamp <= Instant::now() {
Ok((timestamp.elapsed().as_secs_f64() as FLOAT).into())
} else {
Err(make_arithmetic_err("Time-stamp is later than now"))
}
} }
#[cfg(feature = "no_float")] #[cfg(feature = "no_float")]
@ -46,6 +50,8 @@ mod time_functions {
"Integer overflow for timestamp.elapsed: {}", "Integer overflow for timestamp.elapsed: {}",
seconds seconds
))) )))
} else if *timestamp <= Instant::now() {
Err(make_arithmetic_err("Time-stamp is later than now"))
} else { } else {
Ok((seconds as INT).into()) Ok((seconds as INT).into())
} }