Skip to content

Warn against subtracting a constant Duration from Instant::now() #9371

@kangalio

Description

@kangalio

What it does

I'm not sure how large the scope of this lint should be, so here's the most conservative approach first:

This lint finds patterns of the form std::time::Instant::now() - std::time::Duration::from_secs(...) (or from_millis, from_secs_f32, whatever) and warns against potential underflow panics on certain platforms. Maybe there should also be a check that the duration exceeds a certain threshold (e.g. subtracting 50 milliseconds will pretty much always work, but 50 seconds not necessarily)

The warning message would say something like This subtraction can panic, depending on OS and system bootup time. Rewrite your code to not require potentially negative Instants, or make the intention to panic explicit with '.checked_sub(...).unwrap()'

The lint could be expanded to lint for all Durations (not just inline-constructed constant Durations), and/or to lint for all Instants (not just Instant::now()). But I'm not sure if the increased false positive rate is worth it

Lint Name

potential-instant-underflow

Category

suspicious

Advantage

There are no hidden potential panics

Drawbacks

If the system is known to have been booted for the specified Duration, this lint is a false positive. Example thread::sleep(Duration::from_secs(60)); Instant::now() - Duration::from_secs(60);

Example

let delete_before = Instant::now() - Duration::from_secs(60 * 60);
self.entries.retain(|entry| entry.timestamp > delete_before);

Could be written as:

let max_age = Duration::from_secs(60 * 60);
self.entries.retain(|entry| Instant::now() - entry.timestamp < max_age);

Metadata

Metadata

Assignees

Labels

A-lintArea: New lintsgood first issueThese issues are a good way to get started with Clippy

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions