-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
71 lines (59 loc) · 1.59 KB
/
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
package main
import (
"errors"
"fmt"
"strconv"
"strings"
)
// errorMsg returns a formatted string error message
func errorMsg(msg string) string {
return fmt.Sprintf("-ERR %s", msg)
}
// stringMsg returns a formatted string message
func stringMsg(msg string) string {
return "+" + msg
}
// nilBulkStringMsg returns a nil bulk string Msg
func nilBulkStringMsg() string {
return "$-1"
}
type GetIntArgResult struct {
// The result of the parsing operation
Result int
// How many indexes were parsed from the provided byte array
PositionsParsed int
}
// getIntArg parses an integer argument from a string representation and returns
// the result and skipped amount of bytes in the array
func getIntArg(startPosition int, arr []byte) (*GetIntArgResult, error) {
var err error
result := &GetIntArgResult{
Result: 0,
PositionsParsed: 0,
}
// Get digits until termination characters
notDone := true
position := startPosition
// Building out a string with concatenation creates a new string each time. String builder
// is more efficient for incrementally building a string
var stringVal strings.Builder
for notDone {
if arr[position] == '\r' && arr[position+1] == '\n' {
// We hit the termination, consider it done
notDone = false
} else {
stringVal.WriteByte(arr[position])
}
result.PositionsParsed += 1
position += 1
}
if stringVal.Len() == 0 {
return nil, errors.New("no value was detected")
}
resultInt, err := strconv.Atoi(stringVal.String())
if err != nil {
return nil, errors.New("failed to parse int")
}
result.Result = resultInt
return result, nil
}