-
Notifications
You must be signed in to change notification settings - Fork 4
/
value_encode_int.go
81 lines (71 loc) · 1.85 KB
/
value_encode_int.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
// Copyright 2024 GoEdge CDN goedge.cdn@gmail.com. All rights reserved. Official site: https://goedge.cn .
package kvstore
import (
"encoding/binary"
"github.com/iwind/TeaGo/types"
"golang.org/x/exp/constraints"
"strconv"
)
type IntValueEncoder[T constraints.Integer] struct {
}
func NewIntValueEncoder[T constraints.Integer]() *IntValueEncoder[T] {
return &IntValueEncoder[T]{}
}
func (this *IntValueEncoder[T]) Encode(value T) (data []byte, err error) {
switch v := any(value).(type) {
case int8, int16, int32, int, uint:
data = []byte(types.String(v))
case int64:
data = []byte(strconv.FormatInt(v, 16))
case uint8:
return []byte{v}, nil
case uint16:
data = make([]byte, 2)
binary.BigEndian.PutUint16(data, v)
case uint32:
data = make([]byte, 4)
binary.BigEndian.PutUint32(data, v)
case uint64:
data = make([]byte, 8)
binary.BigEndian.PutUint64(data, v)
}
return
}
func (this *IntValueEncoder[T]) EncodeField(value T, fieldName string) ([]byte, error) {
_ = fieldName
return this.Encode(value)
}
func (this *IntValueEncoder[T]) Decode(valueData []byte) (value T, err error) {
switch any(value).(type) {
case int8:
value = T(types.Int8(string(valueData)))
case int16:
value = T(types.Int16(string(valueData)))
case int32:
value = T(types.Int32(string(valueData)))
case int64:
int64Value, _ := strconv.ParseInt(string(valueData), 16, 64)
value = T(int64Value)
case int:
value = T(types.Int(string(valueData)))
case uint:
value = T(types.Uint(string(valueData)))
case uint8:
if len(valueData) == 1 {
value = T(valueData[0])
}
case uint16:
if len(valueData) == 2 {
value = T(binary.BigEndian.Uint16(valueData))
}
case uint32:
if len(valueData) == 4 {
value = T(binary.BigEndian.Uint32(valueData))
}
case uint64:
if len(valueData) == 8 {
value = T(binary.BigEndian.Uint64(valueData))
}
}
return
}