forked from couchbase/gocb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
transcoding.go
95 lines (85 loc) · 1.96 KB
/
transcoding.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
package gocb
import (
"encoding/json"
)
type Transcoder interface {
Decode([]byte, uint32, interface{}) error
Encode(interface{}) ([]byte, uint32, error)
}
type DefaultTranscoder struct {
}
func (t DefaultTranscoder) Decode(bytes []byte, flags uint32, out interface{}) error {
// Check for legacy flags
if flags&cfMask == 0 {
// Legacy Flags
if flags == lfJson {
// Legacy JSON
flags = cfFmtJson
} else {
return clientError{"Unexpected legacy flags value"}
}
}
// Make sure compression is disabled
if flags&cfCmprMask != cfCmprNone {
return clientError{"Unexpected value compression"}
}
// Normal types of decoding
if flags&cfFmtMask == cfFmtBinary {
switch typedOut := out.(type) {
case *[]byte:
*typedOut = bytes
return nil
case *interface{}:
*typedOut = bytes
return nil
default:
return clientError{"You must encode binary in a byte array or interface"}
}
} else if flags&cfFmtMask == cfFmtString {
switch typedOut := out.(type) {
case *string:
*typedOut = string(bytes)
return nil
case *interface{}:
*typedOut = string(bytes)
return nil
default:
return clientError{"You must encode a string in a string or interface"}
}
} else if flags&cfFmtMask == cfFmtJson {
err := json.Unmarshal(bytes, &out)
if err != nil {
return err
}
return nil
} else {
return clientError{"Unexpected flags value"}
}
}
func (t DefaultTranscoder) Encode(value interface{}) ([]byte, uint32, error) {
var bytes []byte
var flags uint32
var err error
switch value.(type) {
case []byte:
bytes = value.([]byte)
flags = cfFmtBinary
case *[]byte:
bytes = *value.(*[]byte)
flags = cfFmtBinary
case string:
bytes = []byte(value.(string))
flags = cfFmtString
case *string:
bytes = []byte(*value.(*string))
flags = cfFmtString
default:
bytes, err = json.Marshal(value)
if err != nil {
return nil, 0, err
}
flags = cfFmtJson
}
// No compression supported currently
return bytes, flags, nil
}