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

305 lines
8.3 KiB
Go
Raw Normal View History

2017-06-13 10:58:53 +02:00
package jsoniter
import (
2017-06-19 17:43:53 +02:00
"encoding/json"
2017-06-17 15:11:23 +02:00
"errors"
2017-06-13 11:47:40 +02:00
"io"
2017-06-13 10:58:53 +02:00
"reflect"
"sync/atomic"
"unsafe"
)
2017-07-09 10:09:23 +02:00
// Config customize how the API should behave.
// The API is created from Config by Froze.
2017-06-13 10:58:53 +02:00
type Config struct {
2017-06-20 18:26:18 +02:00
IndentionStep int
MarshalFloatWith6Digits bool
2017-07-09 10:09:23 +02:00
EscapeHTML bool
2017-06-20 18:26:18 +02:00
SortMapKeys bool
UseNumber bool
}
type frozenConfig struct {
2017-06-16 10:46:30 +02:00
configBeforeFrozen Config
sortMapKeys bool
indentionStep int
decoderCache unsafe.Pointer
encoderCache unsafe.Pointer
extensions []Extension
2017-06-17 08:23:02 +02:00
streamPool chan *Stream
iteratorPool chan *Iterator
2017-06-13 10:58:53 +02:00
}
2017-07-09 10:09:23 +02:00
// API the public interface of this package.
// Primary Marshal and Unmarshal.
type API interface {
IteratorPool
StreamPool
MarshalToString(v interface{}) (string, error)
Marshal(v interface{}) ([]byte, error)
2017-06-29 14:48:27 +02:00
MarshalIndent(v interface{}, prefix, indent string) ([]byte, error)
UnmarshalFromString(str string, v interface{}) error
Unmarshal(data []byte, v interface{}) error
Get(data []byte, path ...interface{}) Any
NewEncoder(writer io.Writer) *Encoder
NewDecoder(reader io.Reader) *Decoder
}
2017-07-09 10:09:23 +02:00
// ConfigDefault the default API
var ConfigDefault = Config{
2017-07-09 10:09:23 +02:00
EscapeHTML: true,
}.Froze()
2017-06-15 17:54:43 +02:00
2017-07-09 10:09:23 +02:00
// ConfigCompatibleWithStandardLibrary tries to be 100% compatible with standard library behavior
2017-06-15 17:54:43 +02:00
var ConfigCompatibleWithStandardLibrary = Config{
2017-07-09 10:09:23 +02:00
EscapeHTML: true,
2017-06-16 10:46:30 +02:00
SortMapKeys: true,
2017-06-15 17:54:43 +02:00
}.Froze()
2017-06-13 10:58:53 +02:00
2017-07-09 10:09:23 +02:00
// ConfigFastest marshals float with only 6 digits precision
2017-06-17 04:21:37 +02:00
var ConfigFastest = Config{
2017-07-09 10:09:23 +02:00
EscapeHTML: false,
2017-06-17 04:21:37 +02:00
MarshalFloatWith6Digits: true,
}.Froze()
2017-07-09 10:09:23 +02:00
// Froze forge API from config
func (cfg Config) Froze() API {
2017-06-29 14:48:27 +02:00
// TODO: cache frozen config
frozenConfig := &frozenConfig{
2017-06-17 04:21:37 +02:00
sortMapKeys: cfg.SortMapKeys,
indentionStep: cfg.IndentionStep,
2017-06-17 08:23:02 +02:00
streamPool: make(chan *Stream, 16),
iteratorPool: make(chan *Iterator, 16),
}
atomic.StorePointer(&frozenConfig.decoderCache, unsafe.Pointer(&map[string]ValDecoder{}))
atomic.StorePointer(&frozenConfig.encoderCache, unsafe.Pointer(&map[string]ValEncoder{}))
if cfg.MarshalFloatWith6Digits {
frozenConfig.marshalFloatWith6Digits()
}
2017-07-09 10:09:23 +02:00
if cfg.EscapeHTML {
frozenConfig.escapeHTML()
2017-06-15 17:54:43 +02:00
}
if cfg.UseNumber {
frozenConfig.useNumber()
}
2017-06-15 18:10:05 +02:00
frozenConfig.configBeforeFrozen = cfg
return frozenConfig
2017-06-13 11:47:40 +02:00
}
func (cfg *frozenConfig) useNumber() {
cfg.addDecoderToCache(reflect.TypeOf((*interface{})(nil)).Elem(), &funcDecoder{func(ptr unsafe.Pointer, iter *Iterator) {
if iter.WhatIsNext() == Number {
*((*interface{})(ptr)) = json.Number(iter.readNumberAsString())
} else {
*((*interface{})(ptr)) = iter.Read()
}
}})
}
func (cfg *frozenConfig) registerExtension(extension Extension) {
2017-06-13 11:47:40 +02:00
cfg.extensions = append(cfg.extensions, extension)
}
2017-06-20 01:51:38 +02:00
type lossyFloat32Encoder struct {
}
2017-06-20 09:11:01 +02:00
func (encoder *lossyFloat32Encoder) Encode(ptr unsafe.Pointer, stream *Stream) {
2017-06-20 01:51:38 +02:00
stream.WriteFloat32Lossy(*((*float32)(ptr)))
}
2017-06-20 09:11:01 +02:00
func (encoder *lossyFloat32Encoder) EncodeInterface(val interface{}, stream *Stream) {
2017-06-20 11:43:47 +02:00
WriteToStream(val, stream, encoder)
2017-06-20 01:51:38 +02:00
}
2017-06-20 09:11:01 +02:00
func (encoder *lossyFloat32Encoder) IsEmpty(ptr unsafe.Pointer) bool {
2017-06-20 01:51:38 +02:00
return *((*float32)(ptr)) == 0
}
type lossyFloat64Encoder struct {
}
2017-06-20 09:11:01 +02:00
func (encoder *lossyFloat64Encoder) Encode(ptr unsafe.Pointer, stream *Stream) {
2017-06-20 01:51:38 +02:00
stream.WriteFloat64Lossy(*((*float64)(ptr)))
}
2017-06-20 09:11:01 +02:00
func (encoder *lossyFloat64Encoder) EncodeInterface(val interface{}, stream *Stream) {
2017-06-20 11:43:47 +02:00
WriteToStream(val, stream, encoder)
2017-06-20 01:51:38 +02:00
}
2017-06-20 09:11:01 +02:00
func (encoder *lossyFloat64Encoder) IsEmpty(ptr unsafe.Pointer) bool {
2017-06-20 01:51:38 +02:00
return *((*float64)(ptr)) == 0
}
2017-06-13 11:47:40 +02:00
// EnableLossyFloatMarshalling keeps 10**(-6) precision
// for float variables for better performance.
func (cfg *frozenConfig) marshalFloatWith6Digits() {
2017-06-13 11:47:40 +02:00
// for better performance
2017-06-20 01:51:38 +02:00
cfg.addEncoderToCache(reflect.TypeOf((*float32)(nil)).Elem(), &lossyFloat32Encoder{})
cfg.addEncoderToCache(reflect.TypeOf((*float64)(nil)).Elem(), &lossyFloat64Encoder{})
2017-06-13 11:47:40 +02:00
}
2017-06-20 01:46:13 +02:00
type htmlEscapedStringEncoder struct {
}
2017-06-20 09:11:01 +02:00
func (encoder *htmlEscapedStringEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
2017-06-20 01:46:13 +02:00
str := *((*string)(ptr))
stream.WriteStringWithHTMLEscaped(str)
2017-06-20 01:46:13 +02:00
}
2017-06-20 09:11:01 +02:00
func (encoder *htmlEscapedStringEncoder) EncodeInterface(val interface{}, stream *Stream) {
2017-06-20 11:43:47 +02:00
WriteToStream(val, stream, encoder)
2017-06-20 01:46:13 +02:00
}
2017-06-20 09:11:01 +02:00
func (encoder *htmlEscapedStringEncoder) IsEmpty(ptr unsafe.Pointer) bool {
2017-06-20 01:46:13 +02:00
return *((*string)(ptr)) == ""
}
2017-07-09 10:09:23 +02:00
func (cfg *frozenConfig) escapeHTML() {
2017-06-20 01:46:13 +02:00
cfg.addEncoderToCache(reflect.TypeOf((*string)(nil)).Elem(), &htmlEscapedStringEncoder{})
2017-06-15 17:54:43 +02:00
}
func (cfg *frozenConfig) addDecoderToCache(cacheKey reflect.Type, decoder ValDecoder) {
2017-06-13 10:58:53 +02:00
done := false
for !done {
ptr := atomic.LoadPointer(&cfg.decoderCache)
cache := *(*map[reflect.Type]ValDecoder)(ptr)
copied := map[reflect.Type]ValDecoder{}
2017-06-13 10:58:53 +02:00
for k, v := range cache {
copied[k] = v
}
copied[cacheKey] = decoder
done = atomic.CompareAndSwapPointer(&cfg.decoderCache, ptr, unsafe.Pointer(&copied))
}
}
func (cfg *frozenConfig) addEncoderToCache(cacheKey reflect.Type, encoder ValEncoder) {
2017-06-13 10:58:53 +02:00
done := false
for !done {
ptr := atomic.LoadPointer(&cfg.encoderCache)
cache := *(*map[reflect.Type]ValEncoder)(ptr)
copied := map[reflect.Type]ValEncoder{}
2017-06-13 10:58:53 +02:00
for k, v := range cache {
copied[k] = v
}
copied[cacheKey] = encoder
done = atomic.CompareAndSwapPointer(&cfg.encoderCache, ptr, unsafe.Pointer(&copied))
}
}
func (cfg *frozenConfig) getDecoderFromCache(cacheKey reflect.Type) ValDecoder {
2017-06-13 10:58:53 +02:00
ptr := atomic.LoadPointer(&cfg.decoderCache)
cache := *(*map[reflect.Type]ValDecoder)(ptr)
2017-06-13 10:58:53 +02:00
return cache[cacheKey]
}
func (cfg *frozenConfig) getEncoderFromCache(cacheKey reflect.Type) ValEncoder {
2017-06-13 10:58:53 +02:00
ptr := atomic.LoadPointer(&cfg.encoderCache)
cache := *(*map[reflect.Type]ValEncoder)(ptr)
2017-06-13 10:58:53 +02:00
return cache[cacheKey]
}
func (cfg *frozenConfig) cleanDecoders() {
typeDecoders = map[string]ValDecoder{}
fieldDecoders = map[string]ValDecoder{}
2017-07-09 10:09:23 +02:00
*cfg = *(cfg.configBeforeFrozen.Froze().(*frozenConfig))
2017-06-13 10:58:53 +02:00
}
func (cfg *frozenConfig) cleanEncoders() {
typeEncoders = map[string]ValEncoder{}
fieldEncoders = map[string]ValEncoder{}
2017-07-09 10:09:23 +02:00
*cfg = *(cfg.configBeforeFrozen.Froze().(*frozenConfig))
2017-06-13 10:58:53 +02:00
}
2017-06-13 11:47:40 +02:00
func (cfg *frozenConfig) MarshalToString(v interface{}) (string, error) {
2017-06-17 11:14:34 +02:00
stream := cfg.BorrowStream(nil)
defer cfg.ReturnStream(stream)
2017-06-17 08:36:05 +02:00
stream.WriteVal(v)
if stream.Error != nil {
2017-06-17 08:36:38 +02:00
return "", stream.Error
2017-06-13 11:47:40 +02:00
}
2017-06-17 08:36:05 +02:00
return string(stream.Buffer()), nil
2017-06-13 11:47:40 +02:00
}
func (cfg *frozenConfig) Marshal(v interface{}) ([]byte, error) {
2017-06-17 11:14:34 +02:00
stream := cfg.BorrowStream(nil)
defer cfg.ReturnStream(stream)
2017-06-13 11:47:40 +02:00
stream.WriteVal(v)
if stream.Error != nil {
return nil, stream.Error
}
2017-06-17 08:36:05 +02:00
result := stream.Buffer()
copied := make([]byte, len(result))
copy(copied, result)
return copied, nil
2017-06-13 11:47:40 +02:00
}
2017-06-29 14:48:27 +02:00
func (cfg *frozenConfig) MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) {
if prefix != "" {
panic("prefix is not supported")
}
for _, r := range indent {
if r != ' ' {
panic("indent can only be space")
}
}
newCfg := cfg.configBeforeFrozen
newCfg.IndentionStep = len(indent)
return newCfg.Froze().Marshal(v)
}
func (cfg *frozenConfig) UnmarshalFromString(str string, v interface{}) error {
2017-06-13 11:47:40 +02:00
data := []byte(str)
data = data[:lastNotSpacePos(data)]
2017-06-17 11:14:34 +02:00
iter := cfg.BorrowIterator(data)
defer cfg.ReturnIterator(iter)
2017-06-13 11:47:40 +02:00
iter.ReadVal(v)
if iter.head == iter.tail {
iter.loadMore()
}
if iter.Error == io.EOF {
return nil
}
if iter.Error == nil {
2017-06-20 09:11:01 +02:00
iter.ReportError("UnmarshalFromString", "there are bytes left after unmarshal")
2017-06-13 11:47:40 +02:00
}
return iter.Error
}
2017-06-15 18:10:05 +02:00
func (cfg *frozenConfig) Get(data []byte, path ...interface{}) Any {
2017-06-17 11:14:34 +02:00
iter := cfg.BorrowIterator(data)
defer cfg.ReturnIterator(iter)
return locatePath(iter, path)
2017-06-15 18:10:05 +02:00
}
func (cfg *frozenConfig) Unmarshal(data []byte, v interface{}) error {
data = data[:lastNotSpacePos(data)]
2017-06-17 11:14:34 +02:00
iter := cfg.BorrowIterator(data)
defer cfg.ReturnIterator(iter)
2017-06-15 18:10:05 +02:00
typ := reflect.TypeOf(v)
if typ.Kind() != reflect.Ptr {
// return non-pointer error
return errors.New("the second param must be ptr type")
}
iter.ReadVal(v)
if iter.head == iter.tail {
iter.loadMore()
}
if iter.Error == io.EOF {
return nil
}
if iter.Error == nil {
2017-06-20 09:11:01 +02:00
iter.ReportError("Unmarshal", "there are bytes left after unmarshal")
2017-06-15 18:10:05 +02:00
}
return iter.Error
2017-06-16 10:46:30 +02:00
}
2017-06-17 08:23:02 +02:00
func (cfg *frozenConfig) NewEncoder(writer io.Writer) *Encoder {
2017-06-17 08:23:02 +02:00
stream := NewStream(cfg, writer, 512)
return &Encoder{stream}
2017-06-17 08:23:02 +02:00
}
func (cfg *frozenConfig) NewDecoder(reader io.Reader) *Decoder {
2017-06-17 08:23:02 +02:00
iter := Parse(cfg, reader, 512)
return &Decoder{iter}
2017-06-17 08:23:02 +02:00
}