Created
September 10, 2010 01:11
-
-
Save zeen/572882 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local gettime = require "socket".gettime; | |
module "shaper" | |
local shaper = {}; | |
function shaper:update() | |
local newt = gettime(); | |
local elapsed = newt - self.t; | |
self.t = newt; | |
local balance = self.rate * elapsed + self.balance; | |
if balance > self.max then | |
self.balance = self.max; | |
else | |
self.balance = balance; | |
end | |
return self.balance; | |
end | |
function shaper:peek(cost) | |
cost = cost or 1; | |
return shaper.balance >= cost or shaper:update() >= cost; | |
end | |
function shaper:poll(cost) | |
if shaper:peek(cost) then | |
self.balance = self.balance - cost; | |
return true; | |
else | |
return false; | |
end | |
end | |
function create(max, period) | |
return setmetatable({ rate = max / period, max = max, t = 0, balance = max }, shaper); | |
end | |
return _M; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment