Debian Codegraph @

_examples/custom_engine_tarantool/tntengine/util.go

raw
1 package tntengine
2
3 import (
4 "hash/fnv"
5 "sync"
6 "time"
7
8 "github.com/centrifugal/centrifuge"
9 "github.com/centrifugal/protocol"
10 )
11
12 // index chooses bucket number in range [0, numBuckets).
13 func index(s string, numBuckets int) int {
14 if numBuckets == 1 {
15 return 0
16 }
17 hash := fnv.New64a()
18 _, _ = hash.Write([]byte(s))
19 return int(hash.Sum64() % uint64(numBuckets))
20 }
21
22 // consistentIndex is an adapted function from https://github.com/dgryski/go-jump
23 // package by Damian Gryski. It consistently chooses a hash bucket number in the
24 // range [0, numBuckets) for the given string. numBuckets must be >= 1.
25 func consistentIndex(s string, numBuckets int) int {
26 hash := fnv.New64a()
27 _, _ = hash.Write([]byte(s))
28 key := hash.Sum64()
29
30 var (
31 b int64 = -1
32 j int64
33 )
34
35 for j < int64(numBuckets) {
36 b = j
37 key = key*2862933555777941757 + 1
38 j = int64(float64(b+1) * (float64(int64(1)<<31) / float64((key>>33)+1)))
39 }
40
41 return int(b)
42 }
43
44 func consistentShard(ch string, shards []*Shard) *Shard {
45 if len(shards) == 1 {
46 return shards[0]
47 }
48 return shards[consistentIndex(ch, len(shards))]
49 }
50
51 func infoToProto(v *centrifuge.ClientInfo) *protocol.ClientInfo {
52 if v == nil {
53 return nil
54 }
55 info := &protocol.ClientInfo{
56 Client: v.ClientID,
57 User: v.UserID,
58 }
59 if len(v.ConnInfo) > 0 {
60 info.ConnInfo = v.ConnInfo
61 }
62 if len(v.ChanInfo) > 0 {
63 info.ChanInfo = v.ChanInfo
64 }
65 return info
66 }
67
68 func infoFromProto(v *protocol.ClientInfo) *centrifuge.ClientInfo {
69 if v == nil {
70 return nil
71 }
72 info := &centrifuge.ClientInfo{
73 ClientID: v.GetClient(),
74 UserID: v.GetUser(),
75 }
76 if len(v.ConnInfo) > 0 {
77 info.ConnInfo = v.ConnInfo
78 }
79 if len(v.ChanInfo) > 0 {
80 info.ChanInfo = v.ChanInfo
81 }
82 return info
83 }
84
85 var timerPool sync.Pool
86
87 // AcquireTimer from pool.
88 func AcquireTimer(d time.Duration) *time.Timer {
89 v := timerPool.Get()
90 if v == nil {
91 return time.NewTimer(d)
92 }
93
94 tm := v.(*time.Timer)
95 if tm.Reset(d) {
96 panic("Received an active timer from the pool!")
97 }
98 return tm
99 }
100
101 // ReleaseTimer to pool.
102 func ReleaseTimer(tm *time.Timer) {
103 if !tm.Stop() {
104 // Do not reuse timer that has been already stopped.
105 // See https://groups.google.com/forum/#!topic/golang-nuts/-8O3AknKpwk
106 return
107 }
108 timerPool.Put(tm)
109 }