-
Notifications
You must be signed in to change notification settings - Fork 0
/
concurrentShardedCountsWithSize.go
93 lines (75 loc) · 2.39 KB
/
concurrentShardedCountsWithSize.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
85
86
87
88
89
90
91
92
93
package counting
import (
"fmt"
"sort"
"strings"
"sync"
"github.com/kalyan3104/k-core/core"
)
var _ CountsWithSize = (*ConcurrentShardedCountsWithSize)(nil)
// ConcurrentShardedCountsWithSize keeps counts (with sizes) for a sharded data structure
type ConcurrentShardedCountsWithSize struct {
mutex sync.RWMutex
byShard map[string]concurrentShardedCountsWithSizeItem
}
type concurrentShardedCountsWithSizeItem struct {
counter int64
sizeInBytes int64
}
// NewConcurrentShardedCountsWithSize creates a new ShardedCountsWithSize
func NewConcurrentShardedCountsWithSize() *ConcurrentShardedCountsWithSize {
return &ConcurrentShardedCountsWithSize{
byShard: make(map[string]concurrentShardedCountsWithSizeItem),
}
}
// PutCounts registers counts for a shard
func (counts *ConcurrentShardedCountsWithSize) PutCounts(shardName string, counter int64, sizeInBytes int64) {
counts.mutex.Lock()
counts.byShard[shardName] = concurrentShardedCountsWithSizeItem{counter: counter, sizeInBytes: sizeInBytes}
counts.mutex.Unlock()
}
// GetTotal gets total count
func (counts *ConcurrentShardedCountsWithSize) GetTotal() int64 {
counts.mutex.RLock()
defer counts.mutex.RUnlock()
total := int64(0)
for _, item := range counts.byShard {
total += item.counter
}
return total
}
// GetTotalSize gets total size
func (counts *ConcurrentShardedCountsWithSize) GetTotalSize() int64 {
counts.mutex.RLock()
defer counts.mutex.RUnlock()
total := int64(0)
for _, item := range counts.byShard {
total += item.sizeInBytes
}
return total
}
func (counts *ConcurrentShardedCountsWithSize) String() string {
var builder strings.Builder
total := counts.GetTotal()
totalSize := core.ConvertBytes(uint64(counts.GetTotalSize()))
_, _ = fmt.Fprintf(&builder, "Total:%d (%s); ", total, totalSize)
counts.mutex.RLock()
defer counts.mutex.RUnlock()
// First, we sort the keys alphanumerically
keys := make([]string, 0, len(counts.byShard))
for key := range counts.byShard {
keys = append(keys, key)
}
sort.Strings(keys)
for _, key := range keys {
item := counts.byShard[key]
counter := item.counter
size := core.ConvertBytes(uint64(item.sizeInBytes))
_, _ = fmt.Fprintf(&builder, "[%s]=%d (%s); ", key, counter, size)
}
return builder.String()
}
// IsInterfaceNil returns true if there is no value under the interface
func (counts *ConcurrentShardedCountsWithSize) IsInterfaceNil() bool {
return counts == nil
}