Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: port div_ceil from stdlib to avoid unstable features #1191

Merged
merged 2 commits into from
Mar 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion src/common/time/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
#![feature(int_roundings)]
// Copyright 2023 Greptime Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
Expand Down
3 changes: 2 additions & 1 deletion src/common/time/src/timestamp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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))
}
}

Expand Down
17 changes: 17 additions & 0 deletions src/common/time/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -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));
}
}