-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcollection_types.go
133 lines (102 loc) · 2.27 KB
/
collection_types.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
package mint
import (
"encoding/binary"
"io"
)
type SliceCollection struct {
fixedLength bool
len uint32
V []MarshallerUnmarshallerValuer
}
func NewSliceCollection(v []MarshallerUnmarshallerValuer, isFixedLength bool) *SliceCollection {
return &SliceCollection{
fixedLength: isFixedLength,
len: uint32(len(v)),
V: v,
}
}
func (s SliceCollection) Len() int {
return int(s.len)
}
func (s *SliceCollection) ReadSize(r io.Reader) (err error) {
if s.fixedLength {
return nil
}
return binary.Read(r, binary.LittleEndian, &s.len)
}
func (s SliceCollection) Marshall(w io.Writer) (err error) {
if !s.fixedLength {
err = binary.Write(w, binary.LittleEndian, s.len)
if err != nil {
return
}
}
for _, i := range s.V {
err = i.Marshall(w)
if err != nil {
return
}
}
return nil
}
func (s *SliceCollection) Unmarshall(r io.Reader) (err error) {
for i := uint32(0); i < s.len; i++ {
err = s.V[i].Unmarshall(r)
if err != nil {
return
}
}
return
}
func (s SliceCollection) Value() any {
return s.V
}
type MapCollection struct {
V map[MarshallerUnmarshallerValuer]MarshallerUnmarshallerValuer
len uint32
}
func NewMapCollection(v map[MarshallerUnmarshallerValuer]MarshallerUnmarshallerValuer) *MapCollection {
return &MapCollection{
V: v,
}
}
func (s MapCollection) Len() int {
return int(s.len)
}
func (s *MapCollection) ReadSize(r io.Reader) (err error) {
var intermediate uint32 = 0
err = binary.Read(r, binary.LittleEndian, &intermediate)
if err != nil {
return
}
s.len = intermediate / 2
return
}
func (s MapCollection) Marshall(w io.Writer) (err error) {
return NewSliceCollection(s.slice(), false).Marshall(w)
}
func (s *MapCollection) Unmarshall(r io.Reader) (err error) {
sl := s.slice()
err = NewSliceCollection(sl, false).Unmarshall(r)
if err != nil {
return
}
s.V = make(map[MarshallerUnmarshallerValuer]MarshallerUnmarshallerValuer)
for i := 0; i < len(sl); i += 2 {
s.V[sl[i]] = sl[i+1]
}
return
}
func (s MapCollection) Value() any {
return s.V
}
func (s MapCollection) slice() []MarshallerUnmarshallerValuer {
slice := make([]MarshallerUnmarshallerValuer, len(s.V)*2)
idx := 0
for k, v := range s.V {
slice[idx] = k
slice[idx+1] = v
idx += 2
}
return slice
}