github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/perf/json/impl.go (about) 1 package json 2 3 import ( 4 "bytes" 5 "io" 6 "sync/atomic" 7 ) 8 9 // Implementation is the interface of an underlying JSON implementation. 10 // User can change the underlying implementation on-the-fly at runtime. 11 type Implementation interface { 12 Marshal(v any) ([]byte, error) 13 MarshalIndent(v any, prefix, indent string) ([]byte, error) 14 Unmarshal(data []byte, v any) error 15 Valid(data []byte) bool 16 17 MarshalToString(v any) (string, error) 18 UnmarshalFromString(data string, v any) error 19 20 Compact(dst *bytes.Buffer, src []byte) error 21 HTMLEscape(dst *bytes.Buffer, src []byte) 22 Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error 23 24 MarshalFastest(v any) ([]byte, error) 25 MarshalNoHTMLEscape(v any, prefix, indent string) ([]byte, error) 26 27 NewEncoder(w io.Writer) UnderlyingEncoder 28 NewDecoder(r io.Reader) UnderlyingDecoder 29 } 30 31 type UnderlyingEncoder interface { 32 Encode(val interface{}) error 33 SetEscapeHTML(on bool) 34 SetIndent(prefix, indent string) 35 } 36 37 type UnderlyingDecoder interface { 38 Decode(val interface{}) error 39 Buffered() io.Reader 40 DisallowUnknownFields() 41 More() bool 42 UseNumber() 43 } 44 45 var globalImpl atomic.Pointer[Implementation] 46 47 func init() { 48 globalImpl.Store(&DefaultJSONIteratorImpl) 49 } 50 51 func getImpl() Implementation { 52 return *globalImpl.Load() 53 } 54 55 // ChangeImpl changes the underlying JSON implementation on-the-fly 56 // at runtime. 57 // 58 // You may see github.com/jxskiss/gopkg/_examples/perf/json/bytedance_sonic 59 // for an example to use github.com/bytedance/sonic as the underlying 60 // implementation. 61 func ChangeImpl(impl Implementation) { 62 globalImpl.Store(&impl) 63 }