-
Notifications
You must be signed in to change notification settings - Fork 0
/
io.go
57 lines (52 loc) · 1.12 KB
/
io.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
package xtransport
import (
"encoding"
"encoding/json"
"fmt"
"io"
"unsafe"
)
func Write(w io.Writer, v interface{}) (n int, err error) {
switch v := v.(type) {
case nil:
return WriteString(w, "")
case string:
return WriteString(w, v)
case []byte:
return WriteBytes(w, v)
case io.WriterTo:
nb, err := v.WriteTo(w)
return int(nb), err
case encoding.BinaryMarshaler:
b, err := v.MarshalBinary()
if err != nil {
return 0, err
}
return WriteBytes(w, b)
case json.Marshaler:
b, err := v.MarshalJSON()
if err != nil {
return 0, err
}
return WriteBytes(w, b)
default:
return 0, fmt.Errorf(
"redis: can't marshal %T (implement encoding.BinaryMarshaler)", v)
}
}
func WriteBytes(w io.Writer, data []byte) (n int, err error) {
return w.Write(data)
}
func WriteString(w io.Writer, data string) (n int, err error) {
return w.Write(stringToBytes(data))
}
//https://github.com/go-redis/redis/blob/master/internal/util/unsafe.go
// stringToBytes converts string to byte slice.
func stringToBytes(s string) []byte {
return *(*[]byte)(unsafe.Pointer(
&struct {
string
Cap int
}{s, len(s)},
))
}