forked from thrasher-corp/gocryptotrader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nonce.go
84 lines (72 loc) · 1.7 KB
/
nonce.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package nonce
import (
"strconv"
"sync"
"time"
)
// Nonce struct holds the nonce value
type Nonce struct {
// Standard nonce
n int64
mtx sync.Mutex
// Hash table exclusive exchange specific nonce values
boundedCall map[string]int64
boundedMtx sync.Mutex
}
// Inc increments the nonce value
func (n *Nonce) Inc() {
n.mtx.Lock()
n.n++
n.mtx.Unlock()
}
// Get retrives the nonce value
func (n *Nonce) Get() int64 {
n.mtx.Lock()
defer n.mtx.Unlock()
return n.n
}
// GetInc increments and returns the value of the nonce
func (n *Nonce) GetInc() int64 {
n.mtx.Lock()
defer n.mtx.Unlock()
n.n++
return n.n
}
// Set sets the nonce value
func (n *Nonce) Set(val int64) {
n.mtx.Lock()
n.n = val
n.mtx.Unlock()
}
// Returns a string version of the nonce
func (n *Nonce) String() string {
n.mtx.Lock()
result := strconv.FormatInt(n.n, 10)
n.mtx.Unlock()
return result
}
// Value is a return type for GetValue
type Value int64
// GetValue returns a nonce value and can be set as a higher precision. Values
// stored in an exchange specific hash table using a single locked call.
func (n *Nonce) GetValue(exchName string, nanoPrecision bool) Value {
n.boundedMtx.Lock()
defer n.boundedMtx.Unlock()
if n.boundedCall == nil {
n.boundedCall = make(map[string]int64)
}
if n.boundedCall[exchName] == 0 {
if nanoPrecision {
n.boundedCall[exchName] = time.Now().UnixNano()
return Value(n.boundedCall[exchName])
}
n.boundedCall[exchName] = time.Now().Unix()
return Value(n.boundedCall[exchName])
}
n.boundedCall[exchName]++
return Value(n.boundedCall[exchName])
}
// String is a Value method that changes format to a string
func (v Value) String() string {
return strconv.FormatInt(int64(v), 10)
}