forked from pangudashu/memcache
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtools.go
More file actions
59 lines (45 loc) · 1.12 KB
/
tools.go
File metadata and controls
59 lines (45 loc) · 1.12 KB
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
package memcache
import (
"bytes"
"encoding/binary"
"encoding/gob"
"errors"
"math"
)
//float 32/64 -> []byte
func Float32ToByte(float float32) []byte {
bits := math.Float32bits(float)
bytes := make([]byte, 4)
binary.LittleEndian.PutUint32(bytes, bits)
return bytes
}
func ByteToFloat32(bytes []byte) float32 {
bits := binary.LittleEndian.Uint32(bytes)
return math.Float32frombits(bits)
}
func Float64ToByte(float float64) []byte {
bits := math.Float64bits(float)
bytes := make([]byte, 8)
binary.LittleEndian.PutUint64(bytes, bits)
return bytes
}
func ByteToFloat64(bytes []byte) float64 {
bits := binary.LittleEndian.Uint64(bytes)
return math.Float64frombits(bits)
}
func StructToByte(value interface{}) (b []byte, err error) {
var buf bytes.Buffer
encoder := gob.NewEncoder(&buf)
if err = encoder.Encode(value); err != nil {
return nil, errors.New("encode fail")
}
return buf.Bytes(), nil
}
func ByteToStruct(b []byte, value interface{}) (err error) {
buf := bytes.NewBuffer(b)
decoder := gob.NewDecoder(buf)
if err = decoder.Decode(value); err != nil {
return errors.New("decode fail")
}
return nil
}