From a7676d88608ea6e3c8338e636821d1fae194ed5b Mon Sep 17 00:00:00 2001 From: Ning Sun Date: Thu, 16 Mar 2023 22:55:35 +0800 Subject: [PATCH] refactor: port div_ceil from stdlib to avoid unstable features (#1191) * refactor: use float div&ceil to avoid unstable features * refactor: port div_ceil from rust stdlib --- src/common/time/src/lib.rs | 1 - src/common/time/src/timestamp.rs | 3 ++- src/common/time/src/util.rs | 17 +++++++++++++++++ 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/common/time/src/lib.rs b/src/common/time/src/lib.rs index b71f7a880e43..fdc9033bed98 100644 --- a/src/common/time/src/lib.rs +++ b/src/common/time/src/lib.rs @@ -1,4 +1,3 @@ -#![feature(int_roundings)] // Copyright 2023 Greptime Team // // Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/src/common/time/src/timestamp.rs b/src/common/time/src/timestamp.rs index 6eaf1f0e3270..61dc826ba6cb 100644 --- a/src/common/time/src/timestamp.rs +++ b/src/common/time/src/timestamp.rs @@ -26,6 +26,7 @@ use snafu::{OptionExt, ResultExt}; use crate::error; use crate::error::{ArithmeticOverflowSnafu, Error, ParseTimestampSnafu, TimestampOverflowSnafu}; +use crate::util::div_ceil; #[derive(Debug, Clone, Default, Copy, Serialize, Deserialize)] pub struct Timestamp { @@ -143,7 +144,7 @@ impl Timestamp { Some(Timestamp::new(value, unit)) } else { let mul = unit.factor() / self.unit().factor(); - Some(Timestamp::new(self.value.div_ceil(mul as i64), unit)) + Some(Timestamp::new(div_ceil(self.value, mul as i64), unit)) } } diff --git a/src/common/time/src/util.rs b/src/common/time/src/util.rs index 95bc6a2a64ad..3f52166c98a2 100644 --- a/src/common/time/src/util.rs +++ b/src/common/time/src/util.rs @@ -17,6 +17,17 @@ pub fn current_time_millis() -> i64 { chrono::Utc::now().timestamp_millis() } +/// Port of rust unstable features `int_roundings`. +pub(crate) fn div_ceil(this: i64, rhs: i64) -> i64 { + let d = this / rhs; + let r = this % rhs; + if r > 0 && rhs > 0 { + d + 1 + } else { + d + } +} + #[cfg(test)] mod tests { use std::time::{self, SystemTime}; @@ -42,4 +53,10 @@ mod tests { assert_eq!(datetime_std.hour(), datetime_now.hour()); assert_eq!(datetime_std.minute(), datetime_now.minute()); } + + #[test] + fn test_div_ceil() { + let v0 = 9223372036854676001; + assert_eq!(9223372036854677, div_ceil(v0, 1000)); + } }