Mercurial > prosody-hg
comparison util/throttle.lua @ 4362:851885cb332d
util.throttle: Generic module by waqas to limit something over some time
| author | Matthew Wild <mwild1@gmail.com> |
|---|---|
| date | Mon, 29 Aug 2011 13:00:33 -0400 |
| parents | |
| children | 28e0bf9cf0f5 |
comparison
equal
deleted
inserted
replaced
| 4361:605045b77bc6 | 4362:851885cb332d |
|---|---|
| 1 | |
| 2 local gettime = require "socket".gettime; | |
| 3 | |
| 4 module "throttle" | |
| 5 | |
| 6 local throttle = {}; | |
| 7 local throttle_mt = { __index = throttle }; | |
| 8 | |
| 9 function throttle:update() | |
| 10 local newt = gettime(); | |
| 11 local elapsed = newt - self.t; | |
| 12 self.t = newt; | |
| 13 local balance = self.rate * elapsed + self.balance; | |
| 14 if balance > self.max then | |
| 15 self.balance = self.max; | |
| 16 else | |
| 17 self.balance = balance; | |
| 18 end | |
| 19 return self.balance; | |
| 20 end | |
| 21 | |
| 22 function throttle:peek(cost) | |
| 23 cost = cost or 1; | |
| 24 return self.balance >= cost or self:update() >= cost; | |
| 25 end | |
| 26 | |
| 27 function throttle:poll(cost, split) | |
| 28 if self:peek(cost) then | |
| 29 self.balance = self.balance - cost; | |
| 30 return true; | |
| 31 else | |
| 32 local balance = self.balance; | |
| 33 if split then | |
| 34 self.balance = 0; | |
| 35 end | |
| 36 return false, balance, (cost-self.balance); | |
| 37 end | |
| 38 end | |
| 39 | |
| 40 function create(max, period) | |
| 41 return setmetatable({ rate = max / period, max = max, t = 0, balance = max }, throttle_mt); | |
| 42 end | |
| 43 | |
| 44 return _M; |
