-
Notifications
You must be signed in to change notification settings - Fork 3
/
gob.go
44 lines (37 loc) · 923 Bytes
/
gob.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
package gobKit
import (
"bytes"
"encoding/gob"
"io"
)
// Marshal 序列化.
/*
e.g.
var m map[interface{}]interface{} = nil
fmt.Println(gobKit.Marshal(m)) // [13 127 4 1 2 255 128 0 1 16 1 16 0 0 4 255 128 0 0] <nil>
var obj interface{} = nil
fmt.Println(gobKit.Marshal(obj)) // [] gob: cannot encode nil value
*/
func Marshal(obj any) ([]byte, error) {
//buf := new(bytes.Buffer)
buf := bytes.NewBuffer(nil)
encoder := gob.NewEncoder(buf)
err := encoder.Encode(obj)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// Unmarshal 反序列化.
/*
PS: 反序列化为map实例,key类型可以是interface{}.
*/
func Unmarshal(data []byte, ptr interface{}) error {
buf := bytes.NewBuffer(data)
decoder := gob.NewDecoder(buf)
return decoder.Decode(ptr)
}
func UnmarshalFromReader(reader io.Reader, ptr interface{}) error {
decoder := gob.NewDecoder(reader)
return decoder.Decode(ptr)
}