Debian Codegraph @

internal/proto/write_buffer.go

raw
1 package proto
2
3 import (
4 "encoding"
5 "fmt"
6 "strconv"
7 )
8
9 const bufferSize = 4096
10
11 type WriteBuffer struct {
12 b []byte
13 }
14
15 func NewWriteBuffer() *WriteBuffer {
16 return &WriteBuffer{
17 b: make([]byte, 0, 4096),
18 }
19 }
20
21 func (w *WriteBuffer) Len() int { return len(w.b) }
22 func (w *WriteBuffer) Bytes() []byte { return w.b }
23 func (w *WriteBuffer) Reset() { w.b = w.b[:0] }
24
25 func (w *WriteBuffer) Append(args []interface{}) error {
26 w.b = append(w.b, ArrayReply)
27 w.b = strconv.AppendUint(w.b, uint64(len(args)), 10)
28 w.b = append(w.b, '\r', '\n')
29
30 for _, arg := range args {
31 if err := w.append(arg); err != nil {
32 return err
33 }
34 }
35 return nil
36 }
37
38 func (w *WriteBuffer) append(val interface{}) error {
39 switch v := val.(type) {
40 case nil:
41 w.AppendString("")
42 case string:
43 w.AppendString(v)
44 case []byte:
45 w.AppendBytes(v)
46 case int:
47 w.AppendString(formatInt(int64(v)))
48 case int8:
49 w.AppendString(formatInt(int64(v)))
50 case int16:
51 w.AppendString(formatInt(int64(v)))
52 case int32:
53 w.AppendString(formatInt(int64(v)))
54 case int64:
55 w.AppendString(formatInt(v))
56 case uint:
57 w.AppendString(formatUint(uint64(v)))
58 case uint8:
59 w.AppendString(formatUint(uint64(v)))
60 case uint16:
61 w.AppendString(formatUint(uint64(v)))
62 case uint32:
63 w.AppendString(formatUint(uint64(v)))
64 case uint64:
65 w.AppendString(formatUint(v))
66 case float32:
67 w.AppendString(formatFloat(float64(v)))
68 case float64:
69 w.AppendString(formatFloat(v))
70 case bool:
71 if v {
72 w.AppendString("1")
73 } else {
74 w.AppendString("0")
75 }
76 default:
77 if bm, ok := val.(encoding.BinaryMarshaler); ok {
78 bb, err := bm.MarshalBinary()
79 if err != nil {
80 return err
81 }
82 w.AppendBytes(bb)
83 } else {
84 return fmt.Errorf(
85 "redis: can't marshal %T (consider implementing encoding.BinaryMarshaler)", val)
86 }
87 }
88 return nil
89 }
90
91 func (w *WriteBuffer) AppendString(s string) {
92 w.b = append(w.b, StringReply)
93 w.b = strconv.AppendUint(w.b, uint64(len(s)), 10)
94 w.b = append(w.b, '\r', '\n')
95 w.b = append(w.b, s...)
96 w.b = append(w.b, '\r', '\n')
97 }
98
99 func (w *WriteBuffer) AppendBytes(p []byte) {
100 w.b = append(w.b, StringReply)
101 w.b = strconv.AppendUint(w.b, uint64(len(p)), 10)
102 w.b = append(w.b, '\r', '\n')
103 w.b = append(w.b, p...)
104 w.b = append(w.b, '\r', '\n')
105 }