From 754da53f3fb42c1b41b1aee4d682040a308b1db8 Mon Sep 17 00:00:00 2001 From: unexge Date: Sun, 31 Dec 2023 12:26:03 +0000 Subject: [PATCH] Add `ensure_i32` util --- src/builtins/time.rs | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/src/builtins/time.rs b/src/builtins/time.rs index fc787e32..1e8710f5 100644 --- a/src/builtins/time.rs +++ b/src/builtins/time.rs @@ -33,18 +33,9 @@ fn add_date(span: &Span, params: &[Ref], args: &[Value], strict: bool) -> ensure_args_count(span, name, params, args, 4)?; let (datetime, _) = parse_epoch(name, ¶ms[0], &args[0])?; - let years: i32 = ensure_numeric(name, ¶ms[1], &args[1])? - .as_i64() - .and_then(|n| n.try_into().ok()) - .ok_or_else(|| span.error("could not convert `years` to int32"))?; - let months: i32 = ensure_numeric(name, ¶ms[2], &args[2])? - .as_i64() - .and_then(|n| n.try_into().ok()) - .ok_or_else(|| span.error("could not convert `months` to int32"))?; - let days: i32 = ensure_numeric(name, ¶ms[3], &args[3])? - .as_i64() - .and_then(|n| n.try_into().ok()) - .ok_or_else(|| span.error("could not convert `days` to int32"))?; + let years = ensure_i32(name, ¶ms[1], &args[1])?; + let months = ensure_i32(name, ¶ms[2], &args[2])?; + let days = ensure_i32(name, ¶ms[3], &args[3])?; let Some(new_year) = datetime.year().checked_add(years) else { return Ok(Value::Undefined); @@ -231,6 +222,13 @@ fn weekday(span: &Span, params: &[Ref], args: &[Value], _strict: bool) -> Ok(Value::String(weekday.into())) } +fn ensure_i32(name: &str, arg: &Expr, v: &Value) -> Result { + ensure_numeric(name, arg, v)? + .as_i64() + .and_then(|n| n.try_into().ok()) + .ok_or_else(|| arg.span().error("could not convert to int32")) +} + fn safe_timestamp_nanos(span: &Span, strict: bool, nanos: Option) -> Result { match nanos { Some(ns) => Ok(Value::Number(ns.into())),