-
-
Notifications
You must be signed in to change notification settings - Fork 36
/
partmap.go
69 lines (54 loc) · 1.44 KB
/
partmap.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
package partmap
// PartMap is a concurrent map with separate partitions to reduce lock contention.
type PartMap struct {
partitions []*partition
finder Partitioner
}
// New creates a new PartMap with the given number of partitions and Partitioner.
func New(partitioner Partitioner, partitions uint) (*PartMap, error) {
if partitions == 0 {
return nil, ErrPartitionsMustBeGreaterThanZero
}
parts := make([]*partition, partitions)
for i := range parts {
parts[i] = &partition{store: make(map[string]any)}
}
return &PartMap{
partitions: parts,
finder: partitioner,
}, nil
}
// Get retrieves a value from the map.
func (pm *PartMap) Get(key string) (any, bool) {
partitionIndex, err := pm.finder.Find(key)
if err != nil {
return nil, false
}
return pm.partitions[partitionIndex].get(key)
}
// Set adds a key-value pair to the map.
func (pm *PartMap) Set(key string, val any) error {
partitionIndex, err := pm.finder.Find(key)
if err != nil {
return err
}
pm.partitions[partitionIndex].set(key, val)
return nil
}
// Delete removes a key-value pair from the map.
func (pm *PartMap) Delete(key string) error {
partitionIndex, err := pm.finder.Find(key)
if err != nil {
return err
}
pm.partitions[partitionIndex].delete(key)
return nil
}
// Len returns the total number of key-value pairs in the PartMap.
func (pm *PartMap) Len() int {
total := 0
for _, p := range pm.partitions {
total += p.len()
}
return total
}