/
pack.go
69 lines (63 loc) · 1.2 KB
/
pack.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 mfscli
import (
"bytes"
"encoding/binary"
"io"
)
func write(w io.Writer, data ...interface{}) {
for _, d := range data {
binary.Write(w, binary.BigEndian, d)
}
}
func read(r io.Reader, data ...interface{}) {
for _, d := range data {
binary.Read(r, binary.BigEndian, d)
}
}
func Pack(data ...interface{}) []byte {
buf := new(bytes.Buffer)
for _, d := range data {
switch v := d.(type) {
case []byte:
buf.Write(v)
case string:
buf.WriteString(v)
case *string:
buf.WriteString(*v)
case int:
write(buf, int32(v))
case *int:
write(buf, int32(*v))
case uint:
write(buf, uint32(v))
case *uint:
write(buf, uint32(*v))
default:
write(buf, v)
}
}
return buf.Bytes()
}
func UnPack(in []byte, out ...interface{}) {
reader := bytes.NewReader(in)
read(reader, out...)
}
func PackCmd(cmd uint32, data ...interface{}) []byte {
size := 0
for _, d := range data {
switch v := d.(type) {
case string:
size += len(v)
case *string:
size += len(*v)
case int, *int, uint, *uint:
size += 4
default:
size += binary.Size(d)
}
}
args := make([]interface{}, 0)
args = append(args, cmd, uint32(size))
args = append(args, data...)
return Pack(args...)
}