/
read_utils.go
112 lines (103 loc) · 2.03 KB
/
read_utils.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 go4redis
import (
"bufio"
"container/list"
"errors"
"strconv"
"strings"
)
func readArray(r *bufio.Reader) (interface{}, error) {
_, err := r.ReadByte()
if err != nil {
return EMPTY_STRING, err
}
countAsStr, err := ReadLine(r)
if err != nil {
return EMPTY_STRING, err
}
arrLen, err := strconv.Atoi(countAsStr)
if err != nil {
return EMPTY_STRING, err
}
l := list.New()
for i := 0; i < arrLen; i++ {
val, err := readType(r)
if err != nil {
return EMPTY_STRING, err
}
l.PushBack(val)
}
return l, nil
}
func readNumber(r *bufio.Reader) (interface{}, error) {
_, err := r.ReadByte()
if err != nil {
return EMPTY_STRING, err
}
value, err := ReadLine(r)
if err != nil {
return EMPTY_STRING, err
}
return strconv.Atoi(value)
}
func readSimpleString(r *bufio.Reader) (interface{}, error) {
c, err := r.ReadByte()
if err != nil {
return EMPTY_STRING, err
}
line, err := ReadLine(r)
if err != nil {
return EMPTY_STRING, err
}
success := true
if c == '-' {
success = false
}
return SimpleString{
value: (strings.Trim(line, NEWLINE)),
success: success,
}, nil
}
func readBulkString(r *bufio.Reader) (interface{}, error) {
_, err := r.ReadByte()
if err != nil {
return EMPTY_STRING, err
}
countAsStr, err := ReadLine(r)
if err != nil {
return EMPTY_STRING, err
}
count, err := strconv.Atoi(countAsStr)
if err != nil {
return EMPTY_STRING, err
}
if count == -1 {
return countAsStr, nil
}
line, err := ReadLine(r)
if err != nil {
return EMPTY_STRING, err
}
if len(line) != count {
return EMPTY_STRING, errors.New("Expected " + countAsStr + " characters in string and got " + line)
}
return line, nil
}
func readType(r *bufio.Reader) (interface{}, error) {
c, err := r.Peek(1)
if err != nil {
return EMPTY_STRING, err
}
switch c[0] {
case '+', '-':
return readSimpleString(r)
case ':':
return readNumber(r)
case '$':
return readBulkString(r)
case '*':
return readArray(r)
default:
return EMPTY_STRING, errors.New("Invalid first token in response")
}
}