-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencode.go
More file actions
42 lines (36 loc) · 777 Bytes
/
Copy pathencode.go
File metadata and controls
42 lines (36 loc) · 777 Bytes
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
package main
import "strconv"
func Encode(resp Resp) []byte {
switch resp.Type {
case TypeString, TypeInt, TypeError:
return encodeTextByBytes(resp)
case TypeBulkBytes:
return encodeBulkBytesByBytes(resp)
default:
return nil
}
}
func encodeTextByBytes(resp Resp) []byte {
size := len(resp.Value) + 3
b := make([]byte, size)
b[0] = resp.Type
copy(b[1:], resp.Value)
b[size-2] = '\r'
b[size-1] = '\n'
return b
}
func encodeBulkBytesByBytes(resp Resp) []byte {
l := len(resp.Value)
count := []byte(strconv.Itoa(l))
countLen := len(count)
size := l + countLen + 5
b := make([]byte, size)
b[0] = resp.Type
copy(b[1:], count)
b[countLen+1] = '\r'
b[countLen+2] = '\n'
copy(b[countLen+3:], resp.Value)
b[size-2] = '\r'
b[size-1] = '\n'
return b
}