Debian Codegraph @

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

raw
1 // Copyright 2020 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 "bytes"
9 "errors"
10 "io"
11 "reflect"
12
13 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonflags"
14 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonopts"
15 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire"
16 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext"
17 )
18
19 // This package supports "inlining" a Go struct field, where the contents
20 // of the serialized field (which must be a JSON object) are treated as if
21 // they are part of the parent Go struct (which represents a JSON object).
22 //
23 // Generally, inlined fields are of a Go struct type, where the fields of the
24 // nested struct are virtually hoisted up to the parent struct using rules
25 // similar to how Go embedding works (but operating within the JSON namespace).
26 //
27 // However, inlined fields may also be of a Go map type with a string key or
28 // a jsontext.Value. Such inlined fields are called "fallback" fields since they
29 // represent any arbitrary JSON object member. Explicitly named fields take
30 // precedence over the inlined fallback. Only one inlined fallback is allowed.
31
32 var errRawInlinedNotObject = errors.New("inlined raw value must be a JSON object")
33
34 var jsontextValueType = reflect.TypeFor[jsontext.Value]()
35
36 // marshalInlinedFallbackAll marshals all the members in an inlined fallback.
37 func marshalInlinedFallbackAll(enc *jsontext.Encoder, va addressableValue, mo *jsonopts.Struct, f *structField, insertUnquotedName func([]byte) bool) error {
38 v := addressableValue{va.Field(f.index0), va.forcedAddr} // addressable if struct value is addressable
39 if len(f.index) > 0 {
40 v = v.fieldByIndex(f.index, false)
41 if !v.IsValid() {
42 return nil // implies a nil inlined field
43 }
44 }
45 v = v.indirect(false)
46 if !v.IsValid() {
47 return nil
48 }
49
50 if v.Type() == jsontextValueType {
51 // TODO(https://go.dev/issue/62121): Use reflect.Value.AssertTo.
52 b := *v.Addr().Interface().(*jsontext.Value)
53 if len(b) == 0 { // TODO: Should this be nil? What if it were all whitespace?
54 return nil
55 }
56
57 dec := export.GetBufferedDecoder(b)
58 defer export.PutBufferedDecoder(dec)
59 xd := export.Decoder(dec)
60 xd.Flags.Set(jsonflags.AllowDuplicateNames | jsonflags.AllowInvalidUTF8 | 1)
61
62 tok, err := dec.ReadToken()
63 if err != nil {
64 if err == io.EOF {
65 err = io.ErrUnexpectedEOF
66 }
67 return newMarshalErrorBefore(enc, v.Type(), err)
68 }
69 if tok.Kind() != '{' {
70 return newMarshalErrorBefore(enc, v.Type(), errRawInlinedNotObject)
71 }
72 for dec.PeekKind() != '}' {
73 // Parse the JSON object name.
74 var flags jsonwire.ValueFlags
75 val, err := xd.ReadValue(&flags)
76 if err != nil {
77 return newMarshalErrorBefore(enc, v.Type(), err)
78 }
79 if insertUnquotedName != nil {
80 name := jsonwire.UnquoteMayCopy(val, flags.IsVerbatim())
81 if !insertUnquotedName(name) {
82 return newDuplicateNameError(enc.StackPointer().Parent(), val, enc.OutputOffset())
83 }
84 }
85 if err := enc.WriteValue(val); err != nil {
86 return err
87 }
88
89 // Parse the JSON object value.
90 val, err = xd.ReadValue(&flags)
91 if err != nil {
92 return newMarshalErrorBefore(enc, v.Type(), err)
93 }
94 if err := enc.WriteValue(val); err != nil {
95 return err
96 }
97 }
98 if _, err := dec.ReadToken(); err != nil {
99 return newMarshalErrorBefore(enc, v.Type(), err)
100 }
101 if err := xd.CheckEOF(); err != nil {
102 return newMarshalErrorBefore(enc, v.Type(), err)
103 }
104 return nil
105 } else {
106 m := v // must be a map[~string]V
107 n := m.Len()
108 if n == 0 {
109 return nil
110 }
111 mk := newAddressableValue(m.Type().Key())
112 mv := newAddressableValue(m.Type().Elem())
113 marshalKey := func(mk addressableValue) error {
114 b, err := jsonwire.AppendQuote(enc.AvailableBuffer(), mk.String(), &mo.Flags)
115 if err != nil {
116 return newMarshalErrorBefore(enc, m.Type().Key(), err)
117 }
118 if insertUnquotedName != nil {
119 isVerbatim := bytes.IndexByte(b, '\\') < 0
120 name := jsonwire.UnquoteMayCopy(b, isVerbatim)
121 if !insertUnquotedName(name) {
122 return newDuplicateNameError(enc.StackPointer().Parent(), b, enc.OutputOffset())
123 }
124 }
125 return enc.WriteValue(b)
126 }
127 marshalVal := f.fncs.marshal
128 if mo.Marshalers != nil {
129 marshalVal, _ = mo.Marshalers.(*Marshalers).lookup(marshalVal, mv.Type())
130 }
131 if !mo.Flags.Get(jsonflags.Deterministic) || n <= 1 {
132 for iter := m.MapRange(); iter.Next(); {
133 mk.SetIterKey(iter)
134 if err := marshalKey(mk); err != nil {
135 return err
136 }
137 mv.Set(iter.Value())
138 if err := marshalVal(enc, mv, mo); err != nil {
139 return err
140 }
141 }
142 } else {
143 names := getStrings(n)
144 for i, iter := 0, m.Value.MapRange(); i < n && iter.Next(); i++ {
145 mk.SetIterKey(iter)
146 (*names)[i] = mk.String()
147 }
148 names.Sort()
149 for _, name := range *names {
150 mk.SetString(name)
151 if err := marshalKey(mk); err != nil {
152 return err
153 }
154 // TODO(https://go.dev/issue/57061): Use mv.SetMapIndexOf.
155 mv.Set(m.MapIndex(mk.Value))
156 if err := marshalVal(enc, mv, mo); err != nil {
157 return err
158 }
159 }
160 putStrings(names)
161 }
162 return nil
163 }
164 }
165
166 // unmarshalInlinedFallbackNext unmarshals only the next member in an inlined fallback.
167 func unmarshalInlinedFallbackNext(dec *jsontext.Decoder, va addressableValue, uo *jsonopts.Struct, f *structField, quotedName, unquotedName []byte) error {
168 v := addressableValue{va.Field(f.index0), va.forcedAddr} // addressable if struct value is addressable
169 if len(f.index) > 0 {
170 v = v.fieldByIndex(f.index, true)
171 }
172 v = v.indirect(true)
173
174 if v.Type() == jsontextValueType {
175 b := v.Addr().Interface().(*jsontext.Value)
176 if len(*b) == 0 { // TODO: Should this be nil? What if it were all whitespace?
177 *b = append(*b, '{')
178 } else {
179 *b = jsonwire.TrimSuffixWhitespace(*b)
180 if jsonwire.HasSuffixByte(*b, '}') {
181 // TODO: When merging into an object for the first time,
182 // should we verify that it is valid?
183 *b = jsonwire.TrimSuffixByte(*b, '}')
184 *b = jsonwire.TrimSuffixWhitespace(*b)
185 if !jsonwire.HasSuffixByte(*b, ',') && !jsonwire.HasSuffixByte(*b, '{') {
186 *b = append(*b, ',')
187 }
188 } else {
189 return newUnmarshalErrorAfterWithSkipping(dec, v.Type(), errRawInlinedNotObject)
190 }
191 }
192 *b = append(*b, quotedName...)
193 *b = append(*b, ':')
194 val, err := dec.ReadValue()
195 if err != nil {
196 return err
197 }
198 *b = append(*b, val...)
199 *b = append(*b, '}')
200 return nil
201 } else {
202 name := string(unquotedName) // TODO: Intern this?
203
204 m := v // must be a map[~string]V
205 if m.IsNil() {
206 m.Set(reflect.MakeMap(m.Type()))
207 }
208 mk := reflect.ValueOf(name)
209 if mkt := m.Type().Key(); mkt != stringType {
210 mk = mk.Convert(mkt)
211 }
212 mv := newAddressableValue(m.Type().Elem()) // TODO: Cache across calls?
213 if v2 := m.MapIndex(mk); v2.IsValid() {
214 mv.Set(v2)
215 }
216
217 unmarshal := f.fncs.unmarshal
218 if uo.Unmarshalers != nil {
219 unmarshal, _ = uo.Unmarshalers.(*Unmarshalers).lookup(unmarshal, mv.Type())
220 }
221 err := unmarshal(dec, mv, uo)
222 m.SetMapIndex(mk, mv.Value)
223 if err != nil {
224 return err
225 }
226 return nil
227 }
228 }