-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwriter.go
91 lines (75 loc) · 1.6 KB
/
writer.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
package main
import (
"fmt"
"io"
"strconv"
)
type Writer struct {
writer io.Writer
}
func (w *Writer) Write(v Value) error {
var bytes = v.Marshal()
fmt.Printf("writing to conn %s", bytes)
_, err := w.writer.Write(bytes)
if err != nil {
fmt.Println("error while writing")
return err
}
return nil
}
func NewWriter(w io.Writer) *Writer {
return &Writer{writer: w}
}
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{}
}
}
func (v Value) marshalString() []byte {
var bytes []byte
bytes = append(bytes, STRING)
bytes = append(bytes, v.str...)
bytes = append(bytes, '\r', '\n')
return bytes
}
func (v Value) marshalBulk() []byte {
var bytes []byte
bytes = append(bytes, BULK)
bytes = append(bytes, strconv.Itoa(len(v.bulk))...)
bytes = append(bytes, '\r', '\n')
bytes = append(bytes, v.bulk...)
bytes = append(bytes, '\r', '\n')
return bytes
}
func (v Value) marshalArray() []byte {
len := len(v.array)
var bytes []byte
bytes = append(bytes, ARRAY)
bytes = append(bytes, strconv.Itoa(len)...)
bytes = append(bytes, '\r', '\n')
for i := 0; i < len; i++ {
bytes = append(bytes, v.array[i].Marshal()...)
}
return bytes
}
func (v Value) marshallError() []byte {
var bytes []byte
bytes = append(bytes, ERROR)
bytes = append(bytes, v.str...)
bytes = append(bytes, '\r', '\n')
return bytes
}
func (v Value) marshallNull() []byte {
return []byte("$-1\r\n")
}