write_buffer.go 2.1 KB

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