-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtype_map.go
76 lines (64 loc) · 1.29 KB
/
type_map.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 parco
import (
"io"
)
type (
mapType[K comparable, V any] struct {
length int
header IntType
keyType Type[K]
valueType Type[V]
pool Pooler
}
)
func (t mapType[K, V]) ByteLength() int {
return t.header.ByteLength() + t.length*(t.keyType.ByteLength()+t.valueType.ByteLength())
}
func (t mapType[K, V]) Parse(r io.Reader) (res map[K]V, err error) {
var (
length int
)
length, err = t.header.Parse(r)
t.length = length
if err != nil {
return nil, err
}
values := make(map[K]V, t.length)
for i := 0; i < t.length; i++ {
var (
k K
v V
)
if k, err = t.keyType.Parse(r); err != nil {
return
}
if v, err = t.valueType.Parse(r); err != nil {
return
}
values[k] = v
}
return values, nil
}
func (t mapType[K, V]) Compile(x map[K]V, w io.Writer) error {
t.length = len(x)
if err := t.header.Compile(t.length, w); err != nil {
return err
}
for k, v := range x {
if err := t.keyType.Compile(k, w); err != nil {
return err
}
if err := t.valueType.Compile(v, w); err != nil {
return err
}
}
return nil
}
func MapType[K comparable, V any](header IntType, keyType Type[K], valueType Type[V]) mapType[K, V] {
return mapType[K, V]{
header: header,
keyType: keyType,
valueType: valueType,
pool: SinglePool,
}
}