reflect_json_raw_message.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package jsoniter
  2. import (
  3. "encoding/json"
  4. "github.com/modern-go/reflect2"
  5. "unsafe"
  6. )
  7. var jsonRawMessageType = reflect2.TypeOfPtr((*json.RawMessage)(nil)).Elem()
  8. var jsoniterRawMessageType = reflect2.TypeOfPtr((*RawMessage)(nil)).Elem()
  9. func createEncoderOfJsonRawMessage(ctx *ctx, typ reflect2.Type) ValEncoder {
  10. if typ == jsonRawMessageType {
  11. return &jsonRawMessageCodec{}
  12. }
  13. if typ == jsoniterRawMessageType {
  14. return &jsoniterRawMessageCodec{}
  15. }
  16. return nil
  17. }
  18. func createDecoderOfJsonRawMessage(ctx *ctx, typ reflect2.Type) ValDecoder {
  19. if typ == jsonRawMessageType {
  20. return &jsonRawMessageCodec{}
  21. }
  22. if typ == jsoniterRawMessageType {
  23. return &jsoniterRawMessageCodec{}
  24. }
  25. return nil
  26. }
  27. type jsonRawMessageCodec struct {
  28. }
  29. func (codec *jsonRawMessageCodec) Decode(ptr unsafe.Pointer, iter *Iterator) {
  30. if iter.ReadNil() {
  31. *((*json.RawMessage)(ptr)) = nil
  32. } else {
  33. *((*json.RawMessage)(ptr)) = iter.SkipAndReturnBytes()
  34. }
  35. }
  36. func (codec *jsonRawMessageCodec) Encode(ptr unsafe.Pointer, stream *Stream) {
  37. if *((*json.RawMessage)(ptr)) == nil {
  38. stream.WriteNil()
  39. } else {
  40. stream.WriteRaw(string(*((*json.RawMessage)(ptr))))
  41. }
  42. }
  43. func (codec *jsonRawMessageCodec) IsEmpty(ptr unsafe.Pointer) bool {
  44. return len(*((*json.RawMessage)(ptr))) == 0
  45. }
  46. type jsoniterRawMessageCodec struct {
  47. }
  48. func (codec *jsoniterRawMessageCodec) Decode(ptr unsafe.Pointer, iter *Iterator) {
  49. if iter.ReadNil() {
  50. *((*RawMessage)(ptr)) = nil
  51. } else {
  52. *((*RawMessage)(ptr)) = iter.SkipAndReturnBytes()
  53. }
  54. }
  55. func (codec *jsoniterRawMessageCodec) Encode(ptr unsafe.Pointer, stream *Stream) {
  56. if *((*RawMessage)(ptr)) == nil {
  57. stream.WriteNil()
  58. } else {
  59. stream.WriteRaw(string(*((*RawMessage)(ptr))))
  60. }
  61. }
  62. func (codec *jsoniterRawMessageCodec) IsEmpty(ptr unsafe.Pointer) bool {
  63. return len(*((*RawMessage)(ptr))) == 0
  64. }