-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresp.go
192 lines (165 loc) · 4.62 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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
package main
import (
"bufio"
"fmt"
"io"
"strconv"
)
const (
STRING = '+'
ERROR = '-'
INTEGER = ':'
BULK = '$'
ARRAY = '*'
)
// Value represents the different types of RESP (Redis Serialization Protocol) values.
type Value struct {
typ string // Type of value ('string', 'error', 'integer', 'bulk', 'array')
str string // Used for string and error types
num int // Used for integer type
bulk string // Used for bulk strings
array []Value // Used for arrays of nested values
}
// Resp is a parser for RESP encoded data.
type Resp struct {
reader *bufio.Reader
}
// NewResp creates a new Resp object with a buffered reader.
func NewResp(rd io.Reader) *Resp {
return &Resp{reader: bufio.NewReader(rd)}
}
// readLine reads a line ending with CRLF from the reader.
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' && line[len(line)-1] == '\n' {
break
}
}
return line[:len(line)-2], n, nil // Trim the CRLF at the end
}
// readInteger reads an integer value following the ':' prefix.
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
}
// Read parses the next RESP value from the stream.
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()
default:
fmt.Printf("Unknown type: %v", string(_type))
return Value{}, fmt.Errorf("unknown value type %v", _type)
}
}
// readArray reads an array prefixed with '*' from the stream.
func (r *Resp) readArray() (Value, error) {
v := Value{typ: "array"}
len, _, err := r.readInteger()
if err != nil {
return v, err
}
v.array = make([]Value, len)
for i := 0; i < len; i++ {
val, err := r.Read()
if err != nil {
return v, err
}
v.array[i] = val
}
return v, nil
}
// readBulk reads a bulk string prefixed with '$' from the stream.
func (r *Resp) readBulk() (Value, error) {
v := Value{typ: "bulk"}
len, _, err := r.readInteger()
if err != nil {
return v, err
}
if len == -1 { // RESP Bulk strings can be null, indicated by "$-1"
return Value{typ: "null"}, nil
}
bulk := make([]byte, len)
_, err = io.ReadFull(r.reader, bulk) // Use ReadFull to ensure we read exactly 'len' bytes
if err != nil {
return v, err
}
v.bulk = string(bulk)
r.readLine() // Read the trailing CRLF
return v, nil
}
// Marshal converts a Value object into its corresponding RESP bytes.
func (v Value) Marshal() []byte {
switch v.typ {
case "array":
return v.marshalArray()
case "bulk":
return v.marshalBulk()
case "string":
return v.marshalString()
case "null":
return v.marshallNull()
case "error":
return v.marshallError()
default:
return []byte("unknown type")
}
}
// marshalString marshals a string value into RESP format.
func (v Value) marshalString() []byte {
return append([]byte{STRING}, append([]byte(v.str), '\r', '\n')...)
}
// marshalBulk marshals a bulk string into RESP format.
func (v Value) marshalBulk() []byte {
bulkHeader := append([]byte{BULK}, append([]byte(strconv.Itoa(len(v.bulk))), '\r', '\n')...)
return append(bulkHeader, append([]byte(v.bulk), '\r', '\n')...)
}
// marshalArray marshals an array of values into RESP format.
func (v Value) marshalArray() []byte {
arrayHeader := append([]byte{ARRAY}, append([]byte(strconv.Itoa(len(v.array))), '\r', '\n')...)
for _, val := range v.array {
arrayHeader = append(arrayHeader, val.Marshal()...)
}
return arrayHeader
}
// marshallError marshals an error message into RESP format.
func (v Value) marshallError() []byte {
return append([]byte{ERROR}, append([]byte(v.str), '\r', '\n')...)
}
// marshallNull marshals a null value into RESP bulk string format.
func (v Value) marshallNull() []byte {
return []byte("$-1\r\n")
}
// Writer wraps an io.Writer to write RESP formatted data.
type Writer struct {
writer io.Writer
}
// NewWriter creates a new Writer object.
func NewWriter(w io.Writer) *Writer {
return &Writer{writer: w}
}
// Write sends a marshaled Value to the underlying writer.
func (w *Writer) Write(v Value) error {
bytes := v.Marshal()
_, err := w.writer.Write(bytes)
return err
}