Add nonce package for exchanges

This commit is contained in:
Adrian Gallagher
2017-08-21 15:57:41 +10:00
parent 0fea98857c
commit f3c1f4880d
20 changed files with 256 additions and 61 deletions

49
exchanges/nonce/nonce.go Normal file
View File

@@ -0,0 +1,49 @@
package nonce
import (
"strconv"
"sync"
)
// Nonce struct holds the nonce value
type Nonce struct {
n int64
mtx 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
}

View File

@@ -0,0 +1,75 @@
package nonce
import (
"testing"
"time"
)
func TestInc(t *testing.T) {
var nonce Nonce
nonce.Set(1)
nonce.Inc()
expected := int64(2)
result := nonce.Get()
if result != expected {
t.Errorf("Test failed. Expected %d got %d", expected, result)
}
}
func TestGet(t *testing.T) {
var nonce Nonce
nonce.Set(112321313)
expected := int64(112321313)
result := nonce.Get()
if expected != result {
t.Errorf("Test failed. Expected %d got %d", expected, result)
}
}
func TestGetInc(t *testing.T) {
var nonce Nonce
nonce.Set(1)
expected := int64(2)
result := nonce.GetInc()
if expected != result {
t.Errorf("Test failed. Expected %d got %d", expected, result)
}
}
func TestSet(t *testing.T) {
var nonce Nonce
nonce.Set(1)
expected := int64(1)
result := nonce.Get()
if expected != result {
t.Errorf("Test failed. Expected %d got %d", expected, result)
}
}
func TestString(t *testing.T) {
var nonce Nonce
nonce.Set(12312313131)
expected := "12312313131"
result := nonce.String()
if expected != result {
t.Errorf("Test failed. Expected %s got %s", expected, result)
}
}
func TestNonceConcurrency(t *testing.T) {
var nonce Nonce
nonce.Set(12312)
for i := 0; i < 1000; i++ {
go nonce.Inc()
}
// Allow sufficient time for all routines to finish
time.Sleep(time.Second)
result := nonce.Get()
expected := int64(12312 + 1000)
if expected != result {
t.Errorf("Test failed. Expected %d got %d", expected, result)
}
}