podman

Форк
0
240 строк · 7.4 Кб
1
// +build !amd64 !go1.16 go1.22
2

3
/*
4
* Copyright 2023 ByteDance Inc.
5
*
6
* Licensed under the Apache License, Version 2.0 (the "License");
7
* you may not use this file except in compliance with the License.
8
* You may obtain a copy of the License at
9
*
10
*     http://www.apache.org/licenses/LICENSE-2.0
11
*
12
* Unless required by applicable law or agreed to in writing, software
13
* distributed under the License is distributed on an "AS IS" BASIS,
14
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
* See the License for the specific language governing permissions and
16
* limitations under the License.
17
*/
18

19
package encoder
20

21
import (
22
   `io`
23
    `bytes`
24
    `encoding/json`
25
    `reflect`
26

27
    `github.com/bytedance/sonic/option`
28
)
29

30
func init() {
31
    println("WARNING: sonic only supports Go1.16~1.20 && CPU amd64, but your environment is not suitable")
32
}
33

34
// Options is a set of encoding options.
35
type Options uint64
36

37
const (
38
    bitSortMapKeys          = iota
39
    bitEscapeHTML          
40
    bitCompactMarshaler
41
    bitNoQuoteTextMarshaler
42
    bitNoNullSliceOrMap
43
    bitValidateString
44
    bitNoValidateJSONMarshaler
45

46
    // used for recursive compile
47
    bitPointerValue = 63
48
)
49

50
const (
51
    // SortMapKeys indicates that the keys of a map needs to be sorted 
52
    // before serializing into JSON.
53
    // WARNING: This hurts performance A LOT, USE WITH CARE.
54
    SortMapKeys          Options = 1 << bitSortMapKeys
55

56
    // EscapeHTML indicates encoder to escape all HTML characters 
57
    // after serializing into JSON (see https://pkg.go.dev/encoding/json#HTMLEscape).
58
    // WARNING: This hurts performance A LOT, USE WITH CARE.
59
    EscapeHTML           Options = 1 << bitEscapeHTML
60

61
    // CompactMarshaler indicates that the output JSON from json.Marshaler 
62
    // is always compact and needs no validation 
63
    CompactMarshaler     Options = 1 << bitCompactMarshaler
64

65
    // NoQuoteTextMarshaler indicates that the output text from encoding.TextMarshaler 
66
    // is always escaped string and needs no quoting
67
    NoQuoteTextMarshaler Options = 1 << bitNoQuoteTextMarshaler
68

69
    // NoNullSliceOrMap indicates all empty Array or Object are encoded as '[]' or '{}',
70
    // instead of 'null'
71
    NoNullSliceOrMap     Options = 1 << bitNoNullSliceOrMap
72

73
    // ValidateString indicates that encoder should validate the input string
74
    // before encoding it into JSON.
75
    ValidateString       Options = 1 << bitValidateString
76

77
    // NoValidateJSONMarshaler indicates that the encoder should not validate the output string
78
    // after encoding the JSONMarshaler to JSON.
79
    NoValidateJSONMarshaler Options = 1 << bitNoValidateJSONMarshaler
80
  
81
    // CompatibleWithStd is used to be compatible with std encoder.
82
    CompatibleWithStd Options = SortMapKeys | EscapeHTML | CompactMarshaler
83
)
84

85
// Encoder represents a specific set of encoder configurations.
86
type Encoder struct {
87
    Opts Options
88
    prefix string
89
    indent string
90
}
91

92
// Encode returns the JSON encoding of v.
93
func (self *Encoder) Encode(v interface{}) ([]byte, error) {
94
    if self.indent != "" || self.prefix != "" { 
95
        return EncodeIndented(v, self.prefix, self.indent, self.Opts)
96
    }
97
    return Encode(v, self.Opts)
98
}
99

100
// SortKeys enables the SortMapKeys option.
101
func (self *Encoder) SortKeys() *Encoder {
102
    self.Opts |= SortMapKeys
103
    return self
104
}
105

106
// SetEscapeHTML specifies if option EscapeHTML opens
107
func (self *Encoder) SetEscapeHTML(f bool) {
108
    if f {
109
        self.Opts |= EscapeHTML
110
    } else {
111
        self.Opts &= ^EscapeHTML
112
    }
113
}
114

115
// SetValidateString specifies if option ValidateString opens
116
func (self *Encoder) SetValidateString(f bool) {
117
    if f {
118
        self.Opts |= ValidateString
119
    } else {
120
        self.Opts &= ^ValidateString
121
    }
122
}
123

