1
0
mirror of https://github.com/json-iterator/go.git synced 2024-11-27 08:30:57 +02:00
json-iterator/feature_adapter.go

47 lines
908 B
Go
Raw Normal View History

2016-12-04 16:50:53 +02:00
package jsoniter
2017-01-06 14:17:47 +02:00
import (
"io"
"unsafe"
2017-01-07 06:28:16 +02:00
"bytes"
2017-01-06 14:17:47 +02:00
)
2016-12-05 07:20:27 +02:00
// Unmarshal adapts to json/encoding APIs
2016-12-04 16:50:53 +02:00
func Unmarshal(data []byte, v interface{}) error {
iter := ParseBytes(data)
2017-01-09 11:47:21 +02:00
iter.ReadVal(v)
2016-12-05 07:20:27 +02:00
if iter.Error == io.EOF {
return nil
}
2016-12-04 16:50:53 +02:00
return iter.Error
}
2017-01-06 14:17:47 +02:00
2017-01-07 06:28:16 +02:00
func UnmarshalFromString(str string, v interface{}) error {
// safe to do the unsafe cast here, as str is always referenced in this scope
2017-01-06 14:17:47 +02:00
data := *(*[]byte)(unsafe.Pointer(&str))
iter := ParseBytes(data)
2017-01-09 11:47:21 +02:00
iter.ReadVal(v)
2017-01-06 14:17:47 +02:00
if iter.Error == io.EOF {
return nil
}
return iter.Error
}
2017-01-07 06:28:16 +02:00
func Marshal(v interface{}) ([]byte, error) {
buf := &bytes.Buffer{}
stream := NewStream(buf, 4096)
stream.WriteVal(v)
2017-01-09 13:19:48 +02:00
stream.Flush()
2017-01-07 06:28:16 +02:00
if stream.Error != nil {
return nil, stream.Error
}
return buf.Bytes(), nil
}
func MarshalToString(v interface{}) (string, error) {
buf, err := Marshal(v)
if err != nil {
return "", err
}
return string(buf), nil
}