summaryrefslogtreecommitdiff
path: root/go/src/lib/statusline/ratelimit.go
blob: 970f8e53924bf0173df9395641330762d3c520fe (plain)
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
package statusline

import (
	"time"
)

type rateLimiter struct {
	lines chan string
	end1  chan bool
	end2  chan struct{}
}

func RateLimit(sl StatusLine, d time.Duration) StatusLine {
	ret := &rateLimiter{
		lines: make(chan string),
		end1:  make(chan bool),
		end2:  make(chan struct{}),
	}
	go func() {
		ticker := time.NewTicker(d)
		var oldLine string
		var newLine string
		dirty := false
		for {
			select {
			case <-ticker.C:
				if dirty && newLine != oldLine {
					sl.Put(newLine)
				}
				dirty = false
			case line := <-ret.lines:
				newLine = line
				dirty = true
			case keep := <-ret.end1:
				if keep && dirty && newLine != oldLine {
					sl.Put(newLine)
				}
				sl.End(keep)
				ticker.Stop()
				ret.end2 <- struct{}{}
				close(ret.end2)
				return
			}
		}
	}()
	return ret
}

func (sl *rateLimiter) Put(line string) {
	sl.lines <- line
}

func (sl *rateLimiter) End(keep bool) {
	sl.end1 <- keep
	close(sl.lines)
	close(sl.end1)
	<-sl.end2
}