You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

115 lines
2.2 KiB

  1. package msgpack
  2. import (
  3. "reflect"
  4. "github.com/vmihailenco/msgpack/codes"
  5. )
  6. func encodeStringValue(e *Encoder, v reflect.Value) error {
  7. return e.EncodeString(v.String())
  8. }
  9. func encodeByteSliceValue(e *Encoder, v reflect.Value) error {
  10. return e.EncodeBytes(v.Bytes())
  11. }
  12. func encodeByteArrayValue(e *Encoder, v reflect.Value) error {
  13. if err := e.EncodeBytesLen(v.Len()); err != nil {
  14. return err
  15. }
  16. if v.CanAddr() {
  17. b := v.Slice(0, v.Len()).Bytes()
  18. return e.write(b)
  19. }
  20. b := make([]byte, v.Len())
  21. reflect.Copy(reflect.ValueOf(b), v)
  22. return e.write(b)
  23. }
  24. func (e *Encoder) EncodeBytesLen(l int) error {
  25. if l < 256 {
  26. return e.write1(codes.Bin8, uint64(l))
  27. }
  28. if l < 65536 {
  29. return e.write2(codes.Bin16, uint64(l))
  30. }
  31. return e.write4(codes.Bin32, uint32(l))
  32. }
  33. func (e *Encoder) encodeStrLen(l int) error {
  34. if l < 32 {
  35. return e.writeCode(codes.FixedStrLow | codes.Code(l))
  36. }
  37. if l < 256 {
  38. return e.write1(codes.Str8, uint64(l))
  39. }
  40. if l < 65536 {
  41. return e.write2(codes.Str16, uint64(l))
  42. }
  43. return e.write4(codes.Str32, uint32(l))
  44. }
  45. func (e *Encoder) EncodeString(v string) error {
  46. if err := e.encodeStrLen(len(v)); err != nil {
  47. return err
  48. }
  49. return e.writeString(v)
  50. }
  51. func (e *Encoder) EncodeBytes(v []byte) error {
  52. if v == nil {
  53. return e.EncodeNil()
  54. }
  55. if err := e.EncodeBytesLen(len(v)); err != nil {
  56. return err
  57. }
  58. return e.write(v)
  59. }
  60. func (e *Encoder) EncodeArrayLen(l int) error {
  61. if l < 16 {
  62. return e.writeCode(codes.FixedArrayLow | codes.Code(l))
  63. }
  64. if l < 65536 {
  65. return e.write2(codes.Array16, uint64(l))
  66. }
  67. return e.write4(codes.Array32, uint32(l))
  68. }
  69. func (e *Encoder) encodeStringSlice(s []string) error {
  70. if s == nil {
  71. return e.EncodeNil()
  72. }
  73. if err := e.EncodeArrayLen(len(s)); err != nil {
  74. return err
  75. }
  76. for _, v := range s {
  77. if err := e.EncodeString(v); err != nil {
  78. return err
  79. }
  80. }
  81. return nil
  82. }
  83. func encodeSliceValue(e *Encoder, v reflect.Value) error {
  84. if v.IsNil() {
  85. return e.EncodeNil()
  86. }
  87. return encodeArrayValue(e, v)
  88. }
  89. func encodeArrayValue(e *Encoder, v reflect.Value) error {
  90. l := v.Len()
  91. if err := e.EncodeArrayLen(l); err != nil {
  92. return err
  93. }
  94. for i := 0; i < l; i++ {
  95. if err := e.EncodeValue(v.Index(i)); err != nil {
  96. return err
  97. }
  98. }
  99. return nil
  100. }