Improve leap years counting performance in distance_of_time_in_words #54923
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Motivation / Background
The
distance_of_time_in_words
function can lead to a denial of service if the givenfrom_time
andto_time
arguments are far apart. I replaced the concerning code with a constant calculation.Detail
The
distance_of_time_in_words
function counts the leap years by using a range and thecount
function:This code can lead to a denial of service if
from_year
andto_year
are far apart, as it iterates over a range generated from the difference of the two arguments, effectively blocking execution. I replaced the code with the following, which calculates the leap years in constant time:This particular case may seem irrelevant at first, but I discovered this problem in a project of mine. Users who are able to set a timestamp can easily trigger this problem when the timestamp is passed somewhere to the
distance_of_time_in_words
function.Checklist
Before submitting the PR make sure the following are checked:
[Fix #issue-number]