Debian Codegraph @

pkg/internal/third_party/go-json-experiment/json/options.go

raw
1 // Copyright 2023 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package json
6
7 import (
8 "fmt"
9
10 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal"
11 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonflags"
12 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonopts"
13 )
14
15 // Options configure [Marshal], [MarshalWrite], [MarshalEncode],
16 // [Unmarshal], [UnmarshalRead], and [UnmarshalDecode] with specific features.
17 // Each function takes in a variadic list of options, where properties
18 // set in later options override the value of previously set properties.
19 //
20 // The Options type is identical to [encoding/json.Options] and
21 // [encoding/json/jsontext.Options]. Options from the other packages can
22 // be used interchangeably with functionality in this package.
23 //
24 // Options represent either a singular option or a set of options.
25 // It can be functionally thought of as a Go map of option properties
26 // (even though the underlying implementation avoids Go maps for performance).
27 //
28 // The constructors (e.g., [Deterministic]) return a singular option value:
29 //
30 // opt := Deterministic(true)
31 //
32 // which is analogous to creating a single entry map:
33 //
34 // opt := Options{"Deterministic": true}
35 //
36 // [JoinOptions] composes multiple options values to together:
37 //
38 // out := JoinOptions(opts...)
39 //
40 // which is analogous to making a new map and copying the options over:
41 //
42 // out := make(Options)
43 // for _, m := range opts {
44 // for k, v := range m {
45 // out[k] = v
46 // }
47 // }
48 //
49 // [GetOption] looks up the value of options parameter:
50 //
51 // v, ok := GetOption(opts, Deterministic)
52 //
53 // which is analogous to a Go map lookup:
54 //
55 // v, ok := Options["Deterministic"]
56 //
57 // There is a single Options type, which is used with both marshal and unmarshal.
58 // Some options affect both operations, while others only affect one operation:
59 //
60 // - [StringifyNumbers] affects marshaling and unmarshaling
61 // - [Deterministic] affects marshaling only
62 // - [FormatNilSliceAsNull] affects marshaling only
63 // - [FormatNilMapAsNull] affects marshaling only
64 // - [OmitZeroStructFields] affects marshaling only
65 // - [MatchCaseInsensitiveNames] affects marshaling and unmarshaling
66 // - [DiscardUnknownMembers] affects marshaling only
67 // - [RejectUnknownMembers] affects unmarshaling only
68 // - [WithMarshalers] affects marshaling only
69 // - [WithUnmarshalers] affects unmarshaling only
70 //
71 // Options that do not affect a particular operation are ignored.
72 type Options = jsonopts.Options
73
74 // JoinOptions coalesces the provided list of options into a single Options.
75 // Properties set in later options override the value of previously set properties.
76 func JoinOptions(srcs ...Options) Options {
77 var dst jsonopts.Struct
78 dst.Join(srcs...)
79 return &dst
80 }
81
82 // GetOption returns the value stored in opts with the provided setter,
83 // reporting whether the value is present.
84 //
85 // Example usage:
86 //
87 // v, ok := json.GetOption(opts, json.Deterministic)
88 //
89 // Options are most commonly introspected to alter the JSON representation of
90 // [MarshalerTo.MarshalJSONTo] and [UnmarshalerFrom.UnmarshalJSONFrom] methods, and
91 // [MarshalToFunc] and [UnmarshalFromFunc] functions.
92 // In such cases, the presence bit should generally be ignored.
93 func GetOption[T any](opts Options, setter func(T) Options) (T, bool) {
94 return jsonopts.GetOption(opts, setter)
95 }
96
97 // DefaultOptionsV2 is the full set of all options that define v2 semantics.
98 // It is equivalent to all options under [Options], [encoding/json.Options],
99 // and [encoding/json/jsontext.Options] being set to false or the zero value,
100 // except for the options related to whitespace formatting.
101 func DefaultOptionsV2() Options {
102 return &jsonopts.DefaultOptionsV2
103 }
104
105 // StringifyNumbers specifies that numeric Go types should be marshaled
106 // as a JSON string containing the equivalent JSON number value.
107 // When unmarshaling, numeric Go types are parsed from a JSON string
108 // containing the JSON number without any surrounding whitespace.
109 //
110 // According to RFC 8259, section 6, a JSON implementation may choose to
111 // limit the representation of a JSON number to an IEEE 754 binary64 value.
112 // This may cause decoders to lose precision for int64 and uint64 types.
113 // Quoting JSON numbers as a JSON string preserves the exact precision.
114 //
115 // This affects either marshaling or unmarshaling.
116 func StringifyNumbers(v bool) Options {
117 if v {
118 return jsonflags.StringifyNumbers | 1
119 } else {
120 return jsonflags.StringifyNumbers | 0
121 }
122 }
123
124 // Deterministic specifies that the same input value will be serialized
125 // as the exact same output bytes. Different processes of
126 // the same program will serialize equal values to the same bytes,
127 // but different versions of the same program are not guaranteed
128 // to produce the exact same sequence of bytes.
129 //
130 // This only affects marshaling and is ignored when unmarshaling.
131 func Deterministic(v bool) Options {
132 if v {
133 return jsonflags.Deterministic | 1
134 } else {
135 return jsonflags.Deterministic | 0
136 }
137 }
138
139 // FormatNilSliceAsNull specifies that a nil Go slice should marshal as a
140 // JSON null instead of the default representation as an empty JSON array
141 // (or an empty JSON string in the case of ~[]byte).
142 // Slice fields explicitly marked with `format:emitempty` still marshal
143 // as an empty JSON array.
144 //
145 // This only affects marshaling and is ignored when unmarshaling.
146 func FormatNilSliceAsNull(v bool) Options {
147 if v {
148 return jsonflags.FormatNilSliceAsNull | 1
149 } else {
150 return jsonflags.FormatNilSliceAsNull | 0
151 }
152 }
153
154 // FormatNilMapAsNull specifies that a nil Go map should marshal as a
155 // JSON null instead of the default representation as an empty JSON object.
156 // Map fields explicitly marked with `format:emitempty` still marshal
157 // as an empty JSON object.
158 //
159 // This only affects marshaling and is ignored when unmarshaling.
160 func FormatNilMapAsNull(v bool) Options {
161 if v {
162 return jsonflags.FormatNilMapAsNull | 1
163 } else {
164 return jsonflags.FormatNilMapAsNull | 0
165 }
166 }
167
168 // OmitZeroStructFields specifies that a Go struct should marshal in such a way
169 // that all struct fields that are zero are omitted from the marshaled output
170 // if the value is zero as determined by the "IsZero() bool" method if present,
171 // otherwise based on whether the field is the zero Go value.
172 // This is semantically equivalent to specifying the `omitzero` tag option
173 // on every field in a Go struct.
174 //
175 // This only affects marshaling and is ignored when unmarshaling.
176 func OmitZeroStructFields(v bool) Options {
177 if v {
178 return jsonflags.OmitZeroStructFields | 1
179 } else {
180 return jsonflags.OmitZeroStructFields | 0
181 }
182 }
183
184 // MatchCaseInsensitiveNames specifies that JSON object members are matched
185 // against Go struct fields using a case-insensitive match of the name.
186 // Go struct fields explicitly marked with `case:strict` or `case:ignore`
187 // always use case-sensitive (or case-insensitive) name matching,
188 // regardless of the value of this option.
189 //
190 // This affects either marshaling or unmarshaling.
191 // For marshaling, this option may alter the detection of duplicate names
192 // (assuming [jsontext.AllowDuplicateNames] is false) from inlined fields
193 // if it matches one of the declared fields in the Go struct.
194 func MatchCaseInsensitiveNames(v bool) Options {
195 if v {
196 return jsonflags.MatchCaseInsensitiveNames | 1
197 } else {
198 return jsonflags.MatchCaseInsensitiveNames | 0
199 }
200 }
201
202 // DiscardUnknownMembers specifies that marshaling should ignore any
203 // JSON object members stored in Go struct fields dedicated to storing
204 // unknown JSON object members.
205 //
206 // This only affects marshaling and is ignored when unmarshaling.
207 func DiscardUnknownMembers(v bool) Options {
208 if v {
209 return jsonflags.DiscardUnknownMembers | 1
210 } else {
211 return jsonflags.DiscardUnknownMembers | 0
212 }
213 }
214
215 // RejectUnknownMembers specifies that unknown members should be rejected
216 // when unmarshaling a JSON object, regardless of whether there is a field
217 // to store unknown members.
218 //
219 // This only affects unmarshaling and is ignored when marshaling.
220 func RejectUnknownMembers(v bool) Options {
221 if v {
222 return jsonflags.RejectUnknownMembers | 1
223 } else {
224 return jsonflags.RejectUnknownMembers | 0
225 }
226 }
227
228 // WithMarshalers specifies a list of type-specific marshalers to use,
229 // which can be used to override the default marshal behavior for values
230 // of particular types.
231 //
232 // This only affects marshaling and is ignored when unmarshaling.
233 func WithMarshalers(v *Marshalers) Options {
234 return (*marshalersOption)(v)
235 }
236
237 // WithUnmarshalers specifies a list of type-specific unmarshalers to use,
238 // which can be used to override the default unmarshal behavior for values
239 // of particular types.
240 //
241 // This only affects unmarshaling and is ignored when marshaling.
242 func WithUnmarshalers(v *Unmarshalers) Options {
243 return (*unmarshalersOption)(v)
244 }
245
246 // These option types are declared here instead of "jsonopts"
247 // to avoid a dependency on "reflect" from "jsonopts".
248 type (
249 marshalersOption Marshalers
250 unmarshalersOption Unmarshalers
251 )
252
253 func (*marshalersOption) JSONOptions(internal.NotForPublicUse) {}
254 func (*unmarshalersOption) JSONOptions(internal.NotForPublicUse) {}
255
256 // Inject support into "jsonopts" to handle these types.
257 func init() {
258 jsonopts.GetUnknownOption = func(src jsonopts.Struct, zero jsonopts.Options) (any, bool) {
259 switch zero.(type) {
260 case *marshalersOption:
261 if !src.Flags.Has(jsonflags.Marshalers) {
262 return (*Marshalers)(nil), false
263 }
264 return src.Marshalers.(*Marshalers), true
265 case *unmarshalersOption:
266 if !src.Flags.Has(jsonflags.Unmarshalers) {
267 return (*Unmarshalers)(nil), false
268 }
269 return src.Unmarshalers.(*Unmarshalers), true
270 default:
271 panic(fmt.Sprintf("unknown option %T", zero))
272 }
273 }
274 jsonopts.JoinUnknownOption = func(dst jsonopts.Struct, src jsonopts.Options) jsonopts.Struct {
275 switch src := src.(type) {
276 case *marshalersOption:
277 dst.Flags.Set(jsonflags.Marshalers | 1)
278 dst.Marshalers = (*Marshalers)(src)
279 case *unmarshalersOption:
280 dst.Flags.Set(jsonflags.Unmarshalers | 1)
281 dst.Unmarshalers = (*Unmarshalers)(src)
282 default:
283 panic(fmt.Sprintf("unknown option %T", src))
284 }
285 return dst
286 }
287 }