-
Notifications
You must be signed in to change notification settings - Fork 1
/
token.go
55 lines (46 loc) · 1.1 KB
/
token.go
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
package coap
import (
"math/rand"
"sync"
"time"
)
type TokenGenerator interface {
NextToken() []byte
}
type RandomTokenGenerator struct {
lastTokenSeq uint8 // Sequence counter
rand *rand.Rand // Random source for token generation
mu sync.Mutex
}
func NewRandomTokenGenerator() TokenGenerator {
return &RandomTokenGenerator{
rand: rand.New(rand.NewSource(time.Now().UnixNano())),
}
}
func (t *RandomTokenGenerator) NextToken() []byte {
// It's critical to not get the same token twice,
// since we identify our interactions by the token
t.mu.Lock()
defer t.mu.Unlock()
tok := make([]byte, 4)
t.rand.Read(tok)
t.lastTokenSeq++
tok[0] = t.lastTokenSeq
return tok
}
// Mainly used for tests, uses 1 Byte tokens that simply count up
type CountingTokenGenerator struct {
lastTokenSeq uint8 // Sequence counter
mu sync.Mutex
}
func NewCountingTokenGenerator() TokenGenerator {
return &CountingTokenGenerator{}
}
func (t *CountingTokenGenerator) NextToken() []byte {
t.mu.Lock()
defer t.mu.Unlock()
tok := make([]byte, 1)
t.lastTokenSeq++
tok[0] = t.lastTokenSeq
return tok
}