Skip to content

Instantly share code, notes, and snippets.

@zeen
Created September 10, 2010 01:11
Show Gist options
  • Save zeen/572882 to your computer and use it in GitHub Desktop.
Save zeen/572882 to your computer and use it in GitHub Desktop.
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