summaryrefslogtreecommitdiff
path: root/go/src/lib/statusline/ratelimit.go
blob: 087466de948097c259baaa2881ad41f9c0b670b8 (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
59
60
61
62
63
64
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
		first := true
		for {
			select {
			case <-ticker.C:
				if newLine != oldLine {
					sl.Put(newLine)
					oldLine = newLine
				}
			case line := <-ret.lines:
				if first {
					first = false
					oldLine = line
					newLine = line
					sl.Put(line)
				} else {
					newLine = line
				}
			case keep := <-ret.end1:
				if 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
}