feature_adapter.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package jsoniter
  2. import (
  3. "io"
  4. "unsafe"
  5. "bytes"
  6. )
  7. // Unmarshal adapts to json/encoding APIs
  8. func Unmarshal(data []byte, v interface{}) error {
  9. iter := ParseBytes(data)
  10. iter.ReadVal(v)
  11. if iter.Error == io.EOF {
  12. return nil
  13. }
  14. if iter.Error == nil {
  15. iter.reportError("UnmarshalAny", "there are bytes left after unmarshal")
  16. }
  17. return iter.Error
  18. }
  19. func UnmarshalAny(data []byte) (Any, error) {
  20. iter := ParseBytes(data)
  21. any := iter.ReadAny()
  22. if iter.Error == io.EOF {
  23. return any, nil
  24. }
  25. if iter.Error == nil {
  26. iter.reportError("UnmarshalAny", "there are bytes left after unmarshal")
  27. }
  28. return any, iter.Error
  29. }
  30. func UnmarshalFromString(str string, v interface{}) error {
  31. // safe to do the unsafe cast here, as str is always referenced in this scope
  32. data := *(*[]byte)(unsafe.Pointer(&str))
  33. iter := ParseBytes(data)
  34. iter.ReadVal(v)
  35. if iter.Error == io.EOF {
  36. return nil
  37. }
  38. if iter.Error == nil {
  39. iter.reportError("UnmarshalFromString", "there are bytes left after unmarshal")
  40. }
  41. return iter.Error
  42. }
  43. func UnmarshalAnyFromString(str string) (Any, error) {
  44. // safe to do the unsafe cast here, as str is always referenced in this scope
  45. data := *(*[]byte)(unsafe.Pointer(&str))
  46. iter := ParseBytes(data)
  47. any := iter.ReadAny()
  48. if iter.Error == io.EOF {
  49. return any, nil
  50. }
  51. if iter.Error == nil {
  52. iter.reportError("UnmarshalAnyFromString", "there are bytes left after unmarshal")
  53. }
  54. return nil, iter.Error
  55. }
  56. func Marshal(v interface{}) ([]byte, error) {
  57. buf := &bytes.Buffer{}
  58. stream := NewStream(buf, 4096)
  59. stream.WriteVal(v)
  60. stream.Flush()
  61. if stream.Error != nil {
  62. return nil, stream.Error
  63. }
  64. return buf.Bytes(), nil
  65. }
  66. func MarshalToString(v interface{}) (string, error) {
  67. buf, err := Marshal(v)
  68. if err != nil {
  69. return "", err
  70. }
  71. return string(buf), nil
  72. }