github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/perf/json/std.go (about)

     1  package json
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"io"
     7  
     8  	"github.com/jxskiss/gopkg/v2/internal/unsafeheader"
     9  )
    10  
    11  // StdImpl uses package "encoding/json" in the standard library
    12  // as the underlying implementation.
    13  var StdImpl Implementation = stdImpl{}
    14  
    15  type stdImpl struct{}
    16  
    17  func (stdImpl) Marshal(v any) ([]byte, error) {
    18  	return json.Marshal(v)
    19  }
    20  
    21  func (stdImpl) MarshalIndent(v any, prefix, indent string) ([]byte, error) {
    22  	return json.MarshalIndent(v, prefix, indent)
    23  }
    24  
    25  func (stdImpl) Unmarshal(data []byte, v any) error {
    26  	return json.Unmarshal(data, v)
    27  }
    28  
    29  func (stdImpl) Valid(data []byte) bool {
    30  	return json.Valid(data)
    31  }
    32  
    33  func (stdImpl) MarshalToString(v any) (string, error) {
    34  	buf, err := json.Marshal(v)
    35  	if err != nil {
    36  		return "", err
    37  	}
    38  	return unsafeheader.BytesToString(buf), nil
    39  }
    40  
    41  func (stdImpl) UnmarshalFromString(data string, v any) error {
    42  	buf := unsafeheader.StringToBytes(data)
    43  	return json.Unmarshal(buf, v)
    44  }
    45  
    46  func (stdImpl) Compact(dst *bytes.Buffer, src []byte) error {
    47  	return json.Compact(dst, src)
    48  }
    49  
    50  func (stdImpl) HTMLEscape(dst *bytes.Buffer, src []byte) {
    51  	json.HTMLEscape(dst, src)
    52  }
    53  
    54  func (stdImpl) Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error {
    55  	return json.Indent(dst, src, prefix, indent)
    56  }
    57  
    58  func (stdImpl) MarshalFastest(v any) ([]byte, error) {
    59  	return json.Marshal(v)
    60  }
    61  
    62  func (stdImpl) MarshalNoHTMLEscape(v any, prefix, indent string) ([]byte, error) {
    63  	var buf bytes.Buffer
    64  	enc := json.NewEncoder(&buf)
    65  	enc.SetEscapeHTML(false)
    66  	enc.SetIndent(prefix, indent)
    67  	err := enc.Encode(v)
    68  	if err != nil {
    69  		return nil, err
    70  	}
    71  
    72  	// json.Encoder always appends '\n' after encoding,
    73  	// which is not same with json.Marshal.
    74  	out := buf.Bytes()
    75  	if len(out) > 0 && out[len(out)-1] == '\n' {
    76  		out = out[:len(out)-1]
    77  	}
    78  	return out, nil
    79  }
    80  
    81  func (stdImpl) NewEncoder(w io.Writer) UnderlyingEncoder {
    82  	return json.NewEncoder(w)
    83  }
    84  
    85  func (stdImpl) NewDecoder(r io.Reader) UnderlyingDecoder {
    86  	return json.NewDecoder(r)
    87  }