-
Notifications
You must be signed in to change notification settings - Fork 9
/
cached.go
76 lines (65 loc) 路 1.34 KB
/
cached.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
package cached
import (
constval "github.com/Equationzhao/g/internal/const"
"github.com/alphadose/haxmap"
)
type Map[k constval.Hashable, v any] struct {
*haxmap.Map[k, v]
}
func NewCacheMap[k constval.Hashable, v any](len int) *Map[k, v] {
return &Map[k, v]{
haxmap.New[k, v](uintptr(len)),
}
}
func (m Map[k, v]) Keys() []k {
keys := make([]k, 0, m.Len())
m.ForEach(func(k k, v v) bool {
keys = append(keys, k)
return true
})
return keys
}
func (m Map[k, v]) Values() []v {
values := make([]v, 0, m.Len())
m.ForEach(func(k k, v v) bool {
values = append(values, v)
return true
})
return values
}
func (m Map[k, v]) Pairs() []Pair[k, v] {
pairs := make([]Pair[k, v], 0, m.Len())
m.ForEach(func(key k, value v) bool {
pairs = append(pairs, Pair[k, v]{
First: key,
Second: value,
})
return true
})
return pairs
}
// Pair is a struct that contains two variables ptr
type Pair[T, U any] struct {
First T
Second U
}
// MakePair return a new Pair
// receive two value
func MakePair[T, U any](first T, second U) Pair[T, U] {
return Pair[T, U]{
First: first,
Second: second,
}
}
// Set the pair
// Copy the `first` and `second` to the pair
func (p *Pair[T, U]) Set(first T, second U) {
p.First = first
p.Second = second
}
func (p Pair[T, U]) Key() T {
return p.First
}
func (p Pair[T, U]) Value() U {
return p.Second
}