Skip to content

Commit

Permalink
refactor: port div_ceil from rust stdlib
Browse files Browse the repository at this point in the history
  • Loading branch information
sunng87 committed Mar 16, 2023
1 parent 998e5e6 commit 8f80ea7
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
4 changes: 2 additions & 2 deletions 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,8 +144,7 @@ impl Timestamp {
Some(Timestamp::new(value, unit))
} else {
let mul = unit.factor() / self.unit().factor();
let new_ts = self.value as f64 / mul as f64;
Some(Timestamp::new(new_ts.ceil() as i64, unit))
Some(Timestamp::new(div_ceil(self.value, mul as i64), unit))
}
}

Expand Down
11 changes: 11 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 Down

0 comments on commit 8f80ea7

Please sign in to comment.