mirror of
https://github.com/d0zingcat/gocryptotrader.git
synced 2026-05-13 15:09:42 +00:00
common/gateio/stream: add thread-safe counter and overide default GenerateMessageID with connection specific implementation (#1615)
* add counter and update gateio * Update exchanges/gateio/gateio.go Co-authored-by: Scott <gloriousCode@users.noreply.github.com> * thrasher: nits * add test case * linter: fix * revert change * thrasher nits --------- Co-authored-by: Ryan O'Hara-Reid <ryan.oharareid@thrasher.io> Co-authored-by: Scott <gloriousCode@users.noreply.github.com>
This commit is contained in:
@@ -19,6 +19,7 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
@@ -672,3 +673,19 @@ func SortStrings[S ~[]E, E fmt.Stringer](x S) S {
|
||||
})
|
||||
return n
|
||||
}
|
||||
|
||||
// Counter is a thread-safe counter.
|
||||
type Counter struct {
|
||||
n int64 // privatised so you can't use counter as a value type
|
||||
}
|
||||
|
||||
// IncrementAndGet returns the next count after incrementing.
|
||||
func (c *Counter) IncrementAndGet() int64 {
|
||||
newID := atomic.AddInt64(&c.n, 1)
|
||||
// Handle overflow by resetting the counter to 1 if it becomes negative
|
||||
if newID < 0 {
|
||||
atomic.StoreInt64(&c.n, 1)
|
||||
return 1
|
||||
}
|
||||
return newID
|
||||
}
|
||||
|
||||
@@ -862,3 +862,18 @@ func (a A) String() string {
|
||||
func TestSortStrings(t *testing.T) {
|
||||
assert.Equal(t, []A{1, 2, 5, 6}, SortStrings([]A{6, 2, 5, 1}))
|
||||
}
|
||||
|
||||
func TestCounter(t *testing.T) {
|
||||
t.Parallel()
|
||||
c := Counter{n: -5}
|
||||
require.Equal(t, int64(1), c.IncrementAndGet())
|
||||
require.Equal(t, int64(2), c.IncrementAndGet())
|
||||
}
|
||||
|
||||
// 683185328 1.787 ns/op 0 B/op 0 allocs/op
|
||||
func BenchmarkCounter(b *testing.B) {
|
||||
c := Counter{}
|
||||
for i := 0; i < b.N; i++ {
|
||||
c.IncrementAndGet()
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user