Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

rate: fix truncated seconds in tokensFromDuration #8

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions rate/rate.go
Original file line number Diff line number Diff line change
Expand Up @@ -380,8 +380,8 @@ func (lim *Limiter) advance(now time.Time) (newNow time.Time, newLast time.Time,
// durationFromTokens is a unit conversion function from the number of tokens to the duration
// of time it takes to accumulate them at a rate of limit tokens per second.
func (limit Limit) durationFromTokens(tokens float64) time.Duration {
seconds := tokens / float64(limit)
return time.Nanosecond * time.Duration(1e9*seconds)
nanosecond := (1e9 * tokens) / float64(limit)
return time.Nanosecond * time.Duration(nanosecond)
}

// tokensFromDuration is a unit conversion function from a time duration to the number of tokens
Expand Down
6 changes: 6 additions & 0 deletions rate/rate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -445,6 +445,12 @@ func TestWaitInf(t *testing.T) {
runWait(t, lim, wait{"exceed-burst-no-error", context.Background(), 3, 0, true})
}

func TestIssue34861(t *testing.T) {
if !NewLimiter(Limit(0.7692307692307693), 1).Allow() {
t.Error("expect true, got false")
}
}

func BenchmarkAllowN(b *testing.B) {
lim := NewLimiter(Every(1*time.Second), 1)
now := time.Now()
Expand Down