Dart token bucket rate limiter
Dart
import 'dart:async';
class TokenBucket {
TokenBucket(this.capacity, this.perSecond)
: _tokens = capacity.toDouble(),
_last = DateTime.now();
final int capacity;
final double perSecond;
double _tokens;
DateTime _last;
bool tryAcquire([int cost = 1]) {
final now = DateTime.now();
final elapsed = now.difference(_last).inMicroseconds / 1e6;
final refilled = _tokens + elapsed * perSecond;
_tokens = refilled < capacity ? refilled : capacity.toDouble();
_last = now;
if (_tokens < cost) return false;
_tokens -= cost;
return true;
}
}