1
0
mirror of https://github.com/json-iterator/go.git synced 2025-06-21 23:07:33 +02:00

add stream

This commit is contained in:
Tao Wen
2017-01-07 12:28:16 +08:00
parent 5af8cc4b09
commit 6f57d41461
8 changed files with 394 additions and 43 deletions

View File

@ -3,6 +3,7 @@ package jsoniter
import (
"io"
"unsafe"
"bytes"
)
// Unmarshal adapts to json/encoding APIs
@ -15,7 +16,8 @@ func Unmarshal(data []byte, v interface{}) error {
return iter.Error
}
func UnmarshalString(str string, v interface{}) error {
func UnmarshalFromString(str string, v interface{}) error {
// safe to do the unsafe cast here, as str is always referenced in this scope
data := *(*[]byte)(unsafe.Pointer(&str))
iter := ParseBytes(data)
iter.Read(v)
@ -24,3 +26,21 @@ func UnmarshalString(str string, v interface{}) error {
}
return iter.Error
}
func Marshal(v interface{}) ([]byte, error) {
buf := &bytes.Buffer{}
stream := NewStream(buf, 4096)
stream.WriteVal(v)
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
}