File: timer.go

package info (click to toggle)
golang-github-jmhodges-clock 1.0-3~bpo8%2B1
  • links: PTS, VCS
  • area: main
  • in suites: jessie-backports
  • size: 92 kB
  • sloc: makefile: 2
file content (66 lines) | stat: -rw-r--r-- 1,382 bytes parent folder | download | duplicates (4)
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
package clock

import "time"

type Timer struct {
	C <-chan time.Time

	timer     *time.Timer
	fakeTimer *fakeTimer
}

func (t *Timer) Reset(d time.Duration) bool {
	if t.timer != nil {
		return t.timer.Reset(d)
	}
	return t.fakeTimer.Reset(d)
}

func (t *Timer) Stop() bool {
	if t.timer != nil {
		return t.timer.Stop()
	}
	return t.fakeTimer.Stop()
}

type fakeTimer struct {
	// c is the same chan as C in the Timer that contains this fakeTimer
	c chan<- time.Time
	// clk is kept so we can maintain just one lock and to add and attempt to
	// send the times made by this timer during Resets and Stops
	clk *fake
	// active is true until the fakeTimer's send is attempted or it has been
	// stopped
	active bool
	// sends is where we store all the sends made by this timer so we can
	// deactivate the old ones when Reset or Stop is called.
	sends []*send
}

func (ft *fakeTimer) Reset(d time.Duration) bool {
	ft.clk.Lock()
	defer ft.clk.Unlock()
	target := ft.clk.t.Add(d)
	active := ft.active
	ft.active = true
	for _, s := range ft.sends {
		s.active = false
	}
	s := ft.clk.addSend(target, ft)
	ft.sends = []*send{s}
	ft.clk.sendTimes()
	return active
}

func (ft *fakeTimer) Stop() bool {
	ft.clk.Lock()
	defer ft.clk.Unlock()
	active := ft.active
	ft.active = false
	for _, s := range ft.sends {
		s.active = false
	}
	ft.sends = nil
	ft.clk.sendTimes()
	return active
}