Add a ceiling variant, mirroring the existing as_micros_ceil() since the existing as_millis() truncates towards zero.
Unified · Split
| @@ -528,6 +528,32 @@ impl Delta { · 527 unmodified lines | |||
| 528 | } | 528 | } |
| 529 | } | 529 | } |
| 530 | 530 | ||
| 531 | /// Return the smallest number of milliseconds greater than or equal | ||
| 532 | /// to the value in the [`Delta`]. | ||
| 533 | #[inline] | ||
| 534 | pub fn as_millis_ceil(self) -> i64 { | ||
| 535 | // Only positive values need to be rounded up: truncating division already | ||
| 536 | // rounds towards zero, i.e. up, for negative values. | ||
| 537 | // | ||
| 538 | // The usual `(nanos + d - 1) / d` is not used because the addition overflows | ||
| 539 | // once `nanos` exceeds `i64::MAX - (d - 1)`; saturating the addition instead | ||
| 540 | // would drop the rounding bias and return a result one unit too small. | ||
| 541 | let n = self.as_nanos(); | ||
| 542 | |||
| 543 | let (n, add) = if n > 0 { (n - 1, 1) } else { (n, 0) }; | ||
| 544 | |||
| 545 | #[cfg(CONFIG_64BIT)] | ||
| 546 | { | ||
| 547 | n / NSEC_PER_MSEC + add | ||
| 548 | } | ||
| 549 | |||
| 550 | #[cfg(not(CONFIG_64BIT))] | ||
| 551 | // SAFETY: It is always safe to call `ktime_to_ms()` with any value. | ||
| 552 | unsafe { | ||
| 553 | bindings::ktime_to_ms(n) + add | ||
| 554 | } | ||
| 555 | } | ||
| 556 | |||
| 531 | /// Return `self % dividend` where `dividend` is in nanoseconds. | 557 | /// Return `self % dividend` where `dividend` is in nanoseconds. |
| 532 | /// | 558 | /// |
| 533 | /// The kernel doesn't have any emulation for `s64 % s64` on 32 bit platforms, so this is | 559 | /// The kernel doesn't have any emulation for `s64 % s64` on 32 bit platforms, so this is |