feature_adapter.go 908 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. return iter.Error
  15. }
  16. func UnmarshalFromString(str string, v interface{}) error {
  17. // safe to do the unsafe cast here, as str is always referenced in this scope
  18. data := *(*[]byte)(unsafe.Pointer(&str))
  19. iter := ParseBytes(data)
  20. iter.ReadVal(v)
  21. if iter.Error == io.EOF {
  22. return nil
  23. }
  24. return iter.Error
  25. }
  26. func Marshal(v interface{}) ([]byte, error) {
  27. buf := &bytes.Buffer{}
  28. stream := NewStream(buf, 4096)
  29. stream.WriteVal(v)
  30. stream.Flush()
  31. if stream.Error != nil {
  32. return nil, stream.Error
  33. }
  34. return buf.Bytes(), nil
  35. }
  36. func MarshalToString(v interface{}) (string, error) {
  37. buf, err := Marshal(v)
  38. if err != nil {
  39. return "", err
  40. }
  41. return string(buf), nil
  42. }