1
0
mirror of https://github.com/json-iterator/go.git synced 2024-11-24 08:22:14 +02:00
json-iterator/config.go

376 lines
10 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"
2018-02-24 16:04:41 +02:00
"io"
"reflect"
2018-02-22 04:29:29 +02:00
"sync"
2018-02-24 16:04:41 +02:00
"unsafe"
"github.com/modern-go/concurrent"
"github.com/modern-go/reflect2"
2017-06-13 10:58:53 +02:00
)
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 {
IndentionStep int
MarshalFloatWith6Digits bool
EscapeHTML bool
SortMapKeys bool
UseNumber bool
DisallowUnknownFields bool
TagKey string
OnlyTaggedField bool
ValidateJsonRawMessage bool
ObjectFieldMustBeSimpleString bool
CaseSensitive bool
}
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-10-10 02:57:02 +02:00
Valid(data []byte) bool
2017-11-22 18:09:35 +02:00
RegisterExtension(extension Extension)
2018-03-14 17:18:20 +02:00
DecoderOf(typ reflect2.Type) ValDecoder
EncoderOf(typ reflect2.Type) ValEncoder
}
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{
EscapeHTML: true,
SortMapKeys: true,
ValidateJsonRawMessage: 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{
EscapeHTML: false,
MarshalFloatWith6Digits: true, // will lose precession
ObjectFieldMustBeSimpleString: true, // do not unescape object field
2017-06-17 04:21:37 +02:00
}.Froze()
2018-02-28 11:11:57 +02:00
type frozenConfig struct {
configBeforeFrozen Config
sortMapKeys bool
indentionStep int
objectFieldMustBeSimpleString bool
onlyTaggedField bool
disallowUnknownFields bool
decoderCache *concurrent.Map
encoderCache *concurrent.Map
2018-07-22 05:51:51 +02:00
encoderExtension Extension
decoderExtension Extension
extraExtensions []Extension
2018-02-28 11:11:57 +02:00
streamPool *sync.Pool
iteratorPool *sync.Pool
caseSensitive bool
2018-02-28 11:11:57 +02:00
}
func (cfg *frozenConfig) initCache() {
cfg.decoderCache = concurrent.NewMap()
cfg.encoderCache = concurrent.NewMap()
}
func (cfg *frozenConfig) addDecoderToCache(cacheKey uintptr, decoder ValDecoder) {
cfg.decoderCache.Store(cacheKey, decoder)
}
func (cfg *frozenConfig) addEncoderToCache(cacheKey uintptr, encoder ValEncoder) {
cfg.encoderCache.Store(cacheKey, encoder)
}
func (cfg *frozenConfig) getDecoderFromCache(cacheKey uintptr) ValDecoder {
decoder, found := cfg.decoderCache.Load(cacheKey)
if found {
return decoder.(ValDecoder)
}
return nil
}
func (cfg *frozenConfig) getEncoderFromCache(cacheKey uintptr) ValEncoder {
encoder, found := cfg.encoderCache.Load(cacheKey)
if found {
return encoder.(ValEncoder)
}
return nil
}
2018-02-28 14:29:23 +02:00
var cfgCache = concurrent.NewMap()
2018-02-28 11:11:57 +02:00
func getFrozenConfigFromCache(cfg Config) *frozenConfig {
obj, found := cfgCache.Load(cfg)
if found {
return obj.(*frozenConfig)
}
return nil
}
func addFrozenConfigToCache(cfg Config, frozenConfig *frozenConfig) {
cfgCache.Store(cfg, frozenConfig)
}
2017-07-09 10:09:23 +02:00
// Froze forge API from config
func (cfg Config) Froze() API {
2018-02-05 16:26:39 +02:00
api := &frozenConfig{
sortMapKeys: cfg.SortMapKeys,
indentionStep: cfg.IndentionStep,
objectFieldMustBeSimpleString: cfg.ObjectFieldMustBeSimpleString,
onlyTaggedField: cfg.OnlyTaggedField,
disallowUnknownFields: cfg.DisallowUnknownFields,
caseSensitive: cfg.CaseSensitive,
2018-02-22 04:29:29 +02:00
}
api.streamPool = &sync.Pool{
New: func() interface{} {
return NewStream(api, nil, 512)
},
}
api.iteratorPool = &sync.Pool{
New: func() interface{} {
return NewIterator(api)
},
}
2018-02-05 15:43:37 +02:00
api.initCache()
2018-02-18 15:14:37 +02:00
encoderExtension := EncoderExtension{}
decoderExtension := DecoderExtension{}
if cfg.MarshalFloatWith6Digits {
2018-02-18 15:14:37 +02:00
api.marshalFloatWith6Digits(encoderExtension)
}
2017-07-09 10:09:23 +02:00
if cfg.EscapeHTML {
api.escapeHTML(encoderExtension)
2017-06-15 17:54:43 +02:00
}
if cfg.UseNumber {
2018-02-18 15:14:37 +02:00
api.useNumber(decoderExtension)
}
if cfg.ValidateJsonRawMessage {
2018-02-18 15:14:37 +02:00
api.validateJsonRawMessage(encoderExtension)
}
2018-07-22 05:51:51 +02:00
api.encoderExtension = encoderExtension
api.decoderExtension = decoderExtension
2018-02-05 15:43:37 +02:00
api.configBeforeFrozen = cfg
2018-02-05 16:26:39 +02:00
return api
}
2018-07-22 05:51:51 +02:00
func (cfg Config) frozeWithCacheReuse(extraExtensions []Extension) *frozenConfig {
2018-02-05 16:26:39 +02:00
api := getFrozenConfigFromCache(cfg)
if api != nil {
return api
}
api = cfg.Froze().(*frozenConfig)
2018-07-22 05:51:51 +02:00
for _, extension := range extraExtensions {
api.RegisterExtension(extension)
}
2018-02-05 15:43:37 +02:00
addFrozenConfigToCache(cfg, api)
return api
2017-06-13 11:47:40 +02:00
}
2018-02-18 15:14:37 +02:00
func (cfg *frozenConfig) validateJsonRawMessage(extension EncoderExtension) {
encoder := &funcEncoder{func(ptr unsafe.Pointer, stream *Stream) {
rawMessage := *(*json.RawMessage)(ptr)
iter := cfg.BorrowIterator([]byte(rawMessage))
2020-01-14 08:14:02 +02:00
defer cfg.ReturnIterator(iter)
iter.Read()
2020-01-14 08:14:02 +02:00
if iter.Error != nil && iter.Error != io.EOF {
stream.WriteRaw("null")
} else {
stream.WriteRaw(string(rawMessage))
}
}, func(ptr unsafe.Pointer) bool {
return len(*((*json.RawMessage)(ptr))) == 0
}}
2018-02-22 04:12:08 +02:00
extension[reflect2.TypeOfPtr((*json.RawMessage)(nil)).Elem()] = encoder
extension[reflect2.TypeOfPtr((*RawMessage)(nil)).Elem()] = encoder
}
2018-02-18 15:14:37 +02:00
func (cfg *frozenConfig) useNumber(extension DecoderExtension) {
2018-02-22 04:12:08 +02:00
extension[reflect2.TypeOfPtr((*interface{})(nil)).Elem()] = &funcDecoder{func(ptr unsafe.Pointer, iter *Iterator) {
exitingValue := *((*interface{})(ptr))
if exitingValue != nil && reflect.TypeOf(exitingValue).Kind() == reflect.Ptr {
iter.ReadVal(exitingValue)
return
}
if iter.WhatIsNext() == NumberValue {
*((*interface{})(ptr)) = json.Number(iter.readNumberAsString())
} else {
*((*interface{})(ptr)) = iter.Read()
}
2018-02-18 15:14:37 +02:00
}}
}
2017-08-21 18:12:09 +02:00
func (cfg *frozenConfig) getTagKey() string {
tagKey := cfg.configBeforeFrozen.TagKey
if tagKey == "" {
return "json"
}
return tagKey
}
2017-11-22 18:09:35 +02:00
func (cfg *frozenConfig) RegisterExtension(extension Extension) {
2018-07-22 05:51:51 +02:00
cfg.extraExtensions = append(cfg.extraExtensions, extension)
copied := cfg.configBeforeFrozen
cfg.configBeforeFrozen = copied
2017-06-13 11:47:40 +02:00
}
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) 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) 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.
2018-02-18 15:14:37 +02:00
func (cfg *frozenConfig) marshalFloatWith6Digits(extension EncoderExtension) {
2017-06-13 11:47:40 +02:00
// for better performance
2018-02-22 04:12:08 +02:00
extension[reflect2.TypeOfPtr((*float32)(nil)).Elem()] = &lossyFloat32Encoder{}
extension[reflect2.TypeOfPtr((*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) IsEmpty(ptr unsafe.Pointer) bool {
2017-06-20 01:46:13 +02:00
return *((*string)(ptr)) == ""
}
func (cfg *frozenConfig) escapeHTML(encoderExtension EncoderExtension) {
2018-02-22 04:12:08 +02:00
encoderExtension[reflect2.TypeOfPtr((*string)(nil)).Elem()] = &htmlEscapedStringEncoder{}
2017-06-15 17:54:43 +02:00
}
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)
2018-07-22 05:51:51 +02:00
return newCfg.frozeWithCacheReuse(cfg.extraExtensions).Marshal(v)
2017-06-29 14:48:27 +02:00
}
func (cfg *frozenConfig) UnmarshalFromString(str string, v interface{}) error {
2017-06-13 11:47:40 +02:00
data := []byte(str)
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)
2018-02-22 04:37:32 +02:00
c := iter.nextToken()
if c == 0 {
if iter.Error == io.EOF {
return nil
}
return iter.Error
2017-06-13 11:47:40 +02:00
}
2018-02-22 04:37:32 +02:00
iter.ReportError("Unmarshal", "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 {
2017-06-17 11:14:34 +02:00
iter := cfg.BorrowIterator(data)
defer cfg.ReturnIterator(iter)
2017-06-15 18:10:05 +02:00
iter.ReadVal(v)
2018-02-22 04:37:32 +02:00
c := iter.nextToken()
if c == 0 {
if iter.Error == io.EOF {
return nil
}
return iter.Error
2017-06-15 18:10:05 +02:00
}
2018-02-22 04:37:32 +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
}
2017-10-10 02:57:02 +02:00
func (cfg *frozenConfig) Valid(data []byte) bool {
iter := cfg.BorrowIterator(data)
defer cfg.ReturnIterator(iter)
iter.Skip()
return iter.Error == nil
}