From ef026930aa8a5b06b67b4784b293c70f3b527d0d Mon Sep 17 00:00:00 2001 From: bohdanstorozhuk Date: Sat, 2 Jul 2022 20:50:59 +0100 Subject: [PATCH] Fix no slack option for int64 based option --- limiter_atomic_int64.go | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/limiter_atomic_int64.go b/limiter_atomic_int64.go index 6588cd0..38604ba 100644 --- a/limiter_atomic_int64.go +++ b/limiter_atomic_int64.go @@ -66,10 +66,10 @@ func (t *atomicInt64Limiter) Take() time.Time { timeOfNextPermissionIssue := atomic.LoadInt64(&t.state) switch { - case timeOfNextPermissionIssue == 0: - // If this is our first request, then we allow it. + case timeOfNextPermissionIssue == 0 || (t.maxSlack == 0 && now-timeOfNextPermissionIssue > int64(t.perRequest)): + // if this is our first call or t.maxSlack == 0 we need to shrink issue time to now newTimeOfNextPermissionIssue = now - case now-timeOfNextPermissionIssue > int64(t.maxSlack): + case t.maxSlack > 0 && now-timeOfNextPermissionIssue > int64(t.maxSlack): // a lot of nanoseconds passed since the last Take call // we will limit max accumulated time to maxSlack newTimeOfNextPermissionIssue = now - int64(t.maxSlack) @@ -82,9 +82,6 @@ func (t *atomicInt64Limiter) Take() time.Time { break } } - nanosToSleepUntilOurPermissionIsIssued := newTimeOfNextPermissionIssue - now - if nanosToSleepUntilOurPermissionIsIssued > 0 { - t.clock.Sleep(time.Duration(nanosToSleepUntilOurPermissionIsIssued)) - } + t.clock.Sleep(time.Duration(newTimeOfNextPermissionIssue - now)) return time.Unix(0, newTimeOfNextPermissionIssue) }