-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathhash.go
112 lines (90 loc) · 2.3 KB
/
hash.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package rdb
import (
"fmt"
"github.com/tommy351/rdb-go/internal/convert"
)
// HashValue contains a key-value pair of a hash entry.
type HashValue struct {
Index string
Value string
}
// HashHead contains the key and the length of a hash. It is returned when a hash
// is read first time.
type HashHead struct {
DataKey
Length int
}
// HashEntry is returned when a new hash entry is read.
type HashEntry struct {
DataKey
HashValue
Length int
}
// HashData is returned when all entries in a hash are all read.
type HashData struct {
DataKey
Value map[string]string
}
type hashValueReader struct{}
func (hashValueReader) ReadValue(r byteReader) (interface{}, error) {
key, err := readString(r)
if err != nil {
return nil, fmt.Errorf("failed to read hash key: %w", err)
}
value, err := readString(r)
if err != nil {
return nil, fmt.Errorf("failed to read hash value: %w", err)
}
return HashValue{
Index: key,
Value: value,
}, nil
}
type hashMapper struct{}
func (hashMapper) MapHead(head *collectionHead) (interface{}, error) {
return &HashHead{
DataKey: head.DataKey,
Length: head.Length,
}, nil
}
func (hashMapper) MapEntry(element *collectionEntry) (interface{}, error) {
return &HashEntry{
DataKey: element.DataKey,
HashValue: element.Value.(HashValue),
Length: element.Length,
}, nil
}
func (hashMapper) MapSlice(slice *collectionSlice) (interface{}, error) {
data := &HashData{
DataKey: slice.DataKey,
Value: make(map[string]string, len(slice.Value)),
}
for _, v := range slice.Value {
v := v.(HashValue)
data.Value[v.Index] = v.Value
}
return data, nil
}
type hashZipListValueReader struct{}
func (hashZipListValueReader) ReadValue(r byteReader) (interface{}, error) {
key, err := readZipListEntry(r)
if err != nil {
return nil, fmt.Errorf("failed to read hash key from ziplist: %w", err)
}
value, err := readZipListEntry(r)
if err != nil {
return nil, fmt.Errorf("failed to read hash value from ziplist: %w", err)
}
keyString, err := convert.String(key)
if err != nil {
return nil, fmt.Errorf("failed to convert hash key to string: %w", err)
}
valueString, err := convert.String(value)
if err != nil {
return nil, fmt.Errorf("failed to convert hash value to string: %w", err)
}
return HashValue{
Index: keyString,
Value: valueString,
}, nil
}