| Buck Clay | 67cbcad | 2015-07-01 11:17:11 +1000 | [diff] [blame] | 1 | // Go support for Protocol Buffers - Google's data interchange format |
| 2 | // |
| 3 | // Copyright 2015 The Go Authors. All rights reserved. |
| 4 | // https://github.com/golang/protobuf |
| 5 | // |
| 6 | // Redistribution and use in source and binary forms, with or without |
| 7 | // modification, are permitted provided that the following conditions are |
| 8 | // met: |
| 9 | // |
| 10 | // * Redistributions of source code must retain the above copyright |
| 11 | // notice, this list of conditions and the following disclaimer. |
| 12 | // * Redistributions in binary form must reproduce the above |
| 13 | // copyright notice, this list of conditions and the following disclaimer |
| 14 | // in the documentation and/or other materials provided with the |
| 15 | // distribution. |
| 16 | // * Neither the name of Google Inc. nor the names of its |
| 17 | // contributors may be used to endorse or promote products derived from |
| 18 | // this software without specific prior written permission. |
| 19 | // |
| 20 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
| 21 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
| 22 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
| 23 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
| 24 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
| 25 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
| 26 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
| 27 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
| 28 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
| 29 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
| 30 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 31 | |
| 32 | /* |
| David Symonds | 5fc2294 | 2016-01-21 14:29:00 +1100 | [diff] [blame] | 33 | Package jsonpb provides marshaling and unmarshaling between protocol buffers and JSON. |
| 34 | It follows the specification at https://developers.google.com/protocol-buffers/docs/proto3#json. |
| Buck Clay | 67cbcad | 2015-07-01 11:17:11 +1000 | [diff] [blame] | 35 | |
| David Symonds | 5fc2294 | 2016-01-21 14:29:00 +1100 | [diff] [blame] | 36 | This package produces a different output than the standard "encoding/json" package, |
| 37 | which does not operate correctly on protocol buffers. |
| Buck Clay | 67cbcad | 2015-07-01 11:17:11 +1000 | [diff] [blame] | 38 | */ |
| 39 | package jsonpb |
| 40 | |
| 41 | import ( |
| 42 | "bytes" |
| 43 | "encoding/json" |
| 44 | "fmt" |
| 45 | "io" |
| 46 | "reflect" |
| 47 | "sort" |
| 48 | "strconv" |
| 49 | "strings" |
| 50 | |
| 51 | "github.com/golang/protobuf/proto" |
| 52 | ) |
| 53 | |
| 54 | var ( |
| 55 | byteArrayType = reflect.TypeOf([]byte{}) |
| 56 | ) |
| 57 | |
| David Symonds | 21f8136 | 2015-08-17 11:59:00 +1000 | [diff] [blame] | 58 | // Marshaler is a configurable object for converting between |
| David Symonds | 45bba20 | 2016-01-29 08:30:00 +1100 | [diff] [blame] | 59 | // protocol buffer objects and a JSON representation for them. |
| David Symonds | 21f8136 | 2015-08-17 11:59:00 +1000 | [diff] [blame] | 60 | type Marshaler struct { |
| David Symonds | 0ea3c03 | 2015-10-19 13:53:00 +1100 | [diff] [blame] | 61 | // Whether to render enum values as integers, as opposed to string values. |
| 62 | EnumsAsInts bool |
| 63 | |
| David Symonds | 45bba20 | 2016-01-29 08:30:00 +1100 | [diff] [blame] | 64 | // Whether to render fields with zero values. |
| 65 | EmitDefaults bool |
| 66 | |
| Buck Clay | 67cbcad | 2015-07-01 11:17:11 +1000 | [diff] [blame] | 67 | // A string to indent each level by. The presence of this field will |
| 68 | // also cause a space to appear between the field separator and |
| 69 | // value, and for newlines to be appear between fields and array |
| 70 | // elements. |
| 71 | Indent string |
| 72 | } |
| 73 | |
| 74 | // Marshal marshals a protocol buffer into JSON. |
| David Symonds | 21f8136 | 2015-08-17 11:59:00 +1000 | [diff] [blame] | 75 | func (m *Marshaler) Marshal(out io.Writer, pb proto.Message) error { |
| Buck Clay | 67cbcad | 2015-07-01 11:17:11 +1000 | [diff] [blame] | 76 | writer := &errWriter{writer: out} |
| 77 | return m.marshalObject(writer, pb, "") |
| 78 | } |
| 79 | |
| 80 | // MarshalToString converts a protocol buffer object to JSON string. |
| David Symonds | 21f8136 | 2015-08-17 11:59:00 +1000 | [diff] [blame] | 81 | func (m *Marshaler) MarshalToString(pb proto.Message) (string, error) { |
| Buck Clay | 67cbcad | 2015-07-01 11:17:11 +1000 | [diff] [blame] | 82 | var buf bytes.Buffer |
| 83 | if err := m.Marshal(&buf, pb); err != nil { |
| 84 | return "", err |
| 85 | } |
| 86 | return buf.String(), nil |
| 87 | } |
| 88 | |
| Juraj Stacho | f9dd693 | 2015-11-03 18:47:00 +1100 | [diff] [blame] | 89 | type int32Slice []int32 |
| 90 | |
| 91 | // For sorting extensions ids to ensure stable output. |
| 92 | func (s int32Slice) Len() int { return len(s) } |
| 93 | func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] } |
| 94 | func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } |
| 95 | |
| Buck Clay | 67cbcad | 2015-07-01 11:17:11 +1000 | [diff] [blame] | 96 | // marshalObject writes a struct to the Writer. |
| David Symonds | 21f8136 | 2015-08-17 11:59:00 +1000 | [diff] [blame] | 97 | func (m *Marshaler) marshalObject(out *errWriter, v proto.Message, indent string) error { |
| Buck Clay | 67cbcad | 2015-07-01 11:17:11 +1000 | [diff] [blame] | 98 | out.write("{") |
| 99 | if m.Indent != "" { |
| 100 | out.write("\n") |
| 101 | } |
| 102 | |
| 103 | s := reflect.ValueOf(v).Elem() |
| Juraj Stacho | f9dd693 | 2015-11-03 18:47:00 +1100 | [diff] [blame] | 104 | firstField := true |
| Buck Clay | 67cbcad | 2015-07-01 11:17:11 +1000 | [diff] [blame] | 105 | for i := 0; i < s.NumField(); i++ { |
| 106 | value := s.Field(i) |
| 107 | valueField := s.Type().Field(i) |
| David Symonds | 31db569 | 2015-08-10 12:45:00 +1000 | [diff] [blame] | 108 | if strings.HasPrefix(valueField.Name, "XXX_") { |
| Buck Clay | 67cbcad | 2015-07-01 11:17:11 +1000 | [diff] [blame] | 109 | continue |
| David Symonds | 31db569 | 2015-08-10 12:45:00 +1000 | [diff] [blame] | 110 | } |
| David Symonds | 31db569 | 2015-08-10 12:45:00 +1000 | [diff] [blame] | 111 | |
| David Symonds | 31db569 | 2015-08-10 12:45:00 +1000 | [diff] [blame] | 112 | // IsNil will panic on most value kinds. |
| 113 | switch value.Kind() { |
| 114 | case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: |
| 115 | if value.IsNil() { |
| Buck Clay | 67cbcad | 2015-07-01 11:17:11 +1000 | [diff] [blame] | 116 | continue |
| 117 | } |
| 118 | } |
| 119 | |
| David Symonds | 45bba20 | 2016-01-29 08:30:00 +1100 | [diff] [blame] | 120 | if !m.EmitDefaults { |
| 121 | switch value.Kind() { |
| 122 | case reflect.Bool: |
| 123 | if !value.Bool() { |
| 124 | continue |
| 125 | } |
| 126 | case reflect.Int32, reflect.Int64: |
| 127 | if value.Int() == 0 { |
| 128 | continue |
| 129 | } |
| 130 | case reflect.Uint32, reflect.Uint64: |
| 131 | if value.Uint() == 0 { |
| 132 | continue |
| 133 | } |
| 134 | case reflect.Float32, reflect.Float64: |
| 135 | if value.Float() == 0 { |
| 136 | continue |
| 137 | } |
| 138 | case reflect.String: |
| 139 | if value.Len() == 0 { |
| 140 | continue |
| 141 | } |
| 142 | } |
| 143 | } |
| 144 | |
| David Symonds | 59b73b3 | 2015-08-24 13:22:02 +1000 | [diff] [blame] | 145 | // Oneof fields need special handling. |
| 146 | if valueField.Tag.Get("protobuf_oneof") != "" { |
| 147 | // value is an interface containing &T{real_value}. |
| 148 | sv := value.Elem().Elem() // interface -> *T -> T |
| 149 | value = sv.Field(0) |
| 150 | valueField = sv.Type().Field(0) |
| David Symonds | 59b73b3 | 2015-08-24 13:22:02 +1000 | [diff] [blame] | 151 | } |
| Juraj Stacho | f9dd693 | 2015-11-03 18:47:00 +1100 | [diff] [blame] | 152 | prop := jsonProperties(valueField) |
| 153 | if !firstField { |
| 154 | m.writeSep(out) |
| Buck Clay | 67cbcad | 2015-07-01 11:17:11 +1000 | [diff] [blame] | 155 | } |
| Juraj Stacho | f9dd693 | 2015-11-03 18:47:00 +1100 | [diff] [blame] | 156 | if err := m.marshalField(out, prop, value, indent); err != nil { |
| Buck Clay | 67cbcad | 2015-07-01 11:17:11 +1000 | [diff] [blame] | 157 | return err |
| 158 | } |
| Juraj Stacho | f9dd693 | 2015-11-03 18:47:00 +1100 | [diff] [blame] | 159 | firstField = false |
| 160 | } |
| Buck Clay | 67cbcad | 2015-07-01 11:17:11 +1000 | [diff] [blame] | 161 | |
| Juraj Stacho | f9dd693 | 2015-11-03 18:47:00 +1100 | [diff] [blame] | 162 | // Handle proto2 extensions. |
| 163 | if ep, ok := v.(extendableProto); ok { |
| 164 | extensions := proto.RegisteredExtensions(v) |
| 165 | extensionMap := ep.ExtensionMap() |
| 166 | // Sort extensions for stable output. |
| 167 | ids := make([]int32, 0, len(extensionMap)) |
| 168 | for id := range extensionMap { |
| 169 | ids = append(ids, id) |
| Buck Clay | 67cbcad | 2015-07-01 11:17:11 +1000 | [diff] [blame] | 170 | } |
| Juraj Stacho | f9dd693 | 2015-11-03 18:47:00 +1100 | [diff] [blame] | 171 | sort.Sort(int32Slice(ids)) |
| 172 | for _, id := range ids { |
| 173 | desc := extensions[id] |
| 174 | if desc == nil { |
| 175 | // unknown extension |
| 176 | continue |
| 177 | } |
| 178 | ext, extErr := proto.GetExtension(ep, desc) |
| 179 | if extErr != nil { |
| 180 | return extErr |
| 181 | } |
| 182 | value := reflect.ValueOf(ext) |
| 183 | var prop proto.Properties |
| 184 | prop.Parse(desc.Tag) |
| 185 | prop.OrigName = fmt.Sprintf("[%s]", desc.Name) |
| 186 | if !firstField { |
| 187 | m.writeSep(out) |
| 188 | } |
| 189 | if err := m.marshalField(out, &prop, value, indent); err != nil { |
| 190 | return err |
| 191 | } |
| 192 | firstField = false |
| 193 | } |
| 194 | |
| Buck Clay | 67cbcad | 2015-07-01 11:17:11 +1000 | [diff] [blame] | 195 | } |
| 196 | |
| 197 | if m.Indent != "" { |
| 198 | out.write("\n") |
| 199 | out.write(indent) |
| 200 | } |
| 201 | out.write("}") |
| 202 | return out.err |
| 203 | } |
| 204 | |
| Juraj Stacho | f9dd693 | 2015-11-03 18:47:00 +1100 | [diff] [blame] | 205 | func (m *Marshaler) writeSep(out *errWriter) { |
| 206 | if m.Indent != "" { |
| 207 | out.write(",\n") |
| 208 | } else { |
| 209 | out.write(",") |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | // marshalField writes field description and value to the Writer. |
| 214 | func (m *Marshaler) marshalField(out *errWriter, prop *proto.Properties, v reflect.Value, indent string) error { |
| 215 | if m.Indent != "" { |
| 216 | out.write(indent) |
| 217 | out.write(m.Indent) |
| 218 | } |
| 219 | out.write(`"`) |
| 220 | out.write(prop.OrigName) |
| 221 | out.write(`":`) |
| 222 | if m.Indent != "" { |
| 223 | out.write(" ") |
| 224 | } |
| 225 | if err := m.marshalValue(out, prop, v, indent); err != nil { |
| 226 | return err |
| 227 | } |
| 228 | return nil |
| 229 | } |
| 230 | |
| Buck Clay | 67cbcad | 2015-07-01 11:17:11 +1000 | [diff] [blame] | 231 | // marshalValue writes the value to the Writer. |
| Juraj Stacho | f9dd693 | 2015-11-03 18:47:00 +1100 | [diff] [blame] | 232 | func (m *Marshaler) marshalValue(out *errWriter, prop *proto.Properties, v reflect.Value, indent string) error { |
| Buck Clay | 67cbcad | 2015-07-01 11:17:11 +1000 | [diff] [blame] | 233 | |
| 234 | var err error |
| 235 | v = reflect.Indirect(v) |
| 236 | |
| 237 | // Handle repeated elements. |
| 238 | if v.Type() != byteArrayType && v.Kind() == reflect.Slice { |
| 239 | out.write("[") |
| 240 | comma := "" |
| 241 | for i := 0; i < v.Len(); i++ { |
| 242 | sliceVal := v.Index(i) |
| 243 | out.write(comma) |
| 244 | if m.Indent != "" { |
| 245 | out.write("\n") |
| 246 | out.write(indent) |
| 247 | out.write(m.Indent) |
| 248 | out.write(m.Indent) |
| 249 | } |
| Juraj Stacho | f9dd693 | 2015-11-03 18:47:00 +1100 | [diff] [blame] | 250 | m.marshalValue(out, prop, sliceVal, indent+m.Indent) |
| Buck Clay | 67cbcad | 2015-07-01 11:17:11 +1000 | [diff] [blame] | 251 | comma = "," |
| 252 | } |
| 253 | if m.Indent != "" { |
| 254 | out.write("\n") |
| 255 | out.write(indent) |
| 256 | out.write(m.Indent) |
| 257 | } |
| 258 | out.write("]") |
| 259 | return out.err |
| 260 | } |
| 261 | |
| 262 | // Handle enumerations. |
| Juraj Stacho | f9dd693 | 2015-11-03 18:47:00 +1100 | [diff] [blame] | 263 | if !m.EnumsAsInts && prop.Enum != "" { |
| Buck Clay | 67cbcad | 2015-07-01 11:17:11 +1000 | [diff] [blame] | 264 | // Unknown enum values will are stringified by the proto library as their |
| David Symonds | 0ea3c03 | 2015-10-19 13:53:00 +1100 | [diff] [blame] | 265 | // value. Such values should _not_ be quoted or they will be interpreted |
| Buck Clay | 67cbcad | 2015-07-01 11:17:11 +1000 | [diff] [blame] | 266 | // as an enum string instead of their value. |
| 267 | enumStr := v.Interface().(fmt.Stringer).String() |
| 268 | var valStr string |
| 269 | if v.Kind() == reflect.Ptr { |
| 270 | valStr = strconv.Itoa(int(v.Elem().Int())) |
| 271 | } else { |
| 272 | valStr = strconv.Itoa(int(v.Int())) |
| 273 | } |
| 274 | isKnownEnum := enumStr != valStr |
| 275 | if isKnownEnum { |
| 276 | out.write(`"`) |
| 277 | } |
| 278 | out.write(enumStr) |
| 279 | if isKnownEnum { |
| 280 | out.write(`"`) |
| 281 | } |
| 282 | return out.err |
| 283 | } |
| 284 | |
| 285 | // Handle nested messages. |
| 286 | if v.Kind() == reflect.Struct { |
| 287 | return m.marshalObject(out, v.Addr().Interface().(proto.Message), indent+m.Indent) |
| 288 | } |
| 289 | |
| 290 | // Handle maps. |
| David Symonds | 3fe63ce | 2015-08-07 15:00:00 +1000 | [diff] [blame] | 291 | // Since Go randomizes map iteration, we sort keys for stable output. |
| Buck Clay | 67cbcad | 2015-07-01 11:17:11 +1000 | [diff] [blame] | 292 | if v.Kind() == reflect.Map { |
| 293 | out.write(`{`) |
| 294 | keys := v.MapKeys() |
| 295 | sort.Sort(mapKeys(keys)) |
| 296 | for i, k := range keys { |
| 297 | if i > 0 { |
| 298 | out.write(`,`) |
| 299 | } |
| 300 | if m.Indent != "" { |
| 301 | out.write("\n") |
| 302 | out.write(indent) |
| 303 | out.write(m.Indent) |
| 304 | out.write(m.Indent) |
| 305 | } |
| 306 | |
| 307 | b, err := json.Marshal(k.Interface()) |
| 308 | if err != nil { |
| 309 | return err |
| 310 | } |
| 311 | s := string(b) |
| 312 | |
| 313 | // If the JSON is not a string value, encode it again to make it one. |
| 314 | if !strings.HasPrefix(s, `"`) { |
| 315 | b, err := json.Marshal(s) |
| 316 | if err != nil { |
| 317 | return err |
| 318 | } |
| 319 | s = string(b) |
| 320 | } |
| 321 | |
| 322 | out.write(s) |
| 323 | out.write(`:`) |
| 324 | if m.Indent != "" { |
| 325 | out.write(` `) |
| 326 | } |
| 327 | |
| Juraj Stacho | f9dd693 | 2015-11-03 18:47:00 +1100 | [diff] [blame] | 328 | if err := m.marshalValue(out, prop, v.MapIndex(k), indent+m.Indent); err != nil { |
| Buck Clay | 67cbcad | 2015-07-01 11:17:11 +1000 | [diff] [blame] | 329 | return err |
| 330 | } |
| 331 | } |
| 332 | if m.Indent != "" { |
| 333 | out.write("\n") |
| 334 | out.write(indent) |
| 335 | out.write(m.Indent) |
| 336 | } |
| 337 | out.write(`}`) |
| 338 | return out.err |
| 339 | } |
| 340 | |
| 341 | // Default handling defers to the encoding/json library. |
| 342 | b, err := json.Marshal(v.Interface()) |
| 343 | if err != nil { |
| 344 | return err |
| 345 | } |
| 346 | needToQuote := string(b[0]) != `"` && (v.Kind() == reflect.Int64 || v.Kind() == reflect.Uint64) |
| 347 | if needToQuote { |
| 348 | out.write(`"`) |
| 349 | } |
| 350 | out.write(string(b)) |
| 351 | if needToQuote { |
| 352 | out.write(`"`) |
| 353 | } |
| 354 | return out.err |
| 355 | } |
| 356 | |
| 357 | // Unmarshal unmarshals a JSON object stream into a protocol |
| 358 | // buffer. This function is lenient and will decode any options |
| David Symonds | 21f8136 | 2015-08-17 11:59:00 +1000 | [diff] [blame] | 359 | // permutations of the related Marshaler. |
| Buck Clay | 67cbcad | 2015-07-01 11:17:11 +1000 | [diff] [blame] | 360 | func Unmarshal(r io.Reader, pb proto.Message) error { |
| 361 | inputValue := json.RawMessage{} |
| 362 | if err := json.NewDecoder(r).Decode(&inputValue); err != nil { |
| 363 | return err |
| 364 | } |
| 365 | return unmarshalValue(reflect.ValueOf(pb).Elem(), inputValue) |
| 366 | } |
| 367 | |
| 368 | // UnmarshalString will populate the fields of a protocol buffer based |
| 369 | // on a JSON string. This function is lenient and will decode any options |
| David Symonds | 21f8136 | 2015-08-17 11:59:00 +1000 | [diff] [blame] | 370 | // permutations of the related Marshaler. |
| Buck Clay | 67cbcad | 2015-07-01 11:17:11 +1000 | [diff] [blame] | 371 | func UnmarshalString(str string, pb proto.Message) error { |
| David Symonds | 5d7f79b | 2015-10-19 11:37:00 +1100 | [diff] [blame] | 372 | return Unmarshal(strings.NewReader(str), pb) |
| Buck Clay | 67cbcad | 2015-07-01 11:17:11 +1000 | [diff] [blame] | 373 | } |
| 374 | |
| 375 | // unmarshalValue converts/copies a value into the target. |
| 376 | func unmarshalValue(target reflect.Value, inputValue json.RawMessage) error { |
| 377 | targetType := target.Type() |
| 378 | |
| 379 | // Allocate memory for pointer fields. |
| 380 | if targetType.Kind() == reflect.Ptr { |
| 381 | target.Set(reflect.New(targetType.Elem())) |
| 382 | return unmarshalValue(target.Elem(), inputValue) |
| 383 | } |
| 384 | |
| 385 | // Handle nested messages. |
| 386 | if targetType.Kind() == reflect.Struct { |
| 387 | var jsonFields map[string]json.RawMessage |
| 388 | if err := json.Unmarshal(inputValue, &jsonFields); err != nil { |
| 389 | return err |
| 390 | } |
| 391 | |
| David Symonds | 5d7f79b | 2015-10-19 11:37:00 +1100 | [diff] [blame] | 392 | sprops := proto.GetProperties(targetType) |
| Buck Clay | 67cbcad | 2015-07-01 11:17:11 +1000 | [diff] [blame] | 393 | for i := 0; i < target.NumField(); i++ { |
| David Symonds | 31db569 | 2015-08-10 12:45:00 +1000 | [diff] [blame] | 394 | ft := target.Type().Field(i) |
| 395 | if strings.HasPrefix(ft.Name, "XXX_") { |
| Buck Clay | 67cbcad | 2015-07-01 11:17:11 +1000 | [diff] [blame] | 396 | continue |
| 397 | } |
| Juraj Stacho | f9dd693 | 2015-11-03 18:47:00 +1100 | [diff] [blame] | 398 | fieldName := jsonProperties(ft).OrigName |
| Buck Clay | 67cbcad | 2015-07-01 11:17:11 +1000 | [diff] [blame] | 399 | |
| David Symonds | 5d7f79b | 2015-10-19 11:37:00 +1100 | [diff] [blame] | 400 | valueForField, ok := jsonFields[fieldName] |
| 401 | if !ok { |
| 402 | continue |
| 403 | } |
| 404 | delete(jsonFields, fieldName) |
| 405 | |
| 406 | // Handle enums, which have an underlying type of int32, |
| 407 | // and may appear as strings. We do this while handling |
| 408 | // the struct so we have access to the enum info. |
| 409 | // The case of an enum appearing as a number is handled |
| 410 | // by the recursive call to unmarshalValue. |
| 411 | if enum := sprops.Prop[i].Enum; valueForField[0] == '"' && enum != "" { |
| 412 | vmap := proto.EnumValueMap(enum) |
| 413 | // Don't need to do unquoting; valid enum names |
| 414 | // are from a limited character set. |
| 415 | s := valueForField[1 : len(valueForField)-1] |
| 416 | n, ok := vmap[string(s)] |
| 417 | if !ok { |
| 418 | return fmt.Errorf("unknown value %q for enum %s", s, enum) |
| Buck Clay | 67cbcad | 2015-07-01 11:17:11 +1000 | [diff] [blame] | 419 | } |
| David Symonds | 5d7f79b | 2015-10-19 11:37:00 +1100 | [diff] [blame] | 420 | f := target.Field(i) |
| 421 | if f.Kind() == reflect.Ptr { // proto2 |
| 422 | f.Set(reflect.New(f.Type().Elem())) |
| 423 | f = f.Elem() |
| 424 | } |
| 425 | f.SetInt(int64(n)) |
| 426 | continue |
| 427 | } |
| 428 | |
| 429 | if err := unmarshalValue(target.Field(i), valueForField); err != nil { |
| 430 | return err |
| Buck Clay | 67cbcad | 2015-07-01 11:17:11 +1000 | [diff] [blame] | 431 | } |
| 432 | } |
| David Symonds | 59b73b3 | 2015-08-24 13:22:02 +1000 | [diff] [blame] | 433 | // Check for any oneof fields. |
| David Symonds | 59b73b3 | 2015-08-24 13:22:02 +1000 | [diff] [blame] | 434 | for fname, raw := range jsonFields { |
| David Symonds | 1baed09 | 2015-08-25 15:42:00 +1000 | [diff] [blame] | 435 | if oop, ok := sprops.OneofTypes[fname]; ok { |
| 436 | nv := reflect.New(oop.Type.Elem()) |
| 437 | target.Field(oop.Field).Set(nv) |
| David Symonds | 59b73b3 | 2015-08-24 13:22:02 +1000 | [diff] [blame] | 438 | if err := unmarshalValue(nv.Elem().Field(0), raw); err != nil { |
| 439 | return err |
| 440 | } |
| 441 | delete(jsonFields, fname) |
| David Symonds | 59b73b3 | 2015-08-24 13:22:02 +1000 | [diff] [blame] | 442 | } |
| 443 | } |
| David Symonds | 3fe63ce | 2015-08-07 15:00:00 +1000 | [diff] [blame] | 444 | if len(jsonFields) > 0 { |
| 445 | // Pick any field to be the scapegoat. |
| 446 | var f string |
| 447 | for fname := range jsonFields { |
| 448 | f = fname |
| 449 | break |
| 450 | } |
| 451 | return fmt.Errorf("unknown field %q in %v", f, targetType) |
| 452 | } |
| Buck Clay | 67cbcad | 2015-07-01 11:17:11 +1000 | [diff] [blame] | 453 | return nil |
| 454 | } |
| 455 | |
| 456 | // Handle arrays (which aren't encoded bytes) |
| 457 | if targetType != byteArrayType && targetType.Kind() == reflect.Slice { |
| 458 | var slc []json.RawMessage |
| 459 | if err := json.Unmarshal(inputValue, &slc); err != nil { |
| 460 | return err |
| 461 | } |
| 462 | len := len(slc) |
| 463 | target.Set(reflect.MakeSlice(targetType, len, len)) |
| 464 | for i := 0; i < len; i++ { |
| 465 | if err := unmarshalValue(target.Index(i), slc[i]); err != nil { |
| 466 | return err |
| 467 | } |
| 468 | } |
| 469 | return nil |
| 470 | } |
| 471 | |
| 472 | // Handle maps (whose keys are always strings) |
| 473 | if targetType.Kind() == reflect.Map { |
| 474 | var mp map[string]json.RawMessage |
| 475 | if err := json.Unmarshal(inputValue, &mp); err != nil { |
| 476 | return err |
| 477 | } |
| 478 | target.Set(reflect.MakeMap(targetType)) |
| 479 | for ks, raw := range mp { |
| 480 | // Unmarshal map key. The core json library already decoded the key into a |
| 481 | // string, so we handle that specially. Other types were quoted post-serialization. |
| 482 | var k reflect.Value |
| 483 | if targetType.Key().Kind() == reflect.String { |
| 484 | k = reflect.ValueOf(ks) |
| 485 | } else { |
| 486 | k = reflect.New(targetType.Key()).Elem() |
| 487 | if err := unmarshalValue(k, json.RawMessage(ks)); err != nil { |
| 488 | return err |
| 489 | } |
| 490 | } |
| 491 | |
| 492 | // Unmarshal map value. |
| 493 | v := reflect.New(targetType.Elem()).Elem() |
| 494 | if err := unmarshalValue(v, raw); err != nil { |
| 495 | return err |
| 496 | } |
| 497 | target.SetMapIndex(k, v) |
| 498 | } |
| 499 | return nil |
| 500 | } |
| 501 | |
| 502 | // 64-bit integers can be encoded as strings. In this case we drop |
| 503 | // the quotes and proceed as normal. |
| 504 | isNum := targetType.Kind() == reflect.Int64 || targetType.Kind() == reflect.Uint64 |
| 505 | if isNum && strings.HasPrefix(string(inputValue), `"`) { |
| 506 | inputValue = inputValue[1 : len(inputValue)-1] |
| 507 | } |
| 508 | |
| 509 | // Use the encoding/json for parsing other value types. |
| 510 | return json.Unmarshal(inputValue, target.Addr().Interface()) |
| 511 | } |
| 512 | |
| Juraj Stacho | f9dd693 | 2015-11-03 18:47:00 +1100 | [diff] [blame] | 513 | // jsonProperties returns parsed proto.Properties for the field. |
| 514 | func jsonProperties(f reflect.StructField) *proto.Properties { |
| David Symonds | 31db569 | 2015-08-10 12:45:00 +1000 | [diff] [blame] | 515 | var prop proto.Properties |
| 516 | prop.Init(f.Type, f.Name, f.Tag.Get("protobuf"), &f) |
| Juraj Stacho | f9dd693 | 2015-11-03 18:47:00 +1100 | [diff] [blame] | 517 | return &prop |
| 518 | } |
| 519 | |
| 520 | // extendableProto is an interface implemented by any protocol buffer that may be extended. |
| 521 | type extendableProto interface { |
| 522 | proto.Message |
| 523 | ExtensionRangeArray() []proto.ExtensionRange |
| 524 | ExtensionMap() map[int32]proto.Extension |
| Buck Clay | 67cbcad | 2015-07-01 11:17:11 +1000 | [diff] [blame] | 525 | } |
| 526 | |
| 527 | // Writer wrapper inspired by https://blog.golang.org/errors-are-values |
| 528 | type errWriter struct { |
| 529 | writer io.Writer |
| 530 | err error |
| 531 | } |
| 532 | |
| 533 | func (w *errWriter) write(str string) { |
| 534 | if w.err != nil { |
| 535 | return |
| 536 | } |
| 537 | _, w.err = w.writer.Write([]byte(str)) |
| 538 | } |
| 539 | |
| 540 | // Map fields may have key types of non-float scalars, strings and enums. |
| 541 | // The easiest way to sort them in some deterministic order is to use fmt. |
| 542 | // If this turns out to be inefficient we can always consider other options, |
| 543 | // such as doing a Schwartzian transform. |
| 544 | type mapKeys []reflect.Value |
| 545 | |
| 546 | func (s mapKeys) Len() int { return len(s) } |
| 547 | func (s mapKeys) Swap(i, j int) { s[i], s[j] = s[j], s[i] } |
| 548 | func (s mapKeys) Less(i, j int) bool { |
| 549 | return fmt.Sprint(s[i].Interface()) < fmt.Sprint(s[j].Interface()) |
| 550 | } |