Skip to content

Commit

Permalink
use saturating_mult to prevent overflow of tokens_to_add
Browse files Browse the repository at this point in the history
  • Loading branch information
jakewmeyer committed Oct 7, 2023
1 parent c21b335 commit ea67cc9
Showing 1 changed file with 7 additions and 11 deletions.
18 changes: 7 additions & 11 deletions src/token_bucket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,25 +27,21 @@ impl TokenBucket {
}

pub fn take(&mut self) -> bool {
self.update();
if self.available_tokens >= self.take_rate {
self.available_tokens -= self.take_rate;
true
} else {
false
}
}

fn update(&mut self) {
let now = Instant::now();
let elapsed = now.duration_since(self.last_update).as_secs();
let tokens_to_add = (elapsed as u8) * self.fill_rate;
let tokens_to_add = (elapsed as u8).saturating_mul(self.fill_rate);
// Check if we have at least one token to add
// to prevent fractional token tracking
if tokens_to_add >= 1 {
self.available_tokens = (self.available_tokens + tokens_to_add).min(self.capacity);
self.last_update = now;
}
if self.available_tokens >= self.take_rate {
self.available_tokens -= self.take_rate;
true
} else {
false
}
}
}

Expand Down

0 comments on commit ea67cc9

Please sign in to comment.