From 3a3125d030ee5d4a43d311ae765201c860bab264 Mon Sep 17 00:00:00 2001 From: Finn Bear Date: Wed, 18 Oct 2023 01:53:25 -0700 Subject: [PATCH] Optimize `time::from::nanos` function. (#2811) --- lib/src/fnc/time.rs | 17 +++-------------- 1 file changed, 3 insertions(+), 14 deletions(-) diff --git a/lib/src/fnc/time.rs b/lib/src/fnc/time.rs index 0e8601ac..d0e79f0a 100644 --- a/lib/src/fnc/time.rs +++ b/lib/src/fnc/time.rs @@ -247,21 +247,10 @@ pub mod from { use chrono::{NaiveDateTime, Offset, TimeZone, Utc}; pub fn nanos((val,): (i64,)) -> Result { - // Example unix nanoseconds timestamp: 1_696_537_096_309_565_400ns - // Get seconds part: 1_696_537_096s - // Get nanoseconds part: 309_565_400ns - let s = val.to_string(); + const NANOS_PER_SEC: i64 = 1_000_000_000; - let seconds: i64 = if s.len() > 9 { - s.as_str()[..(s.len() - 9)].parse().unwrap() - } else { - 0 - }; - let nanoseconds: u32 = if s.len() > 9 { - s.as_str()[(s.len() - 9)..].parse().unwrap() - } else { - s.as_str().parse().unwrap() - }; + let seconds = val.div_euclid(NANOS_PER_SEC); + let nanoseconds = val.rem_euclid(NANOS_PER_SEC) as u32; match NaiveDateTime::from_timestamp_opt(seconds, nanoseconds) { Some(v) => match Utc.fix().from_local_datetime(&v).earliest() {