-
Notifications
You must be signed in to change notification settings - Fork 0
/
deserializer.go
145 lines (134 loc) · 2.46 KB
/
deserializer.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package main
import (
"bufio"
"fmt"
"io"
"strconv"
)
const (
STRING = '+'
ERROR = '-'
INTEGER = ':'
BULK = '$'
ARRAY = '*'
)
type Value struct {
typ string // refare to data type
str string // strings from simple strings
num int
bulk string
array []Value
}
type Resp struct {
reader *bufio.Reader
}
func NewResp(rd io.Reader) *Resp {
return &Resp{reader: bufio.NewReader(rd)}
}
func (r *Resp) readLine() (line []byte, n int, err error) {
for {
b, err := r.reader.ReadByte()
if err != nil {
return nil, 0, err
}
n += 1
line = append(line, b)
if len(line) >= 2 && line[len(line)-2] == '\r' {
break
}
}
return line[:len(line)-2], n, nil
}
func (r *Resp) readInteger() (x int, n int, err error) {
line, n, err := r.readLine()
if err != nil {
return 0, 0, nil
}
i64, err := strconv.ParseInt(string(line), 10, 64)
if err != nil {
return 0, 0, nil
}
return int(i64), n, err
}
func (r *Resp) Read() (Value, error) {
_type, err := r.reader.ReadByte()
if err != nil {
return Value{}, err
}
switch _type {
case ARRAY:
return r.readArray()
case BULK:
return r.readBulk()
case STRING:
return r.readString()
case ERROR:
return r.readError()
case INTEGER:
return r.readIntegerValue()
default:
fmt.Printf("Unknown type : %v", string(_type))
return Value{}, nil
}
}
func (r *Resp) readArray() (Value, error) {
v := Value{}
v.typ = "array"
// read the length of the array
len, _, err := r.readInteger()
if err != nil {
return v, err
}
// iterate over the arrays elements
v.array = make([]Value, 0)
for i := 0; i < len; i++ {
val, err := r.Read()
if err != nil {
return v, err
}
v.array = append(v.array, val)
}
return v, nil
}
func (r *Resp) readBulk() (Value, error) {
v := Value{}
v.typ = "bulk"
len, _, err := r.readInteger()
if err != nil {
return v, err
}
bulk := make([]byte, len)
r.reader.Read(bulk)
v.bulk = string(bulk)
r.readLine()
return v, nil
}
func (r *Resp) readString() (Value, error) {
v := Value{}
v.typ = "string"
val, _, err := r.readLine()
if err != nil {
return v, err
}
v.str = string(val)
return v, nil
}
func (r *Resp) readError() (Value, error) {
v := Value{}
v.typ = "error"
val, _, err := r.readLine()
if err != nil {
return v, err
}
v.str = string(val)
return v, nil
}
func (r *Resp) readIntegerValue() (Value, error) {
v := Value{typ: "integer"}
val, _, err := r.readInteger()
if err != nil {
return v, err
}
v.num = val
return v, nil
}