From 93be05b8f92c8d4a5797251cd73b6088cbcb6c2c Mon Sep 17 00:00:00 2001 From: Tatsuya Kawano Date: Wed, 1 Jan 2025 14:55:04 +0800 Subject: [PATCH] Avoid panic in an internal `to_std_instant` method --- src/future/base_cache.rs | 15 ++++++++++++++- src/sync_base/base_cache.rs | 15 ++++++++++++++- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/future/base_cache.rs b/src/future/base_cache.rs index cf94a608..3ad417ab 100644 --- a/src/future/base_cache.rs +++ b/src/future/base_cache.rs @@ -1027,7 +1027,20 @@ impl Clocks { } else { (self.origin, self.origin_std) }; - origin_std + (time.checked_duration_since(origin).unwrap()) + + // `checked_duration_since` should always succeed here because the `origin` + // is set when this `Cache` is created, and the `time` is either the last + // modified or last accessed time of a cached entry. So `time` should always + // be greater than or equal to `origin`. + // + // However, this is not always true when `quanta::Instant` is used as the + // time source? https://github.com/moka-rs/moka/issues/472 + // + // (Or do we set zero Instant to last modified/accessed time somewhere?) + // + // As a workaround, let's use zero duration when `checked_duration_since` + // fails. + origin_std + (time.checked_duration_since(origin).unwrap_or_default()) } #[cfg(test)] diff --git a/src/sync_base/base_cache.rs b/src/sync_base/base_cache.rs index fe951d29..abbab102 100644 --- a/src/sync_base/base_cache.rs +++ b/src/sync_base/base_cache.rs @@ -896,7 +896,20 @@ impl Clocks { } else { (self.origin, self.origin_std) }; - origin_std + (time.checked_duration_since(origin).unwrap()) + + // `checked_duration_since` should always succeed here because the `origin` + // is set when this `Cache` is created, and the `time` is either the last + // modified or last accessed time of a cached entry. So `time` should always + // be greater than or equal to `origin`. + // + // However, this is not always true when `quanta::Instant` is used as the + // time source? https://github.com/moka-rs/moka/issues/472 + // + // (Or do we set zero Instant to last modified/accessed time somewhere?) + // + // As a workaround, let's use zero duration when `checked_duration_since` + // fails. + origin_std + (time.checked_duration_since(origin).unwrap_or_default()) } #[cfg(test)]