blob: d97a60c3b61b6366319d2b5d17b6cb9db181f8f4 [file] [log] [blame]
Herbie Ongc96a79d2019-03-08 10:49:17 -08001// Copyright 2019 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
Damien Neil5c5b5312019-05-14 12:44:37 -07005package protojson
Herbie Ongc96a79d2019-03-08 10:49:17 -08006
7import (
8 "encoding/base64"
9 "fmt"
10 "math"
11 "strconv"
12 "strings"
13
Damien Neile89e6242019-05-13 23:55:40 -070014 "google.golang.org/protobuf/internal/encoding/json"
15 "google.golang.org/protobuf/internal/errors"
16 "google.golang.org/protobuf/internal/pragma"
17 "google.golang.org/protobuf/internal/set"
18 "google.golang.org/protobuf/proto"
19 pref "google.golang.org/protobuf/reflect/protoreflect"
20 "google.golang.org/protobuf/reflect/protoregistry"
Herbie Ongc96a79d2019-03-08 10:49:17 -080021)
22
23// Unmarshal reads the given []byte into the given proto.Message.
Joe Tsaicdb77732019-05-14 16:05:06 -070024func Unmarshal(b []byte, m proto.Message) error {
25 return UnmarshalOptions{}.Unmarshal(b, m)
Herbie Ongc96a79d2019-03-08 10:49:17 -080026}
27
28// UnmarshalOptions is a configurable JSON format parser.
Herbie Onge52379a2019-03-15 18:00:19 -070029type UnmarshalOptions struct {
30 pragma.NoUnkeyedLiterals
31
Herbie Ong4f0be712019-04-25 17:57:12 -070032 // If AllowPartial is set, input for messages that will result in missing
33 // required fields will not return an error.
Herbie Ong329be5b2019-03-27 14:47:59 -070034 AllowPartial bool
35
Herbie Ong4f0be712019-04-25 17:57:12 -070036 // If DiscardUnknown is set, unknown fields are ignored.
37 DiscardUnknown bool
38
Joe Tsai1c283042019-05-14 14:28:19 -070039 // Resolver is used for looking up types when unmarshaling
40 // google.protobuf.Any messages or extension fields.
41 // If nil, this defaults to using protoregistry.GlobalTypes.
42 Resolver interface {
43 protoregistry.MessageTypeResolver
44 protoregistry.ExtensionTypeResolver
45 }
Herbie Ong822de2d2019-03-27 13:16:23 -070046
47 decoder *json.Decoder
Herbie Onge52379a2019-03-15 18:00:19 -070048}
Herbie Ongc96a79d2019-03-08 10:49:17 -080049
50// Unmarshal reads the given []byte and populates the given proto.Message using
51// options in UnmarshalOptions object. It will clear the message first before
52// setting the fields. If it returns an error, the given message may be
53// partially set.
Joe Tsaicdb77732019-05-14 16:05:06 -070054func (o UnmarshalOptions) Unmarshal(b []byte, m proto.Message) error {
Herbie Ongc96a79d2019-03-08 10:49:17 -080055 // TODO: Determine if we would like to have an option for merging or only
Joe Tsai378c1322019-04-25 23:48:08 -070056 // have merging behavior. We should at least be consistent with textproto
Herbie Ongc96a79d2019-03-08 10:49:17 -080057 // marshaling.
Joe Tsai378c1322019-04-25 23:48:08 -070058 proto.Reset(m)
Herbie Ongc96a79d2019-03-08 10:49:17 -080059
Herbie Ong822de2d2019-03-27 13:16:23 -070060 if o.Resolver == nil {
61 o.Resolver = protoregistry.GlobalTypes
Herbie Onge52379a2019-03-15 18:00:19 -070062 }
Herbie Ong822de2d2019-03-27 13:16:23 -070063 o.decoder = json.NewDecoder(b)
Herbie Onge52379a2019-03-15 18:00:19 -070064
Damien Neil8c86fc52019-06-19 09:28:29 -070065 if err := o.unmarshalMessage(m.ProtoReflect(), false); err != nil {
Herbie Ongc96a79d2019-03-08 10:49:17 -080066 return err
67 }
68
69 // Check for EOF.
Herbie Ong822de2d2019-03-27 13:16:23 -070070 val, err := o.decoder.Read()
Herbie Ongc96a79d2019-03-08 10:49:17 -080071 if err != nil {
72 return err
73 }
74 if val.Type() != json.EOF {
75 return unexpectedJSONError{val}
76 }
Damien Neil4686e232019-04-05 13:31:40 -070077
Damien Neil8c86fc52019-06-19 09:28:29 -070078 if o.AllowPartial {
79 return nil
Damien Neil4686e232019-04-05 13:31:40 -070080 }
Damien Neil8c86fc52019-06-19 09:28:29 -070081 return proto.IsInitialized(m)
Herbie Ongc96a79d2019-03-08 10:49:17 -080082}
83
Herbie Ongc96a79d2019-03-08 10:49:17 -080084// unexpectedJSONError is an error that contains the unexpected json.Value. This
Herbie Ong822de2d2019-03-27 13:16:23 -070085// is returned by methods to provide callers the read json.Value that it did not
86// expect.
Herbie Ongc96a79d2019-03-08 10:49:17 -080087// TODO: Consider moving this to internal/encoding/json for consistency with
88// errors that package returns.
89type unexpectedJSONError struct {
90 value json.Value
91}
92
93func (e unexpectedJSONError) Error() string {
94 return newError("unexpected value %s", e.value).Error()
95}
96
97// newError returns an error object. If one of the values passed in is of
98// json.Value type, it produces an error with position info.
99func newError(f string, x ...interface{}) error {
100 var hasValue bool
101 var line, column int
102 for i := 0; i < len(x); i++ {
103 if val, ok := x[i].(json.Value); ok {
104 line, column = val.Position()
105 hasValue = true
106 break
107 }
108 }
109 e := errors.New(f, x...)
110 if hasValue {
111 return errors.New("(line %d:%d): %v", line, column, e)
112 }
113 return e
114}
115
Herbie Ongc96a79d2019-03-08 10:49:17 -0800116// unmarshalMessage unmarshals a message into the given protoreflect.Message.
Herbie Ong8ac9dd22019-03-27 12:20:50 -0700117func (o UnmarshalOptions) unmarshalMessage(m pref.Message, skipTypeURL bool) error {
Joe Tsai0fc49f82019-05-01 12:29:25 -0700118 if isCustomType(m.Descriptor().FullName()) {
Herbie Ong822de2d2019-03-27 13:16:23 -0700119 return o.unmarshalCustomType(m)
Herbie Onge63c4c42019-03-22 22:20:22 -0700120 }
Herbie Ongc96a79d2019-03-08 10:49:17 -0800121
Herbie Ong822de2d2019-03-27 13:16:23 -0700122 jval, err := o.decoder.Read()
Damien Neil8c86fc52019-06-19 09:28:29 -0700123 if err != nil {
Herbie Ongc96a79d2019-03-08 10:49:17 -0800124 return err
125 }
126 if jval.Type() != json.StartObject {
127 return unexpectedJSONError{jval}
128 }
129
Damien Neil8c86fc52019-06-19 09:28:29 -0700130 if err := o.unmarshalFields(m, skipTypeURL); err != nil {
Herbie Onge63c4c42019-03-22 22:20:22 -0700131 return err
132 }
133
Damien Neil8c86fc52019-06-19 09:28:29 -0700134 return nil
Herbie Onge63c4c42019-03-22 22:20:22 -0700135}
136
137// unmarshalFields unmarshals the fields into the given protoreflect.Message.
Herbie Ong8ac9dd22019-03-27 12:20:50 -0700138func (o UnmarshalOptions) unmarshalFields(m pref.Message, skipTypeURL bool) error {
Herbie Onge63c4c42019-03-22 22:20:22 -0700139 var seenNums set.Ints
Herbie Ong8a1d4602019-04-02 20:19:36 -0700140 var seenOneofs set.Ints
Herbie Onge63c4c42019-03-22 22:20:22 -0700141
Joe Tsai0fc49f82019-05-01 12:29:25 -0700142 messageDesc := m.Descriptor()
Joe Tsai0fc49f82019-05-01 12:29:25 -0700143 fieldDescs := messageDesc.Fields()
Herbie Onge63c4c42019-03-22 22:20:22 -0700144
Herbie Ongc96a79d2019-03-08 10:49:17 -0800145Loop:
146 for {
147 // Read field name.
Herbie Ong822de2d2019-03-27 13:16:23 -0700148 jval, err := o.decoder.Read()
Damien Neil8c86fc52019-06-19 09:28:29 -0700149 if err != nil {
Herbie Ongc96a79d2019-03-08 10:49:17 -0800150 return err
151 }
152 switch jval.Type() {
153 default:
154 return unexpectedJSONError{jval}
155 case json.EndObject:
156 break Loop
157 case json.Name:
158 // Continue below.
159 }
160
161 name, err := jval.Name()
Damien Neil8c86fc52019-06-19 09:28:29 -0700162 if err != nil {
Herbie Ongc96a79d2019-03-08 10:49:17 -0800163 return err
164 }
Herbie Ong8ac9dd22019-03-27 12:20:50 -0700165 // Unmarshaling a non-custom embedded message in Any will contain the
166 // JSON field "@type" which should be skipped because it is not a field
167 // of the embedded message, but simply an artifact of the Any format.
168 if skipTypeURL && name == "@type" {
169 o.decoder.Read()
170 continue
171 }
Herbie Ongc96a79d2019-03-08 10:49:17 -0800172
Herbie Onge52379a2019-03-15 18:00:19 -0700173 // Get the FieldDescriptor.
174 var fd pref.FieldDescriptor
175 if strings.HasPrefix(name, "[") && strings.HasSuffix(name, "]") {
176 // Only extension names are in [name] format.
Joe Tsai378c1322019-04-25 23:48:08 -0700177 extName := pref.FullName(name[1 : len(name)-1])
178 extType, err := o.findExtension(extName)
179 if err != nil && err != protoregistry.NotFound {
180 return errors.New("unable to resolve [%v]: %v", extName, err)
Herbie Onge52379a2019-03-15 18:00:19 -0700181 }
Joe Tsai378c1322019-04-25 23:48:08 -0700182 fd = extType
Herbie Onge52379a2019-03-15 18:00:19 -0700183 } else {
184 // The name can either be the JSON name or the proto field name.
185 fd = fieldDescs.ByJSONName(name)
186 if fd == nil {
187 fd = fieldDescs.ByName(pref.Name(name))
188 }
Joe Tsaid47ea192019-07-09 22:38:15 -0700189 if fd != nil && fd.IsWeak() && fd.Message().IsPlaceholder() {
190 fd = nil // reset since the weak reference is not linked in
191 }
Herbie Ongc96a79d2019-03-08 10:49:17 -0800192 }
193
194 if fd == nil {
195 // Field is unknown.
Herbie Ong4f0be712019-04-25 17:57:12 -0700196 if o.DiscardUnknown {
Damien Neil8c86fc52019-06-19 09:28:29 -0700197 if err := skipJSONValue(o.decoder); err != nil {
Herbie Ong4f0be712019-04-25 17:57:12 -0700198 return err
199 }
200 continue
201 }
Joe Tsai0fc49f82019-05-01 12:29:25 -0700202 return newError("%v contains unknown field %s", messageDesc.FullName(), jval)
Herbie Ongc96a79d2019-03-08 10:49:17 -0800203 }
204
205 // Do not allow duplicate fields.
206 num := uint64(fd.Number())
207 if seenNums.Has(num) {
Joe Tsai0fc49f82019-05-01 12:29:25 -0700208 return newError("%v contains repeated field %s", messageDesc.FullName(), jval)
Herbie Ongc96a79d2019-03-08 10:49:17 -0800209 }
210 seenNums.Set(num)
211
Herbie Onge63c4c42019-03-22 22:20:22 -0700212 // No need to set values for JSON null unless the field type is
Herbie Ong300b9fe2019-03-29 15:42:20 -0700213 // google.protobuf.Value or google.protobuf.NullValue.
214 if o.decoder.Peek() == json.Null && !isKnownValue(fd) && !isNullValue(fd) {
Herbie Ong822de2d2019-03-27 13:16:23 -0700215 o.decoder.Read()
Herbie Ongc96a79d2019-03-08 10:49:17 -0800216 continue
217 }
218
Joe Tsaiac31a352019-05-13 14:32:56 -0700219 switch {
220 case fd.IsList():
Joe Tsai378c1322019-04-25 23:48:08 -0700221 list := m.Mutable(fd).List()
Damien Neil8c86fc52019-06-19 09:28:29 -0700222 if err := o.unmarshalList(list, fd); err != nil {
Herbie Ongc96a79d2019-03-08 10:49:17 -0800223 return errors.New("%v|%q: %v", fd.FullName(), name, err)
224 }
Joe Tsaiac31a352019-05-13 14:32:56 -0700225 case fd.IsMap():
Joe Tsai378c1322019-04-25 23:48:08 -0700226 mmap := m.Mutable(fd).Map()
Damien Neil8c86fc52019-06-19 09:28:29 -0700227 if err := o.unmarshalMap(mmap, fd); err != nil {
Joe Tsaiac31a352019-05-13 14:32:56 -0700228 return errors.New("%v|%q: %v", fd.FullName(), name, err)
229 }
230 default:
Herbie Ong8a1d4602019-04-02 20:19:36 -0700231 // If field is a oneof, check if it has already been set.
Joe Tsaiac31a352019-05-13 14:32:56 -0700232 if od := fd.ContainingOneof(); od != nil {
Herbie Ong8a1d4602019-04-02 20:19:36 -0700233 idx := uint64(od.Index())
234 if seenOneofs.Has(idx) {
235 return errors.New("%v: oneof is already set", od.FullName())
236 }
237 seenOneofs.Set(idx)
238 }
239
Herbie Ongc96a79d2019-03-08 10:49:17 -0800240 // Required or optional fields.
Damien Neil8c86fc52019-06-19 09:28:29 -0700241 if err := o.unmarshalSingular(m, fd); err != nil {
Herbie Ongc96a79d2019-03-08 10:49:17 -0800242 return errors.New("%v|%q: %v", fd.FullName(), name, err)
243 }
Herbie Ongc96a79d2019-03-08 10:49:17 -0800244 }
245 }
246
Damien Neil8c86fc52019-06-19 09:28:29 -0700247 return nil
Herbie Ongc96a79d2019-03-08 10:49:17 -0800248}
249
Herbie Onge52379a2019-03-15 18:00:19 -0700250// findExtension returns protoreflect.ExtensionType from the resolver if found.
Herbie Ong822de2d2019-03-27 13:16:23 -0700251func (o UnmarshalOptions) findExtension(xtName pref.FullName) (pref.ExtensionType, error) {
252 xt, err := o.Resolver.FindExtensionByName(xtName)
Herbie Onge52379a2019-03-15 18:00:19 -0700253 if err == nil {
254 return xt, nil
255 }
256
257 // Check if this is a MessageSet extension field.
Herbie Ong822de2d2019-03-27 13:16:23 -0700258 xt, err = o.Resolver.FindExtensionByName(xtName + ".message_set_extension")
Herbie Onge52379a2019-03-15 18:00:19 -0700259 if err == nil && isMessageSetExtension(xt) {
260 return xt, nil
261 }
262 return nil, protoregistry.NotFound
263}
264
Herbie Ong300b9fe2019-03-29 15:42:20 -0700265func isKnownValue(fd pref.FieldDescriptor) bool {
Joe Tsaid24bc722019-04-15 23:39:09 -0700266 md := fd.Message()
Herbie Ong300b9fe2019-03-29 15:42:20 -0700267 return md != nil && md.FullName() == "google.protobuf.Value"
268}
269
270func isNullValue(fd pref.FieldDescriptor) bool {
Joe Tsaid24bc722019-04-15 23:39:09 -0700271 ed := fd.Enum()
Herbie Ong300b9fe2019-03-29 15:42:20 -0700272 return ed != nil && ed.FullName() == "google.protobuf.NullValue"
273}
274
Herbie Ongc96a79d2019-03-08 10:49:17 -0800275// unmarshalSingular unmarshals to the non-repeated field specified by the given
276// FieldDescriptor.
Joe Tsai378c1322019-04-25 23:48:08 -0700277func (o UnmarshalOptions) unmarshalSingular(m pref.Message, fd pref.FieldDescriptor) error {
Herbie Ongc96a79d2019-03-08 10:49:17 -0800278 var val pref.Value
279 var err error
Herbie Ongc96a79d2019-03-08 10:49:17 -0800280 switch fd.Kind() {
281 case pref.MessageKind, pref.GroupKind:
Joe Tsai378c1322019-04-25 23:48:08 -0700282 m2 := m.NewMessage(fd)
283 err = o.unmarshalMessage(m2, false)
284 val = pref.ValueOf(m2)
Herbie Ongc96a79d2019-03-08 10:49:17 -0800285 default:
Herbie Ong822de2d2019-03-27 13:16:23 -0700286 val, err = o.unmarshalScalar(fd)
Herbie Ongc96a79d2019-03-08 10:49:17 -0800287 }
288
Damien Neil8c86fc52019-06-19 09:28:29 -0700289 if err != nil {
Herbie Ongc96a79d2019-03-08 10:49:17 -0800290 return err
291 }
Joe Tsai378c1322019-04-25 23:48:08 -0700292 m.Set(fd, val)
Damien Neil8c86fc52019-06-19 09:28:29 -0700293 return nil
Herbie Ongc96a79d2019-03-08 10:49:17 -0800294}
295
296// unmarshalScalar unmarshals to a scalar/enum protoreflect.Value specified by
297// the given FieldDescriptor.
Herbie Ong822de2d2019-03-27 13:16:23 -0700298func (o UnmarshalOptions) unmarshalScalar(fd pref.FieldDescriptor) (pref.Value, error) {
Herbie Ongc96a79d2019-03-08 10:49:17 -0800299 const b32 int = 32
300 const b64 int = 64
301
Herbie Ong822de2d2019-03-27 13:16:23 -0700302 jval, err := o.decoder.Read()
Damien Neil8c86fc52019-06-19 09:28:29 -0700303 if err != nil {
Herbie Ongc96a79d2019-03-08 10:49:17 -0800304 return pref.Value{}, err
305 }
306
307 kind := fd.Kind()
308 switch kind {
309 case pref.BoolKind:
310 return unmarshalBool(jval)
311
312 case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind:
313 return unmarshalInt(jval, b32)
314
315 case pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind:
316 return unmarshalInt(jval, b64)
317
318 case pref.Uint32Kind, pref.Fixed32Kind:
319 return unmarshalUint(jval, b32)
320
321 case pref.Uint64Kind, pref.Fixed64Kind:
322 return unmarshalUint(jval, b64)
323
324 case pref.FloatKind:
325 return unmarshalFloat(jval, b32)
326
327 case pref.DoubleKind:
328 return unmarshalFloat(jval, b64)
329
330 case pref.StringKind:
331 pval, err := unmarshalString(jval)
Damien Neil8c86fc52019-06-19 09:28:29 -0700332 if err != nil {
Herbie Ongc96a79d2019-03-08 10:49:17 -0800333 return pval, err
334 }
Damien Neil8c86fc52019-06-19 09:28:29 -0700335 return pval, nil
Herbie Ongc96a79d2019-03-08 10:49:17 -0800336
337 case pref.BytesKind:
338 return unmarshalBytes(jval)
339
340 case pref.EnumKind:
341 return unmarshalEnum(jval, fd)
342 }
343
344 panic(fmt.Sprintf("invalid scalar kind %v", kind))
345}
346
347func unmarshalBool(jval json.Value) (pref.Value, error) {
348 if jval.Type() != json.Bool {
349 return pref.Value{}, unexpectedJSONError{jval}
350 }
351 b, err := jval.Bool()
352 return pref.ValueOf(b), err
353}
354
355func unmarshalInt(jval json.Value, bitSize int) (pref.Value, error) {
356 switch jval.Type() {
357 case json.Number:
358 return getInt(jval, bitSize)
359
360 case json.String:
Herbie Onge52379a2019-03-15 18:00:19 -0700361 // Decode number from string.
Herbie Ong06a6b0b2019-04-24 21:15:45 -0700362 s := strings.TrimSpace(jval.String())
363 if len(s) != len(jval.String()) {
364 return pref.Value{}, errors.New("invalid number %v", jval.Raw())
365 }
366 dec := json.NewDecoder([]byte(s))
Herbie Ongc96a79d2019-03-08 10:49:17 -0800367 jval, err := dec.Read()
Damien Neil8c86fc52019-06-19 09:28:29 -0700368 if err != nil {
Herbie Ongc96a79d2019-03-08 10:49:17 -0800369 return pref.Value{}, err
370 }
371 return getInt(jval, bitSize)
372 }
373 return pref.Value{}, unexpectedJSONError{jval}
374}
375
376func getInt(jval json.Value, bitSize int) (pref.Value, error) {
377 n, err := jval.Int(bitSize)
378 if err != nil {
379 return pref.Value{}, err
380 }
381 if bitSize == 32 {
382 return pref.ValueOf(int32(n)), nil
383 }
384 return pref.ValueOf(n), nil
385}
386
387func unmarshalUint(jval json.Value, bitSize int) (pref.Value, error) {
388 switch jval.Type() {
389 case json.Number:
390 return getUint(jval, bitSize)
391
392 case json.String:
Herbie Onge52379a2019-03-15 18:00:19 -0700393 // Decode number from string.
Herbie Ong06a6b0b2019-04-24 21:15:45 -0700394 s := strings.TrimSpace(jval.String())
395 if len(s) != len(jval.String()) {
396 return pref.Value{}, errors.New("invalid number %v", jval.Raw())
397 }
398 dec := json.NewDecoder([]byte(s))
Herbie Ongc96a79d2019-03-08 10:49:17 -0800399 jval, err := dec.Read()
Damien Neil8c86fc52019-06-19 09:28:29 -0700400 if err != nil {
Herbie Ongc96a79d2019-03-08 10:49:17 -0800401 return pref.Value{}, err
402 }
403 return getUint(jval, bitSize)
404 }
405 return pref.Value{}, unexpectedJSONError{jval}
406}
407
408func getUint(jval json.Value, bitSize int) (pref.Value, error) {
409 n, err := jval.Uint(bitSize)
410 if err != nil {
411 return pref.Value{}, err
412 }
413 if bitSize == 32 {
414 return pref.ValueOf(uint32(n)), nil
415 }
416 return pref.ValueOf(n), nil
417}
418
419func unmarshalFloat(jval json.Value, bitSize int) (pref.Value, error) {
420 switch jval.Type() {
421 case json.Number:
422 return getFloat(jval, bitSize)
423
424 case json.String:
425 s := jval.String()
426 switch s {
427 case "NaN":
428 if bitSize == 32 {
429 return pref.ValueOf(float32(math.NaN())), nil
430 }
431 return pref.ValueOf(math.NaN()), nil
432 case "Infinity":
433 if bitSize == 32 {
434 return pref.ValueOf(float32(math.Inf(+1))), nil
435 }
436 return pref.ValueOf(math.Inf(+1)), nil
437 case "-Infinity":
438 if bitSize == 32 {
439 return pref.ValueOf(float32(math.Inf(-1))), nil
440 }
441 return pref.ValueOf(math.Inf(-1)), nil
442 }
Herbie Onge52379a2019-03-15 18:00:19 -0700443 // Decode number from string.
Herbie Ong06a6b0b2019-04-24 21:15:45 -0700444 if len(s) != len(strings.TrimSpace(s)) {
445 return pref.Value{}, errors.New("invalid number %v", jval.Raw())
446 }
Herbie Onge52379a2019-03-15 18:00:19 -0700447 dec := json.NewDecoder([]byte(s))
Herbie Ongc96a79d2019-03-08 10:49:17 -0800448 jval, err := dec.Read()
Damien Neil8c86fc52019-06-19 09:28:29 -0700449 if err != nil {
Herbie Ongc96a79d2019-03-08 10:49:17 -0800450 return pref.Value{}, err
451 }
452 return getFloat(jval, bitSize)
453 }
454 return pref.Value{}, unexpectedJSONError{jval}
455}
456
457func getFloat(jval json.Value, bitSize int) (pref.Value, error) {
458 n, err := jval.Float(bitSize)
459 if err != nil {
460 return pref.Value{}, err
461 }
462 if bitSize == 32 {
463 return pref.ValueOf(float32(n)), nil
464 }
465 return pref.ValueOf(n), nil
466}
467
468func unmarshalString(jval json.Value) (pref.Value, error) {
469 if jval.Type() != json.String {
470 return pref.Value{}, unexpectedJSONError{jval}
471 }
472 return pref.ValueOf(jval.String()), nil
473}
474
475func unmarshalBytes(jval json.Value) (pref.Value, error) {
476 if jval.Type() != json.String {
477 return pref.Value{}, unexpectedJSONError{jval}
478 }
479
480 s := jval.String()
481 enc := base64.StdEncoding
482 if strings.ContainsAny(s, "-_") {
483 enc = base64.URLEncoding
484 }
485 if len(s)%4 != 0 {
486 enc = enc.WithPadding(base64.NoPadding)
487 }
488 b, err := enc.DecodeString(s)
489 if err != nil {
490 return pref.Value{}, err
491 }
492 return pref.ValueOf(b), nil
493}
494
495func unmarshalEnum(jval json.Value, fd pref.FieldDescriptor) (pref.Value, error) {
496 switch jval.Type() {
497 case json.String:
498 // Lookup EnumNumber based on name.
499 s := jval.String()
Joe Tsaid24bc722019-04-15 23:39:09 -0700500 if enumVal := fd.Enum().Values().ByName(pref.Name(s)); enumVal != nil {
Herbie Ongc96a79d2019-03-08 10:49:17 -0800501 return pref.ValueOf(enumVal.Number()), nil
502 }
503 return pref.Value{}, newError("invalid enum value %q", jval)
504
505 case json.Number:
506 n, err := jval.Int(32)
507 if err != nil {
508 return pref.Value{}, err
509 }
510 return pref.ValueOf(pref.EnumNumber(n)), nil
Herbie Ong300b9fe2019-03-29 15:42:20 -0700511
512 case json.Null:
513 // This is only valid for google.protobuf.NullValue.
514 if isNullValue(fd) {
515 return pref.ValueOf(pref.EnumNumber(0)), nil
516 }
Herbie Ongc96a79d2019-03-08 10:49:17 -0800517 }
518
519 return pref.Value{}, unexpectedJSONError{jval}
520}
521
Herbie Ong822de2d2019-03-27 13:16:23 -0700522func (o UnmarshalOptions) unmarshalList(list pref.List, fd pref.FieldDescriptor) error {
Herbie Ong822de2d2019-03-27 13:16:23 -0700523 jval, err := o.decoder.Read()
Damien Neil8c86fc52019-06-19 09:28:29 -0700524 if err != nil {
Herbie Ongc96a79d2019-03-08 10:49:17 -0800525 return err
526 }
527 if jval.Type() != json.StartArray {
528 return unexpectedJSONError{jval}
529 }
530
531 switch fd.Kind() {
532 case pref.MessageKind, pref.GroupKind:
533 for {
534 m := list.NewMessage()
Herbie Ong8ac9dd22019-03-27 12:20:50 -0700535 err := o.unmarshalMessage(m, false)
Damien Neil8c86fc52019-06-19 09:28:29 -0700536 if err != nil {
Herbie Ongc96a79d2019-03-08 10:49:17 -0800537 if e, ok := err.(unexpectedJSONError); ok {
538 if e.value.Type() == json.EndArray {
539 // Done with list.
Damien Neil8c86fc52019-06-19 09:28:29 -0700540 return nil
Herbie Ongc96a79d2019-03-08 10:49:17 -0800541 }
542 }
543 return err
544 }
545 list.Append(pref.ValueOf(m))
546 }
547 default:
548 for {
Herbie Ong822de2d2019-03-27 13:16:23 -0700549 val, err := o.unmarshalScalar(fd)
Damien Neil8c86fc52019-06-19 09:28:29 -0700550 if err != nil {
Herbie Ongc96a79d2019-03-08 10:49:17 -0800551 if e, ok := err.(unexpectedJSONError); ok {
552 if e.value.Type() == json.EndArray {
553 // Done with list.
Damien Neil8c86fc52019-06-19 09:28:29 -0700554 return nil
Herbie Ongc96a79d2019-03-08 10:49:17 -0800555 }
556 }
557 return err
558 }
559 list.Append(val)
560 }
561 }
Damien Neil8c86fc52019-06-19 09:28:29 -0700562 return nil
Herbie Ongc96a79d2019-03-08 10:49:17 -0800563}
564
Herbie Ong822de2d2019-03-27 13:16:23 -0700565func (o UnmarshalOptions) unmarshalMap(mmap pref.Map, fd pref.FieldDescriptor) error {
Herbie Ong822de2d2019-03-27 13:16:23 -0700566 jval, err := o.decoder.Read()
Damien Neil8c86fc52019-06-19 09:28:29 -0700567 if err != nil {
Herbie Ongc96a79d2019-03-08 10:49:17 -0800568 return err
569 }
570 if jval.Type() != json.StartObject {
571 return unexpectedJSONError{jval}
572 }
573
Herbie Ongc96a79d2019-03-08 10:49:17 -0800574 // Determine ahead whether map entry is a scalar type or a message type in
575 // order to call the appropriate unmarshalMapValue func inside the for loop
576 // below.
Joe Tsaiac31a352019-05-13 14:32:56 -0700577 var unmarshalMapValue func() (pref.Value, error)
578 switch fd.MapValue().Kind() {
Herbie Ongc96a79d2019-03-08 10:49:17 -0800579 case pref.MessageKind, pref.GroupKind:
580 unmarshalMapValue = func() (pref.Value, error) {
581 m := mmap.NewMessage()
Damien Neil8c86fc52019-06-19 09:28:29 -0700582 if err := o.unmarshalMessage(m, false); err != nil {
Herbie Ongc96a79d2019-03-08 10:49:17 -0800583 return pref.Value{}, err
584 }
Damien Neil8c86fc52019-06-19 09:28:29 -0700585 return pref.ValueOf(m), nil
Herbie Ongc96a79d2019-03-08 10:49:17 -0800586 }
Joe Tsaiac31a352019-05-13 14:32:56 -0700587 default:
588 unmarshalMapValue = func() (pref.Value, error) {
589 return o.unmarshalScalar(fd.MapValue())
590 }
Herbie Ongc96a79d2019-03-08 10:49:17 -0800591 }
592
593Loop:
594 for {
595 // Read field name.
Herbie Ong822de2d2019-03-27 13:16:23 -0700596 jval, err := o.decoder.Read()
Damien Neil8c86fc52019-06-19 09:28:29 -0700597 if err != nil {
Herbie Ongc96a79d2019-03-08 10:49:17 -0800598 return err
599 }
600 switch jval.Type() {
601 default:
602 return unexpectedJSONError{jval}
603 case json.EndObject:
604 break Loop
605 case json.Name:
606 // Continue.
607 }
608
609 name, err := jval.Name()
Damien Neil8c86fc52019-06-19 09:28:29 -0700610 if err != nil {
Herbie Ongc96a79d2019-03-08 10:49:17 -0800611 return err
612 }
613
614 // Unmarshal field name.
Joe Tsaiac31a352019-05-13 14:32:56 -0700615 pkey, err := unmarshalMapKey(name, fd.MapKey())
Damien Neil8c86fc52019-06-19 09:28:29 -0700616 if err != nil {
Herbie Ongc96a79d2019-03-08 10:49:17 -0800617 return err
618 }
619
620 // Check for duplicate field name.
621 if mmap.Has(pkey) {
622 return newError("duplicate map key %q", jval)
623 }
624
625 // Read and unmarshal field value.
626 pval, err := unmarshalMapValue()
Damien Neil8c86fc52019-06-19 09:28:29 -0700627 if err != nil {
Herbie Ongc96a79d2019-03-08 10:49:17 -0800628 return err
629 }
630
631 mmap.Set(pkey, pval)
632 }
633
Damien Neil8c86fc52019-06-19 09:28:29 -0700634 return nil
Herbie Ongc96a79d2019-03-08 10:49:17 -0800635}
636
637// unmarshalMapKey converts given string into a protoreflect.MapKey. A map key type is any
638// integral or string type.
639func unmarshalMapKey(name string, fd pref.FieldDescriptor) (pref.MapKey, error) {
640 const b32 = 32
641 const b64 = 64
642 const base10 = 10
643
644 kind := fd.Kind()
645 switch kind {
646 case pref.StringKind:
647 return pref.ValueOf(name).MapKey(), nil
648
649 case pref.BoolKind:
650 switch name {
651 case "true":
652 return pref.ValueOf(true).MapKey(), nil
653 case "false":
654 return pref.ValueOf(false).MapKey(), nil
655 }
656 return pref.MapKey{}, errors.New("invalid value for boolean key %q", name)
657
658 case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind:
659 n, err := strconv.ParseInt(name, base10, b32)
660 if err != nil {
661 return pref.MapKey{}, err
662 }
663 return pref.ValueOf(int32(n)).MapKey(), nil
664
665 case pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind:
666 n, err := strconv.ParseInt(name, base10, b64)
667 if err != nil {
668 return pref.MapKey{}, err
669 }
670 return pref.ValueOf(int64(n)).MapKey(), nil
671
672 case pref.Uint32Kind, pref.Fixed32Kind:
673 n, err := strconv.ParseUint(name, base10, b32)
674 if err != nil {
675 return pref.MapKey{}, err
676 }
677 return pref.ValueOf(uint32(n)).MapKey(), nil
678
679 case pref.Uint64Kind, pref.Fixed64Kind:
680 n, err := strconv.ParseUint(name, base10, b64)
681 if err != nil {
682 return pref.MapKey{}, err
683 }
684 return pref.ValueOf(uint64(n)).MapKey(), nil
685 }
686
687 panic(fmt.Sprintf("%s: invalid kind %s for map key", fd.FullName(), kind))
688}