podman

Форк
0
196 строк · 7.8 Кб
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
    // NoValidateJSONMarshaler indicates that the encoder should not validate the output string
74
    // after encoding the JSONMarshaler to JSON.
75
    NoValidateJSONMarshaler       bool
76
}
77
 
78
var (
79
    // ConfigDefault is the default config of APIs, aiming at efficiency and safty.
80
    ConfigDefault = Config{}.Froze()
81
 
82
    // ConfigStd is the standard config of APIs, aiming at being compatible with encoding/json.
83
    ConfigStd = Config{
84
        EscapeHTML : true,
85
        SortMapKeys: true,
86
        CompactMarshaler: true,
87
        CopyString : true,
88
        ValidateString : true,
89
    }.Froze()
90
 
91
    // ConfigFastest is the fastest config of APIs, aiming at speed.
92
    ConfigFastest = Config{
93
        NoQuoteTextMarshaler: true,
94
        NoValidateJSONMarshaler: true,
95
    }.Froze()
96
)
97
 
98
 
99
// API is a binding of specific config.
100
// This interface is inspired by github.com/json-iterator/go,
101
// and has same behaviors under equavilent config.
102
type API interface {
103
    // MarshalToString returns the JSON encoding string of v
104
    MarshalToString(v interface{}) (string, error)
105
    // Marshal returns the JSON encoding bytes of v.
106
    Marshal(v interface{}) ([]byte, error)
107
    // MarshalIndent returns the JSON encoding bytes with indent and prefix.
108
    MarshalIndent(v interface{}, prefix, indent string) ([]byte, error)
109
    // UnmarshalFromString parses the JSON-encoded bytes and stores the result in the value pointed to by v.
110
    UnmarshalFromString(str string, v interface{}) error
111
    // Unmarshal parses the JSON-encoded string and stores the result in the value pointed to by v.
112
    Unmarshal(data []byte, v interface{}) error
113
    // NewEncoder create a Encoder holding writer
114
    NewEncoder(writer io.Writer) Encoder
115
    // NewDecoder create a Decoder holding reader
116
    NewDecoder(reader io.Reader) Decoder
117
    // Valid validates the JSON-encoded bytes and reportes if it is valid
118
    Valid(data []byte) bool
119
}
120

121
// Encoder encodes JSON into io.Writer
122
type Encoder interface {
123
    // Encode writes the JSON encoding of v to the stream, followed by a newline character.
124
    Encode(val interface{}) error
125
    // SetEscapeHTML specifies whether problematic HTML characters 
126
    // should be escaped inside JSON quoted strings. 
127
    // The default behavior NOT ESCAPE 
128
    SetEscapeHTML(on bool)
129
    // SetIndent instructs the encoder to format each subsequent encoded value 
130
    // as if indented by the package-level function Indent(dst, src, prefix, indent).
131
    // Calling SetIndent("", "") disables indentation
132
    SetIndent(prefix, indent string)
133
}
134

135
// Decoder decodes JSON from io.Read
136
type Decoder interface {
137
    // Decode reads the next JSON-encoded value from its input and stores it in the value pointed to by v.
138
    Decode(val interface{}) error
139
    // Buffered returns a reader of the data remaining in the Decoder's buffer.
140
    // The reader is valid until the next call to Decode.
141
    Buffered() io.Reader
142
    // DisallowUnknownFields causes the Decoder to return an error when the destination is a struct 
143
    // and the input contains object keys which do not match any non-ignored, exported fields in the destination.
144
    DisallowUnknownFields()
145
    // More reports whether there is another element in the current array or object being parsed.
146
    More() bool
147
    // UseNumber causes the Decoder to unmarshal a number into an interface{} as a Number instead of as a float64.
148
    UseNumber()
149
}
150

151
// Marshal returns the JSON encoding bytes of v.
152
func Marshal(val interface{}) ([]byte, error) {
153
    return ConfigDefault.Marshal(val)
154
}
155

156
// MarshalString returns the JSON encoding string of v.
157
func MarshalString(val interface{}) (string, error) {
158
    return ConfigDefault.MarshalToString(val)
159
}
160

161
// Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v.
162
// NOTICE: This API copies given buffer by default,
163
// if you want to pass JSON more efficiently, use UnmarshalString instead.
164
func Unmarshal(buf []byte, val interface{}) error {
165
    return ConfigDefault.Unmarshal(buf, val)
166
}
167

168
// UnmarshalString is like Unmarshal, except buf is a string.
169
func UnmarshalString(buf string, val interface{}) error {
170
    return ConfigDefault.UnmarshalFromString(buf, val)
171
}
172

173
// Get searches the given path from json,
174
// and returns its representing ast.Node.
175
//
176
// Each path arg must be integer or string:
177
//     - Integer is target index(>=0), means searching current node as array.
178
//     - String is target key, means searching current node as object.
179
//
180
// 
181
// Note, the api expects the json is well-formed at least,
182
// otherwise it may return unexpected result.
183
func Get(src []byte, path ...interface{}) (ast.Node, error) {
184
    return GetFromString(string(src), path...)
185
}
186

187
// GetFromString is same with Get except src is string,
188
// which can reduce unnecessary memory copy.
189
func GetFromString(src string, path ...interface{}) (ast.Node, error) {
190
    return ast.NewSearcher(src).GetByPath(path...)
191
}
192

193
// Valid reports whether data is a valid JSON encoding.
194
func Valid(data []byte) bool {
195
    return ConfigDefault.Valid(data)
196
}
197

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.