reflect_json_raw_message.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. *((*json.RawMessage)(ptr)) = json.RawMessage(iter.SkipAndReturnBytes())
  31. }
  32. func (codec *jsonRawMessageCodec) Encode(ptr unsafe.Pointer, stream *Stream) {
  33. stream.WriteRaw(string(*((*json.RawMessage)(ptr))))
  34. }
  35. func (codec *jsonRawMessageCodec) IsEmpty(ptr unsafe.Pointer) bool {
  36. return len(*((*json.RawMessage)(ptr))) == 0
  37. }
  38. type jsoniterRawMessageCodec struct {
  39. }
  40. func (codec *jsoniterRawMessageCodec) Decode(ptr unsafe.Pointer, iter *Iterator) {
  41. *((*RawMessage)(ptr)) = RawMessage(iter.SkipAndReturnBytes())
  42. }
  43. func (codec *jsoniterRawMessageCodec) Encode(ptr unsafe.Pointer, stream *Stream) {
  44. stream.WriteRaw(string(*((*RawMessage)(ptr))))
  45. }
  46. func (codec *jsoniterRawMessageCodec) IsEmpty(ptr unsafe.Pointer) bool {
  47. return len(*((*RawMessage)(ptr))) == 0
  48. }