124
// SetNoValidateJSONMarshaler specifies if option NoValidateJSONMarshaler opens
125
func (self *Encoder) SetNoValidateJSONMarshaler(f bool) {
126
    if f {
127
        self.Opts |= NoValidateJSONMarshaler
128
    } else {
129
        self.Opts &= ^NoValidateJSONMarshaler
130
    }
131
}
132

133
// SetCompactMarshaler specifies if option CompactMarshaler opens
134
func (self *Encoder) SetCompactMarshaler(f bool) {
135
    if f {
136
        self.Opts |= CompactMarshaler
137
    } else {
138
        self.Opts &= ^CompactMarshaler
139
    }
140
}
141

142
// SetNoQuoteTextMarshaler specifies if option NoQuoteTextMarshaler opens
143
func (self *Encoder) SetNoQuoteTextMarshaler(f bool) {
144
    if f {
145
        self.Opts |= NoQuoteTextMarshaler
146
    } else {
147
        self.Opts &= ^NoQuoteTextMarshaler
148
    }
149
}
150

151
// SetIndent instructs the encoder to format each subsequent encoded
152
// value as if indented by the package-level function EncodeIndent().
153
// Calling SetIndent("", "") disables indentation.
154
func (enc *Encoder) SetIndent(prefix, indent string) {
155
    enc.prefix = prefix
156
    enc.indent = indent
157
}
158

159
// Quote returns the JSON-quoted version of s.
160
func Quote(s string) string {
161
    /* check for empty string */
162
    if s == "" {
163
        return `""`
164
    }
165

166
    out, _ := json.Marshal(s)
167
    return string(out)
168
}
169

170
// Encode returns the JSON encoding of val, encoded with opts.
171
func Encode(val interface{}, opts Options) ([]byte, error) {
172
   return json.Marshal(val)
173
}
174

175
// EncodeInto is like Encode but uses a user-supplied buffer instead of allocating
176
// a new one.
177
func EncodeInto(buf *[]byte, val interface{}, opts Options) error {
178
   if buf == nil {
179
       panic("user-supplied buffer buf is nil")
180
   }
181
   w := bytes.NewBuffer(*buf)
182
   enc := json.NewEncoder(w)
183
   enc.SetEscapeHTML((opts & EscapeHTML) != 0)
184
   err := enc.Encode(val)
185
   *buf = w.Bytes()
186
   return err
187
}
188

189
// HTMLEscape appends to dst the JSON-encoded src with <, >, &, U+2028 and U+2029
190
// characters inside string literals changed to \u003c, \u003e, \u0026, \u2028, \u2029
191
// so that the JSON will be safe to embed inside HTML <script> tags.
192
// For historical reasons, web browsers don't honor standard HTML
193
// escaping within <script> tags, so an alternative JSON encoding must
194
// be used.
195
func HTMLEscape(dst []byte, src []byte) []byte {
196
   d := bytes.NewBuffer(dst)
197
   json.HTMLEscape(d, src)
198
   return d.Bytes()
199
}
200

201
// EncodeIndented is like Encode but applies Indent to format the output.
202
// Each JSON element in the output will begin on a new line beginning with prefix
203
// followed by one or more copies of indent according to the indentation nesting.
204
func EncodeIndented(val interface{}, prefix string, indent string, opts Options) ([]byte, error) {
205
   w := bytes.NewBuffer([]byte{})
206
   enc := json.NewEncoder(w)
207
   enc.SetEscapeHTML((opts & EscapeHTML) != 0)
208
   enc.SetIndent(prefix, indent)
209
   err := enc.Encode(val)
210
   out := w.Bytes()
211
   return out, err
212
}
213

214
// Pretouch compiles vt ahead-of-time to avoid JIT compilation on-the-fly, in
215
// order to reduce the first-hit latency.
216
//
217
// Opts are the compile options, for example, "option.WithCompileRecursiveDepth" is
218
// a compile option to set the depth of recursive compile for the nested struct type.
219
func Pretouch(vt reflect.Type, opts ...option.CompileOption) error {
220
   return nil
221
}
222

223
// Valid validates json and returns first non-blank character position,
224
// if it is only one valid json value.
225
// Otherwise returns invalid character position using start.
226
//
227
// Note: it does not check for the invalid UTF-8 characters.
228
func Valid(data []byte) (ok bool, start int) {
229
   return json.Valid(data), 0
230
}
231

232
// StreamEncoder uses io.Writer as 
233
type StreamEncoder = json.Encoder
234

235
// NewStreamEncoder adapts to encoding/json.NewDecoder API.
236
//
237
// NewStreamEncoder returns a new encoder that write to w.
238
func NewStreamEncoder(w io.Writer) *StreamEncoder {
239
   return json.NewEncoder(w)
240
}
241

242

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

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

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

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