-
Notifications
You must be signed in to change notification settings - Fork 1
/
trickle.lua
101 lines (84 loc) · 1.92 KB
/
trickle.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
-- -*-lua-*-
--
-- $Id: trickle.lua $
--
-- Author: Markus Stenberg <[email protected]>
--
-- Created: Mon Sep 17 13:12:19 2012 mstenber
-- Last modified: Wed Sep 19 14:33:36 2012 mstenber
-- Edit time: 23 min
--
-- Trickle implementation - just done as a test of getting Lua code working
-- Assumed parameters during new (at least): imin, imax, k, env
-- env should have:
-- send() method for env to send it's state
-- time()
-- env should call
-- run() periodically (at least as often as next() wants)
-- got_consistent() when receiving something consistent
-- got_inconsistent() when receiving something inconsistent
local math = math
local setmetatable = setmetatable
local assert = assert
module(...)
Trickle = { }
Trickle.__index = Trickle
function Trickle:new(o)
o = o or {}
setmetatable(o, self)
o:start()
return o
end
-- alg:1
function Trickle:start()
-- check parameters were really provided
assert(self.imin, "imin missing")
assert(self.imax, "imax missing")
assert(self.k, "k missing")
assert(self.env, "env missing")
self.i = self.imin
self.c = 0
-- alg:2
self:_reset_timer()
end
function Trickle:_reset_timer()
self.t = self.i * (1 + math.random()) / 2
self.st = self.env:time()
self.sent = false
end
function Trickle:run()
local nt = self.env:time() - self.st
-- alg:4
if nt >= self.t and not self.sent
then
self.sent = true
self.env:send()
end
-- alg:5
if nt >= self.i
then
self.i = self.i * 2
if self.i >= self.imax
then
self.i = self.imax
end
self:_reset_timer()
end
end
function Trickle:next()
local nt = self.env:time() - self.st
local td = nt - self.t
return td
end
-- alg:3
function Trickle:got_consistent()
self.c = self.c + 1
end
-- alg:6
function Trickle:got_inconsistent()
if self.i > self.imin
then
self.i = self.imin
self:_reset_timer()
end
end