PageRenderTime 56ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/format.go

http://github.com/simonz05/exp-godis
Go | 95 lines | 70 code | 17 blank | 8 comment | 6 complexity | c5139c155b91b36d61063337df0e7cd2 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. package godis
  2. import (
  3. "bytes"
  4. "fmt"
  5. "strconv"
  6. )
  7. const (
  8. cr byte = 13
  9. lf byte = 10
  10. dollar byte = 36
  11. colon byte = 58
  12. minus byte = 45
  13. plus byte = 43
  14. star byte = 42
  15. )
  16. var (
  17. delim = []byte{cr, lf}
  18. )
  19. func intlen(n int) int {
  20. l := 1
  21. if n < 0 {
  22. n = -n
  23. l++
  24. }
  25. n /= 10
  26. for n > 9 {
  27. l++
  28. n /= 10
  29. }
  30. return l
  31. }
  32. func arglen(arg []byte) int {
  33. // $ datalen \r\n data \r\n
  34. return 1 + intlen(len(arg)) + 2 + len(arg) + 2
  35. }
  36. /* Build a new command by concencate an array
  37. * of bytes which create a redis command.
  38. * Returns a byte array */
  39. func formatArgs(args [][]byte) []byte {
  40. // * args count \r\n
  41. n := 1 + intlen(len(args)) + 2
  42. for i := 0; i < len(args); i++ {
  43. n += arglen(args[i])
  44. }
  45. buf := make([]byte, 0, n)
  46. buf = append(buf, star)
  47. buf = strconv.AppendUint(buf, uint64(len(args)), 10)
  48. buf = append(buf, delim...)
  49. for _, arg := range args {
  50. buf = append(buf, dollar)
  51. buf = strconv.AppendUint(buf, uint64(len(arg)), 10)
  52. buf = append(buf, delim...)
  53. buf = append(buf, arg...)
  54. buf = append(buf, delim...)
  55. }
  56. return buf
  57. }
  58. /* Build a new command by concencate an array
  59. * of strings which create a redis command.
  60. * Returns a byte array */
  61. func format(args ...interface{}) []byte {
  62. buf := make([][]byte, len(args))
  63. for i, arg := range args {
  64. switch v := arg.(type) {
  65. case []byte:
  66. buf[i] = v
  67. case nil:
  68. buf[i] = []byte(nil)
  69. case string:
  70. buf[i] = []byte(v)
  71. default:
  72. var b bytes.Buffer
  73. fmt.Fprint(&b, v)
  74. buf[i] = b.Bytes()
  75. }
  76. }
  77. return formatArgs(buf)
  78. }