github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/perf/json/jsoniter.go (about) 1 package json 2 3 import ( 4 "bytes" 5 "io" 6 7 jsoniter "github.com/json-iterator/go" 8 ) 9 10 // DefaultJSONIteratorImpl uses [jsoniter.ConfigCompatibleWithStandardLibrary] 11 // as the underlying implementation. 12 var DefaultJSONIteratorImpl = NewJSONIteratorImpl( 13 jsoniter.ConfigCompatibleWithStandardLibrary, true) 14 15 // NewJSONIteratorImpl returns an implementation which uses api as the 16 // underlying config. 17 // If useConfigFastest is true, it uses [jsoniter.ConfigFastest] 18 // for method MarshalFastest, else it uses api.Marshal. 19 func NewJSONIteratorImpl(api jsoniter.API, useConfigFastest bool) Implementation { 20 impl := &jsoniterImpl{ 21 api: api, 22 marshalFastest: api.Marshal, 23 } 24 if useConfigFastest { 25 impl.marshalFastest = jsoniter.ConfigFastest.Marshal 26 } 27 return impl 28 } 29 30 type jsoniterImpl struct { 31 api jsoniter.API 32 marshalFastest func(v any) ([]byte, error) 33 } 34 35 func (impl jsoniterImpl) Marshal(v any) ([]byte, error) { 36 return impl.api.Marshal(v) 37 } 38 39 func (impl jsoniterImpl) MarshalIndent(v any, prefix, indent string) ([]byte, error) { 40 return impl.api.MarshalIndent(v, prefix, indent) 41 } 42 43 func (impl jsoniterImpl) Unmarshal(data []byte, v any) error { 44 return impl.api.Unmarshal(data, v) 45 } 46 47 func (impl jsoniterImpl) Valid(data []byte) bool { 48 return impl.api.Valid(data) 49 } 50 51 func (impl jsoniterImpl) MarshalToString(v any) (string, error) { 52 return impl.api.MarshalToString(v) 53 } 54 55 func (impl jsoniterImpl) UnmarshalFromString(data string, v any) error { 56 return impl.api.UnmarshalFromString(data, v) 57 } 58 59 func (impl jsoniterImpl) Compact(dst *bytes.Buffer, src []byte) error { 60 return StdImpl.Compact(dst, src) 61 } 62 63 func (impl jsoniterImpl) HTMLEscape(dst *bytes.Buffer, src []byte) { 64 StdImpl.HTMLEscape(dst, src) 65 } 66 67 func (impl jsoniterImpl) Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error { 68 return StdImpl.Indent(dst, src, prefix, indent) 69 } 70 71 func (impl jsoniterImpl) MarshalFastest(v any) ([]byte, error) { 72 return impl.marshalFastest(v) 73 } 74 75 func (impl jsoniterImpl) MarshalNoHTMLEscape(v any, prefix, indent string) ([]byte, error) { 76 return StdImpl.MarshalNoHTMLEscape(v, prefix, indent) 77 } 78 79 func (impl jsoniterImpl) NewEncoder(w io.Writer) UnderlyingEncoder { 80 return impl.api.NewEncoder(w) 81 } 82 83 func (impl jsoniterImpl) NewDecoder(r io.Reader) UnderlyingDecoder { 84 return impl.api.NewDecoder(r) 85 }