generated from openacid/gotmpl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nativeint.go
53 lines (44 loc) · 1.06 KB
/
nativeint.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
package qcodec
import (
"encoding/binary"
"math/bits"
)
// Int converts int to slice of bytes and back.
type Int struct{}
// Encode converts int to slice of bytes.
func (c Int) Encode(d interface{}) []byte {
size := bits.UintSize / 8
b := make([]byte, size)
v := d.(int)
if size == 4 {
binary.LittleEndian.PutUint32(b, uint32(v))
} else if size == 8 {
binary.LittleEndian.PutUint64(b, uint64(v))
} else {
panic("unknown int size")
}
return b
}
// Decode converts slice of bytes to int.
// It returns number bytes consumed and an int.
func (c Int) Decode(b []byte) (int, interface{}) {
size := bits.UintSize / 8
s := b[:size]
var d int
if size == 4 {
d = int(binary.LittleEndian.Uint32(s))
} else if size == 8 {
d = int(binary.LittleEndian.Uint64(s))
} else {
panic("unknown int size")
}
return size, d
}
// GetSize returns native int size in byte after encoding v.
func (c Int) Size(d interface{}) int {
return bits.UintSize / 8
}
// GetEncodedSize returns native int size.
func (c Int) EncodedSize(b []byte) int {
return bits.UintSize / 8
}