File: timer.go

package info (click to toggle)
golang-github-lucas-clemente-quic-go 0.54.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 4,312 kB
  • sloc: sh: 54; makefile: 7
file content (57 lines) | stat: -rw-r--r-- 1,158 bytes parent folder | download | duplicates (3)
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
package utils

import (
	"math"
	"time"
)

// A Timer wrapper that behaves correctly when resetting
type Timer struct {
	t        *time.Timer
	read     bool
	deadline time.Time
}

// NewTimer creates a new timer that is not set
func NewTimer() *Timer {
	return &Timer{t: time.NewTimer(time.Duration(math.MaxInt64))}
}

// Chan returns the channel of the wrapped timer
func (t *Timer) Chan() <-chan time.Time {
	return t.t.C
}

// Reset the timer, no matter whether the value was read or not
func (t *Timer) Reset(deadline time.Time) {
	if deadline.Equal(t.deadline) && !t.read {
		// No need to reset the timer
		return
	}

	// We need to drain the timer if the value from its channel was not read yet.
	// See https://groups.google.com/forum/#!topic/golang-dev/c9UUfASVPoU
	if !t.t.Stop() && !t.read {
		<-t.t.C
	}
	if !deadline.IsZero() {
		t.t.Reset(time.Until(deadline))
	}

	t.read = false
	t.deadline = deadline
}

// SetRead should be called after the value from the chan was read
func (t *Timer) SetRead() {
	t.read = true
}

func (t *Timer) Deadline() time.Time {
	return t.deadline
}

// Stop stops the timer
func (t *Timer) Stop() {
	t.t.Stop()
}