feature_adapter.go 886 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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.Read(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.Read(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. if stream.Error != nil {
  31. return nil, stream.Error
  32. }
  33. return buf.Bytes(), nil
  34. }
  35. func MarshalToString(v interface{}) (string, error) {
  36. buf, err := Marshal(v)
  37. if err != nil {
  38. return "", err
  39. }
  40. return string(buf), nil
  41. }