gtsocial-umbx

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README | LICENSE

api.go (7596B)


      1 /*
      2  * Copyright 2021 ByteDance Inc.
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *     http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package sonic
     18 
     19 import (
     20     `io`
     21 
     22     `github.com/bytedance/sonic/ast`
     23 )
     24 
     25 // Config is a combination of sonic/encoder.Options and sonic/decoder.Options
     26 type Config struct {
     27     // EscapeHTML indicates encoder to escape all HTML characters 
     28     // after serializing into JSON (see https://pkg.go.dev/encoding/json#HTMLEscape).
     29     // WARNING: This hurts performance A LOT, USE WITH CARE.
     30     EscapeHTML                    bool
     31 
     32     // SortMapKeys indicates encoder that the keys of a map needs to be sorted 
     33     // before serializing into JSON.
     34     // WARNING: This hurts performance A LOT, USE WITH CARE.
     35     SortMapKeys                   bool
     36 
     37     // CompactMarshaler indicates encoder that the output JSON from json.Marshaler 
     38     // is always compact and needs no validation 
     39     CompactMarshaler              bool
     40 
     41     // NoQuoteTextMarshaler indicates encoder that the output text from encoding.TextMarshaler 
     42     // is always escaped string and needs no quoting
     43     NoQuoteTextMarshaler          bool
     44 
     45     // NoNullSliceOrMap indicates encoder that all empty Array or Object are encoded as '[]' or '{}',
     46     // instead of 'null'
     47     NoNullSliceOrMap              bool
     48 
     49     // UseInt64 indicates decoder to unmarshal an integer into an interface{} as an
     50     // int64 instead of as a float64.
     51     UseInt64                      bool
     52 
     53     // UseNumber indicates decoder to unmarshal a number into an interface{} as a
     54     // json.Number instead of as a float64.
     55     UseNumber                     bool
     56 
     57     // UseUnicodeErrors indicates decoder to return an error when encounter invalid
     58     // UTF-8 escape sequences.
     59     UseUnicodeErrors              bool
     60 
     61     // DisallowUnknownFields indicates decoder to return an error when the destination
     62     // is a struct and the input contains object keys which do not match any
     63     // non-ignored, exported fields in the destination.
     64     DisallowUnknownFields         bool
     65 
     66     // CopyString indicates decoder to decode string values by copying instead of referring.
     67     CopyString                    bool
     68 
     69     // ValidateString indicates decoder and encoder to valid string values: decoder will return errors 
     70     // when unescaped control chars(\u0000-\u001f) in the string value of JSON.
     71     ValidateString                    bool
     72 }
     73  
     74 var (
     75     // ConfigDefault is the default config of APIs, aiming at efficiency and safty.
     76     ConfigDefault = Config{}.Froze()
     77  
     78     // ConfigStd is the standard config of APIs, aiming at being compatible with encoding/json.
     79     ConfigStd = Config{
     80         EscapeHTML : true,
     81         SortMapKeys: true,
     82         CompactMarshaler: true,
     83         CopyString : true,
     84         ValidateString : true,
     85     }.Froze()
     86  
     87     // ConfigFastest is the fastest config of APIs, aiming at speed.
     88     ConfigFastest = Config{
     89         NoQuoteTextMarshaler: true,
     90     }.Froze()
     91 )
     92  
     93  
     94 // API is a binding of specific config.
     95 // This interface is inspired by github.com/json-iterator/go,
     96 // and has same behaviors under equavilent config.
     97 type API interface {
     98     // MarshalToString returns the JSON encoding string of v
     99     MarshalToString(v interface{}) (string, error)
    100     // Marshal returns the JSON encoding bytes of v.
    101     Marshal(v interface{}) ([]byte, error)
    102     // MarshalIndent returns the JSON encoding bytes with indent and prefix.
    103     MarshalIndent(v interface{}, prefix, indent string) ([]byte, error)
    104     // UnmarshalFromString parses the JSON-encoded bytes and stores the result in the value pointed to by v.
    105     UnmarshalFromString(str string, v interface{}) error
    106     // Unmarshal parses the JSON-encoded string and stores the result in the value pointed to by v.
    107     Unmarshal(data []byte, v interface{}) error
    108     // NewEncoder create a Encoder holding writer
    109     NewEncoder(writer io.Writer) Encoder
    110     // NewDecoder create a Decoder holding reader
    111     NewDecoder(reader io.Reader) Decoder
    112     // Valid validates the JSON-encoded bytes and reportes if it is valid
    113     Valid(data []byte) bool
    114 }
    115 
    116 // Encoder encodes JSON into io.Writer
    117 type Encoder interface {
    118     // Encode writes the JSON encoding of v to the stream, followed by a newline character.
    119     Encode(val interface{}) error
    120     // SetEscapeHTML specifies whether problematic HTML characters 
    121     // should be escaped inside JSON quoted strings. 
    122     // The default behavior NOT ESCAPE 
    123     SetEscapeHTML(on bool)
    124     // SetIndent instructs the encoder to format each subsequent encoded value 
    125     // as if indented by the package-level function Indent(dst, src, prefix, indent).
    126     // Calling SetIndent("", "") disables indentation
    127     SetIndent(prefix, indent string)
    128 }
    129 
    130 // Decoder decodes JSON from io.Read
    131 type Decoder interface {
    132     // Decode reads the next JSON-encoded value from its input and stores it in the value pointed to by v.
    133     Decode(val interface{}) error
    134     // Buffered returns a reader of the data remaining in the Decoder's buffer.
    135     // The reader is valid until the next call to Decode.
    136     Buffered() io.Reader
    137     // DisallowUnknownFields causes the Decoder to return an error when the destination is a struct 
    138     // and the input contains object keys which do not match any non-ignored, exported fields in the destination.
    139     DisallowUnknownFields()
    140     // More reports whether there is another element in the current array or object being parsed.
    141     More() bool
    142     // UseNumber causes the Decoder to unmarshal a number into an interface{} as a Number instead of as a float64.
    143     UseNumber()
    144 }
    145 
    146 // Marshal returns the JSON encoding bytes of v.
    147 func Marshal(val interface{}) ([]byte, error) {
    148     return ConfigDefault.Marshal(val)
    149 }
    150 
    151 // MarshalString returns the JSON encoding string of v.
    152 func MarshalString(val interface{}) (string, error) {
    153     return ConfigDefault.MarshalToString(val)
    154 }
    155 
    156 // Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v.
    157 // NOTICE: This API copies given buffer by default,
    158 // if you want to pass JSON more efficiently, use UnmarshalString instead.
    159 func Unmarshal(buf []byte, val interface{}) error {
    160     return ConfigDefault.Unmarshal(buf, val)
    161 }
    162 
    163 // UnmarshalString is like Unmarshal, except buf is a string.
    164 func UnmarshalString(buf string, val interface{}) error {
    165     return ConfigDefault.UnmarshalFromString(buf, val)
    166 }
    167 
    168 // Get searches the given path from json,
    169 // and returns its representing ast.Node.
    170 //
    171 // Each path arg must be integer or string:
    172 //     - Integer is target index(>=0), means searching current node as array.
    173 //     - String is target key, means searching current node as object.
    174 //
    175 // 
    176 // Note, the api expects the json is well-formed at least,
    177 // otherwise it may return unexpected result.
    178 func Get(src []byte, path ...interface{}) (ast.Node, error) {
    179     return GetFromString(string(src), path...)
    180 }
    181 
    182 // GetFromString is same with Get except src is string,
    183 // which can reduce unnecessary memory copy.
    184 func GetFromString(src string, path ...interface{}) (ast.Node, error) {
    185     return ast.NewSearcher(src).GetByPath(path...)
    186 }