-
Notifications
You must be signed in to change notification settings - Fork 0
/
resp.go
127 lines (101 loc) · 1.92 KB
/
resp.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
package main
import (
"bufio"
"fmt"
"io"
"strconv"
)
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, err
}
i64, err := strconv.ParseInt(string(line), 10, 64)
if err != nil {
return 0, n, err
}
return int(i64), n, nil
}
func (r *Resp) Read() (Value, error) {
_type, err := r.reader.ReadByte()
if err != nil {
return Value{}, err
}
switch _type {
case ARRAY.Type:
return r.readArray()
case BULK.Type:
return r.readBulk()
default:
fmt.Printf("Unknown type: %v", string(_type))
return Value{}, nil
}
}
func (r *Resp) readArray() (Value, error) {
v := Value{}
v.Typ = ARRAY.Str
// read length of array
length, _, err := r.readInteger()
if err != nil {
return v, err
}
// foreach line, parse and read the value
v.Array = make([]Value, length)
for i := 0; i < length; i++ {
val, err := r.Read()
if err != nil {
return v, err
}
// add parsed value to array
v.Array[i] = val
}
return v, nil
}
func (r *Resp) readBulk() (Value, error) {
v := Value{}
v.Typ = BULK.Str
len, _, err := r.readInteger()
if err != nil {
return v, err
}
bulk := make([]byte, len)
r.reader.Read(bulk)
v.Bulk = string(bulk)
// Read the trailing CRLF
r.readLine()
return v, nil
}
type Writer struct {
writer io.Writer
}
func NewWriter(w io.Writer) *Writer {
return &Writer{writer: w}
}
func (w *Writer) Write(v Value) error {
var bytes = v.Marshal()
_, err := w.writer.Write(bytes)
if err != nil {
return err
}
return nil
}