util.throttle: Fix 'outstanding' return value
[prosody.git] / util / throttle.lua
1
2 local gettime = require "socket".gettime;
3 local setmetatable = setmetatable;
4
5 module "throttle"
6
7 local throttle = {};
8 local throttle_mt = { __index = throttle };
9
10 function throttle:update()
11         local newt = gettime();
12         local elapsed = newt - self.t;
13         self.t = newt;
14         local balance = self.rate * elapsed + self.balance;
15         if balance > self.max then
16                 self.balance = self.max;
17         else
18                 self.balance = balance;
19         end
20         return self.balance;
21 end
22
23 function throttle:peek(cost)
24         cost = cost or 1;
25         return self.balance >= cost or self:update() >= cost;
26 end
27
28 function throttle:poll(cost, split)
29         if self:peek(cost) then
30                 self.balance = self.balance - cost;
31                 return true;
32         else
33                 local balance = self.balance;
34                 if split then
35                         self.balance = 0;
36                 end
37                 return false, balance, (cost-balance);
38         end
39 end
40
41 function create(max, period)
42         return setmetatable({ rate = max / period, max = max, t = 0, balance = max }, throttle_mt);
43 end
44
45 return _M;