jsonpb.go 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263
  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. Package jsonpb provides marshaling and unmarshaling between protocol buffers and JSON.
  33. It follows the specification at https://developers.google.com/protocol-buffers/docs/proto3#json.
  34. This package produces a different output than the standard "encoding/json" package,
  35. which does not operate correctly on protocol buffers.
  36. */
  37. package jsonpb
  38. import (
  39. "bytes"
  40. "encoding/json"
  41. "errors"
  42. "fmt"
  43. "io"
  44. "math"
  45. "reflect"
  46. "sort"
  47. "strconv"
  48. "strings"
  49. "time"
  50. "github.com/golang/protobuf/proto"
  51. stpb "github.com/golang/protobuf/ptypes/struct"
  52. )
  53. const secondInNanos = int64(time.Second / time.Nanosecond)
  54. // Marshaler is a configurable object for converting between
  55. // protocol buffer objects and a JSON representation for them.
  56. type Marshaler struct {
  57. // Whether to render enum values as integers, as opposed to string values.
  58. EnumsAsInts bool
  59. // Whether to render fields with zero values.
  60. EmitDefaults bool
  61. // A string to indent each level by. The presence of this field will
  62. // also cause a space to appear between the field separator and
  63. // value, and for newlines to be appear between fields and array
  64. // elements.
  65. Indent string
  66. // Whether to use the original (.proto) name for fields.
  67. OrigName bool
  68. // A custom URL resolver to use when marshaling Any messages to JSON.
  69. // If unset, the default resolution strategy is to extract the
  70. // fully-qualified type name from the type URL and pass that to
  71. // proto.MessageType(string).
  72. AnyResolver AnyResolver
  73. }
  74. // AnyResolver takes a type URL, present in an Any message, and resolves it into
  75. // an instance of the associated message.
  76. type AnyResolver interface {
  77. Resolve(typeUrl string) (proto.Message, error)
  78. }
  79. func defaultResolveAny(typeUrl string) (proto.Message, error) {
  80. // Only the part of typeUrl after the last slash is relevant.
  81. mname := typeUrl
  82. if slash := strings.LastIndex(mname, "/"); slash >= 0 {
  83. mname = mname[slash+1:]
  84. }
  85. mt := proto.MessageType(mname)
  86. if mt == nil {
  87. return nil, fmt.Errorf("unknown message type %q", mname)
  88. }
  89. return reflect.New(mt.Elem()).Interface().(proto.Message), nil
  90. }
  91. // JSONPBMarshaler is implemented by protobuf messages that customize the
  92. // way they are marshaled to JSON. Messages that implement this should
  93. // also implement JSONPBUnmarshaler so that the custom format can be
  94. // parsed.
  95. type JSONPBMarshaler interface {
  96. MarshalJSONPB(*Marshaler) ([]byte, error)
  97. }
  98. // JSONPBUnmarshaler is implemented by protobuf messages that customize
  99. // the way they are unmarshaled from JSON. Messages that implement this
  100. // should also implement JSONPBMarshaler so that the custom format can be
  101. // produced.
  102. type JSONPBUnmarshaler interface {
  103. UnmarshalJSONPB(*Unmarshaler, []byte) error
  104. }
  105. // Marshal marshals a protocol buffer into JSON.
  106. func (m *Marshaler) Marshal(out io.Writer, pb proto.Message) error {
  107. v := reflect.ValueOf(pb)
  108. if pb == nil || (v.Kind() == reflect.Ptr && v.IsNil()) {
  109. return errors.New("Marshal called with nil")
  110. }
  111. // Check for unset required fields first.
  112. if err := checkRequiredFields(pb); err != nil {
  113. return err
  114. }
  115. writer := &errWriter{writer: out}
  116. return m.marshalObject(writer, pb, "", "")
  117. }
  118. // MarshalToString converts a protocol buffer object to JSON string.
  119. func (m *Marshaler) MarshalToString(pb proto.Message) (string, error) {
  120. var buf bytes.Buffer
  121. if err := m.Marshal(&buf, pb); err != nil {
  122. return "", err
  123. }
  124. return buf.String(), nil
  125. }
  126. type int32Slice []int32
  127. var nonFinite = map[string]float64{
  128. `"NaN"`: math.NaN(),
  129. `"Infinity"`: math.Inf(1),
  130. `"-Infinity"`: math.Inf(-1),
  131. }
  132. // For sorting extensions ids to ensure stable output.
  133. func (s int32Slice) Len() int { return len(s) }
  134. func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] }
  135. func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  136. type wkt interface {
  137. XXX_WellKnownType() string
  138. }
  139. // marshalObject writes a struct to the Writer.
  140. func (m *Marshaler) marshalObject(out *errWriter, v proto.Message, indent, typeURL string) error {
  141. if jsm, ok := v.(JSONPBMarshaler); ok {
  142. b, err := jsm.MarshalJSONPB(m)
  143. if err != nil {
  144. return err
  145. }
  146. if typeURL != "" {
  147. // we are marshaling this object to an Any type
  148. var js map[string]*json.RawMessage
  149. if err = json.Unmarshal(b, &js); err != nil {
  150. return fmt.Errorf("type %T produced invalid JSON: %v", v, err)
  151. }
  152. turl, err := json.Marshal(typeURL)
  153. if err != nil {
  154. return fmt.Errorf("failed to marshal type URL %q to JSON: %v", typeURL, err)
  155. }
  156. js["@type"] = (*json.RawMessage)(&turl)
  157. if b, err = json.Marshal(js); err != nil {
  158. return err
  159. }
  160. }
  161. out.write(string(b))
  162. return out.err
  163. }
  164. s := reflect.ValueOf(v).Elem()
  165. // Handle well-known types.
  166. if wkt, ok := v.(wkt); ok {
  167. switch wkt.XXX_WellKnownType() {
  168. case "DoubleValue", "FloatValue", "Int64Value", "UInt64Value",
  169. "Int32Value", "UInt32Value", "BoolValue", "StringValue", "BytesValue":
  170. // "Wrappers use the same representation in JSON
  171. // as the wrapped primitive type, ..."
  172. sprop := proto.GetProperties(s.Type())
  173. return m.marshalValue(out, sprop.Prop[0], s.Field(0), indent)
  174. case "Any":
  175. // Any is a bit more involved.
  176. return m.marshalAny(out, v, indent)
  177. case "Duration":
  178. // "Generated output always contains 0, 3, 6, or 9 fractional digits,
  179. // depending on required precision."
  180. s, ns := s.Field(0).Int(), s.Field(1).Int()
  181. if ns <= -secondInNanos || ns >= secondInNanos {
  182. return fmt.Errorf("ns out of range (%v, %v)", -secondInNanos, secondInNanos)
  183. }
  184. if (s > 0 && ns < 0) || (s < 0 && ns > 0) {
  185. return errors.New("signs of seconds and nanos do not match")
  186. }
  187. if s < 0 {
  188. ns = -ns
  189. }
  190. x := fmt.Sprintf("%d.%09d", s, ns)
  191. x = strings.TrimSuffix(x, "000")
  192. x = strings.TrimSuffix(x, "000")
  193. x = strings.TrimSuffix(x, ".000")
  194. out.write(`"`)
  195. out.write(x)
  196. out.write(`s"`)
  197. return out.err
  198. case "Struct", "ListValue":
  199. // Let marshalValue handle the `Struct.fields` map or the `ListValue.values` slice.
  200. // TODO: pass the correct Properties if needed.
  201. return m.marshalValue(out, &proto.Properties{}, s.Field(0), indent)
  202. case "Timestamp":
  203. // "RFC 3339, where generated output will always be Z-normalized
  204. // and uses 0, 3, 6 or 9 fractional digits."
  205. s, ns := s.Field(0).Int(), s.Field(1).Int()
  206. if ns < 0 || ns >= secondInNanos {
  207. return fmt.Errorf("ns out of range [0, %v)", secondInNanos)
  208. }
  209. t := time.Unix(s, ns).UTC()
  210. // time.RFC3339Nano isn't exactly right (we need to get 3/6/9 fractional digits).
  211. x := t.Format("2006-01-02T15:04:05.000000000")
  212. x = strings.TrimSuffix(x, "000")
  213. x = strings.TrimSuffix(x, "000")
  214. x = strings.TrimSuffix(x, ".000")
  215. out.write(`"`)
  216. out.write(x)
  217. out.write(`Z"`)
  218. return out.err
  219. case "Value":
  220. // Value has a single oneof.
  221. kind := s.Field(0)
  222. if kind.IsNil() {
  223. // "absence of any variant indicates an error"
  224. return errors.New("nil Value")
  225. }
  226. // oneof -> *T -> T -> T.F
  227. x := kind.Elem().Elem().Field(0)
  228. // TODO: pass the correct Properties if needed.
  229. return m.marshalValue(out, &proto.Properties{}, x, indent)
  230. }
  231. }
  232. out.write("{")
  233. if m.Indent != "" {
  234. out.write("\n")
  235. }
  236. firstField := true
  237. if typeURL != "" {
  238. if err := m.marshalTypeURL(out, indent, typeURL); err != nil {
  239. return err
  240. }
  241. firstField = false
  242. }
  243. for i := 0; i < s.NumField(); i++ {
  244. value := s.Field(i)
  245. valueField := s.Type().Field(i)
  246. if strings.HasPrefix(valueField.Name, "XXX_") {
  247. continue
  248. }
  249. // IsNil will panic on most value kinds.
  250. switch value.Kind() {
  251. case reflect.Chan, reflect.Func, reflect.Interface:
  252. if value.IsNil() {
  253. continue
  254. }
  255. }
  256. if !m.EmitDefaults {
  257. switch value.Kind() {
  258. case reflect.Bool:
  259. if !value.Bool() {
  260. continue
  261. }
  262. case reflect.Int32, reflect.Int64:
  263. if value.Int() == 0 {
  264. continue
  265. }
  266. case reflect.Uint32, reflect.Uint64:
  267. if value.Uint() == 0 {
  268. continue
  269. }
  270. case reflect.Float32, reflect.Float64:
  271. if value.Float() == 0 {
  272. continue
  273. }
  274. case reflect.String:
  275. if value.Len() == 0 {
  276. continue
  277. }
  278. case reflect.Map, reflect.Ptr, reflect.Slice:
  279. if value.IsNil() {
  280. continue
  281. }
  282. }
  283. }
  284. // Oneof fields need special handling.
  285. if valueField.Tag.Get("protobuf_oneof") != "" {
  286. // value is an interface containing &T{real_value}.
  287. sv := value.Elem().Elem() // interface -> *T -> T
  288. value = sv.Field(0)
  289. valueField = sv.Type().Field(0)
  290. }
  291. prop := jsonProperties(valueField, m.OrigName)
  292. if !firstField {
  293. m.writeSep(out)
  294. }
  295. if err := m.marshalField(out, prop, value, indent); err != nil {
  296. return err
  297. }
  298. firstField = false
  299. }
  300. // Handle proto2 extensions.
  301. if ep, ok := v.(proto.Message); ok {
  302. extensions := proto.RegisteredExtensions(v)
  303. // Sort extensions for stable output.
  304. ids := make([]int32, 0, len(extensions))
  305. for id, desc := range extensions {
  306. if !proto.HasExtension(ep, desc) {
  307. continue
  308. }
  309. ids = append(ids, id)
  310. }
  311. sort.Sort(int32Slice(ids))
  312. for _, id := range ids {
  313. desc := extensions[id]
  314. if desc == nil {
  315. // unknown extension
  316. continue
  317. }
  318. ext, extErr := proto.GetExtension(ep, desc)
  319. if extErr != nil {
  320. return extErr
  321. }
  322. value := reflect.ValueOf(ext)
  323. var prop proto.Properties
  324. prop.Parse(desc.Tag)
  325. prop.JSONName = fmt.Sprintf("[%s]", desc.Name)
  326. if !firstField {
  327. m.writeSep(out)
  328. }
  329. if err := m.marshalField(out, &prop, value, indent); err != nil {
  330. return err
  331. }
  332. firstField = false
  333. }
  334. }
  335. if m.Indent != "" {
  336. out.write("\n")
  337. out.write(indent)
  338. }
  339. out.write("}")
  340. return out.err
  341. }
  342. func (m *Marshaler) writeSep(out *errWriter) {
  343. if m.Indent != "" {
  344. out.write(",\n")
  345. } else {
  346. out.write(",")
  347. }
  348. }
  349. func (m *Marshaler) marshalAny(out *errWriter, any proto.Message, indent string) error {
  350. // "If the Any contains a value that has a special JSON mapping,
  351. // it will be converted as follows: {"@type": xxx, "value": yyy}.
  352. // Otherwise, the value will be converted into a JSON object,
  353. // and the "@type" field will be inserted to indicate the actual data type."
  354. v := reflect.ValueOf(any).Elem()
  355. turl := v.Field(0).String()
  356. val := v.Field(1).Bytes()
  357. var msg proto.Message
  358. var err error
  359. if m.AnyResolver != nil {
  360. msg, err = m.AnyResolver.Resolve(turl)
  361. } else {
  362. msg, err = defaultResolveAny(turl)
  363. }
  364. if err != nil {
  365. return err
  366. }
  367. if err := proto.Unmarshal(val, msg); err != nil {
  368. return err
  369. }
  370. if _, ok := msg.(wkt); ok {
  371. out.write("{")
  372. if m.Indent != "" {
  373. out.write("\n")
  374. }
  375. if err := m.marshalTypeURL(out, indent, turl); err != nil {
  376. return err
  377. }
  378. m.writeSep(out)
  379. if m.Indent != "" {
  380. out.write(indent)
  381. out.write(m.Indent)
  382. out.write(`"value": `)
  383. } else {
  384. out.write(`"value":`)
  385. }
  386. if err := m.marshalObject(out, msg, indent+m.Indent, ""); err != nil {
  387. return err
  388. }
  389. if m.Indent != "" {
  390. out.write("\n")
  391. out.write(indent)
  392. }
  393. out.write("}")
  394. return out.err
  395. }
  396. return m.marshalObject(out, msg, indent, turl)
  397. }
  398. func (m *Marshaler) marshalTypeURL(out *errWriter, indent, typeURL string) error {
  399. if m.Indent != "" {
  400. out.write(indent)
  401. out.write(m.Indent)
  402. }
  403. out.write(`"@type":`)
  404. if m.Indent != "" {
  405. out.write(" ")
  406. }
  407. b, err := json.Marshal(typeURL)
  408. if err != nil {
  409. return err
  410. }
  411. out.write(string(b))
  412. return out.err
  413. }
  414. // marshalField writes field description and value to the Writer.
  415. func (m *Marshaler) marshalField(out *errWriter, prop *proto.Properties, v reflect.Value, indent string) error {
  416. if m.Indent != "" {
  417. out.write(indent)
  418. out.write(m.Indent)
  419. }
  420. out.write(`"`)
  421. out.write(prop.JSONName)
  422. out.write(`":`)
  423. if m.Indent != "" {
  424. out.write(" ")
  425. }
  426. if err := m.marshalValue(out, prop, v, indent); err != nil {
  427. return err
  428. }
  429. return nil
  430. }
  431. // marshalValue writes the value to the Writer.
  432. func (m *Marshaler) marshalValue(out *errWriter, prop *proto.Properties, v reflect.Value, indent string) error {
  433. var err error
  434. v = reflect.Indirect(v)
  435. // Handle nil pointer
  436. if v.Kind() == reflect.Invalid {
  437. out.write("null")
  438. return out.err
  439. }
  440. // Handle repeated elements.
  441. if v.Kind() == reflect.Slice && v.Type().Elem().Kind() != reflect.Uint8 {
  442. out.write("[")
  443. comma := ""
  444. for i := 0; i < v.Len(); i++ {
  445. sliceVal := v.Index(i)
  446. out.write(comma)
  447. if m.Indent != "" {
  448. out.write("\n")
  449. out.write(indent)
  450. out.write(m.Indent)
  451. out.write(m.Indent)
  452. }
  453. if err := m.marshalValue(out, prop, sliceVal, indent+m.Indent); err != nil {
  454. return err
  455. }
  456. comma = ","
  457. }
  458. if m.Indent != "" {
  459. out.write("\n")
  460. out.write(indent)
  461. out.write(m.Indent)
  462. }
  463. out.write("]")
  464. return out.err
  465. }
  466. // Handle well-known types.
  467. // Most are handled up in marshalObject (because 99% are messages).
  468. if wkt, ok := v.Interface().(wkt); ok {
  469. switch wkt.XXX_WellKnownType() {
  470. case "NullValue":
  471. out.write("null")
  472. return out.err
  473. }
  474. }
  475. // Handle enumerations.
  476. if !m.EnumsAsInts && prop.Enum != "" {
  477. // Unknown enum values will are stringified by the proto library as their
  478. // value. Such values should _not_ be quoted or they will be interpreted
  479. // as an enum string instead of their value.
  480. enumStr := v.Interface().(fmt.Stringer).String()
  481. var valStr string
  482. if v.Kind() == reflect.Ptr {
  483. valStr = strconv.Itoa(int(v.Elem().Int()))
  484. } else {
  485. valStr = strconv.Itoa(int(v.Int()))
  486. }
  487. isKnownEnum := enumStr != valStr
  488. if isKnownEnum {
  489. out.write(`"`)
  490. }
  491. out.write(enumStr)
  492. if isKnownEnum {
  493. out.write(`"`)
  494. }
  495. return out.err
  496. }
  497. // Handle nested messages.
  498. if v.Kind() == reflect.Struct {
  499. return m.marshalObject(out, v.Addr().Interface().(proto.Message), indent+m.Indent, "")
  500. }
  501. // Handle maps.
  502. // Since Go randomizes map iteration, we sort keys for stable output.
  503. if v.Kind() == reflect.Map {
  504. out.write(`{`)
  505. keys := v.MapKeys()
  506. sort.Sort(mapKeys(keys))
  507. for i, k := range keys {
  508. if i > 0 {
  509. out.write(`,`)
  510. }
  511. if m.Indent != "" {
  512. out.write("\n")
  513. out.write(indent)
  514. out.write(m.Indent)
  515. out.write(m.Indent)
  516. }
  517. // TODO handle map key prop properly
  518. b, err := json.Marshal(k.Interface())
  519. if err != nil {
  520. return err
  521. }
  522. s := string(b)
  523. // If the JSON is not a string value, encode it again to make it one.
  524. if !strings.HasPrefix(s, `"`) {
  525. b, err := json.Marshal(s)
  526. if err != nil {
  527. return err
  528. }
  529. s = string(b)
  530. }
  531. out.write(s)
  532. out.write(`:`)
  533. if m.Indent != "" {
  534. out.write(` `)
  535. }
  536. vprop := prop
  537. if prop != nil && prop.MapValProp != nil {
  538. vprop = prop.MapValProp
  539. }
  540. if err := m.marshalValue(out, vprop, v.MapIndex(k), indent+m.Indent); err != nil {
  541. return err
  542. }
  543. }
  544. if m.Indent != "" {
  545. out.write("\n")
  546. out.write(indent)
  547. out.write(m.Indent)
  548. }
  549. out.write(`}`)
  550. return out.err
  551. }
  552. // Handle non-finite floats, e.g. NaN, Infinity and -Infinity.
  553. if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 {
  554. f := v.Float()
  555. var sval string
  556. switch {
  557. case math.IsInf(f, 1):
  558. sval = `"Infinity"`
  559. case math.IsInf(f, -1):
  560. sval = `"-Infinity"`
  561. case math.IsNaN(f):
  562. sval = `"NaN"`
  563. }
  564. if sval != "" {
  565. out.write(sval)
  566. return out.err
  567. }
  568. }
  569. // Default handling defers to the encoding/json library.
  570. b, err := json.Marshal(v.Interface())
  571. if err != nil {
  572. return err
  573. }
  574. needToQuote := string(b[0]) != `"` && (v.Kind() == reflect.Int64 || v.Kind() == reflect.Uint64)
  575. if needToQuote {
  576. out.write(`"`)
  577. }
  578. out.write(string(b))
  579. if needToQuote {
  580. out.write(`"`)
  581. }
  582. return out.err
  583. }
  584. // Unmarshaler is a configurable object for converting from a JSON
  585. // representation to a protocol buffer object.
  586. type Unmarshaler struct {
  587. // Whether to allow messages to contain unknown fields, as opposed to
  588. // failing to unmarshal.
  589. AllowUnknownFields bool
  590. // A custom URL resolver to use when unmarshaling Any messages from JSON.
  591. // If unset, the default resolution strategy is to extract the
  592. // fully-qualified type name from the type URL and pass that to
  593. // proto.MessageType(string).
  594. AnyResolver AnyResolver
  595. }
  596. // UnmarshalNext unmarshals the next protocol buffer from a JSON object stream.
  597. // This function is lenient and will decode any options permutations of the
  598. // related Marshaler.
  599. func (u *Unmarshaler) UnmarshalNext(dec *json.Decoder, pb proto.Message) error {
  600. inputValue := json.RawMessage{}
  601. if err := dec.Decode(&inputValue); err != nil {
  602. return err
  603. }
  604. if err := u.unmarshalValue(reflect.ValueOf(pb).Elem(), inputValue, nil); err != nil {
  605. return err
  606. }
  607. return checkRequiredFields(pb)
  608. }
  609. // Unmarshal unmarshals a JSON object stream into a protocol
  610. // buffer. This function is lenient and will decode any options
  611. // permutations of the related Marshaler.
  612. func (u *Unmarshaler) Unmarshal(r io.Reader, pb proto.Message) error {
  613. dec := json.NewDecoder(r)
  614. return u.UnmarshalNext(dec, pb)
  615. }
  616. // UnmarshalNext unmarshals the next protocol buffer from a JSON object stream.
  617. // This function is lenient and will decode any options permutations of the
  618. // related Marshaler.
  619. func UnmarshalNext(dec *json.Decoder, pb proto.Message) error {
  620. return new(Unmarshaler).UnmarshalNext(dec, pb)
  621. }
  622. // Unmarshal unmarshals a JSON object stream into a protocol
  623. // buffer. This function is lenient and will decode any options
  624. // permutations of the related Marshaler.
  625. func Unmarshal(r io.Reader, pb proto.Message) error {
  626. return new(Unmarshaler).Unmarshal(r, pb)
  627. }
  628. // UnmarshalString will populate the fields of a protocol buffer based
  629. // on a JSON string. This function is lenient and will decode any options
  630. // permutations of the related Marshaler.
  631. func UnmarshalString(str string, pb proto.Message) error {
  632. return new(Unmarshaler).Unmarshal(strings.NewReader(str), pb)
  633. }
  634. // unmarshalValue converts/copies a value into the target.
  635. // prop may be nil.
  636. func (u *Unmarshaler) unmarshalValue(target reflect.Value, inputValue json.RawMessage, prop *proto.Properties) error {
  637. targetType := target.Type()
  638. // Allocate memory for pointer fields.
  639. if targetType.Kind() == reflect.Ptr {
  640. // If input value is "null" and target is a pointer type, then the field should be treated as not set
  641. // UNLESS the target is structpb.Value, in which case it should be set to structpb.NullValue.
  642. _, isJSONPBUnmarshaler := target.Interface().(JSONPBUnmarshaler)
  643. if string(inputValue) == "null" && targetType != reflect.TypeOf(&stpb.Value{}) && !isJSONPBUnmarshaler {
  644. return nil
  645. }
  646. target.Set(reflect.New(targetType.Elem()))
  647. return u.unmarshalValue(target.Elem(), inputValue, prop)
  648. }
  649. if jsu, ok := target.Addr().Interface().(JSONPBUnmarshaler); ok {
  650. return jsu.UnmarshalJSONPB(u, []byte(inputValue))
  651. }
  652. // Handle well-known types that are not pointers.
  653. if w, ok := target.Addr().Interface().(wkt); ok {
  654. switch w.XXX_WellKnownType() {
  655. case "DoubleValue", "FloatValue", "Int64Value", "UInt64Value",
  656. "Int32Value", "UInt32Value", "BoolValue", "StringValue", "BytesValue":
  657. return u.unmarshalValue(target.Field(0), inputValue, prop)
  658. case "Any":
  659. // Use json.RawMessage pointer type instead of value to support pre-1.8 version.
  660. // 1.8 changed RawMessage.MarshalJSON from pointer type to value type, see
  661. // https://github.com/golang/go/issues/14493
  662. var jsonFields map[string]*json.RawMessage
  663. if err := json.Unmarshal(inputValue, &jsonFields); err != nil {
  664. return err
  665. }
  666. val, ok := jsonFields["@type"]
  667. if !ok || val == nil {
  668. return errors.New("Any JSON doesn't have '@type'")
  669. }
  670. var turl string
  671. if err := json.Unmarshal([]byte(*val), &turl); err != nil {
  672. return fmt.Errorf("can't unmarshal Any's '@type': %q", *val)
  673. }
  674. target.Field(0).SetString(turl)
  675. var m proto.Message
  676. var err error
  677. if u.AnyResolver != nil {
  678. m, err = u.AnyResolver.Resolve(turl)
  679. } else {
  680. m, err = defaultResolveAny(turl)
  681. }
  682. if err != nil {
  683. return err
  684. }
  685. if _, ok := m.(wkt); ok {
  686. val, ok := jsonFields["value"]
  687. if !ok {
  688. return errors.New("Any JSON doesn't have 'value'")
  689. }
  690. if err := u.unmarshalValue(reflect.ValueOf(m).Elem(), *val, nil); err != nil {
  691. return fmt.Errorf("can't unmarshal Any nested proto %T: %v", m, err)
  692. }
  693. } else {
  694. delete(jsonFields, "@type")
  695. nestedProto, err := json.Marshal(jsonFields)
  696. if err != nil {
  697. return fmt.Errorf("can't generate JSON for Any's nested proto to be unmarshaled: %v", err)
  698. }
  699. if err = u.unmarshalValue(reflect.ValueOf(m).Elem(), nestedProto, nil); err != nil {
  700. return fmt.Errorf("can't unmarshal Any nested proto %T: %v", m, err)
  701. }
  702. }
  703. b, err := proto.Marshal(m)
  704. if err != nil {
  705. return fmt.Errorf("can't marshal proto %T into Any.Value: %v", m, err)
  706. }
  707. target.Field(1).SetBytes(b)
  708. return nil
  709. case "Duration":
  710. unq, err := unquote(string(inputValue))
  711. if err != nil {
  712. return err
  713. }
  714. d, err := time.ParseDuration(unq)
  715. if err != nil {
  716. return fmt.Errorf("bad Duration: %v", err)
  717. }
  718. ns := d.Nanoseconds()
  719. s := ns / 1e9
  720. ns %= 1e9
  721. target.Field(0).SetInt(s)
  722. target.Field(1).SetInt(ns)
  723. return nil
  724. case "Timestamp":
  725. unq, err := unquote(string(inputValue))
  726. if err != nil {
  727. return err
  728. }
  729. t, err := time.Parse(time.RFC3339Nano, unq)
  730. if err != nil {
  731. return fmt.Errorf("bad Timestamp: %v", err)
  732. }
  733. target.Field(0).SetInt(t.Unix())
  734. target.Field(1).SetInt(int64(t.Nanosecond()))
  735. return nil
  736. case "Struct":
  737. var m map[string]json.RawMessage
  738. if err := json.Unmarshal(inputValue, &m); err != nil {
  739. return fmt.Errorf("bad StructValue: %v", err)
  740. }
  741. target.Field(0).Set(reflect.ValueOf(map[string]*stpb.Value{}))
  742. for k, jv := range m {
  743. pv := &stpb.Value{}
  744. if err := u.unmarshalValue(reflect.ValueOf(pv).Elem(), jv, prop); err != nil {
  745. return fmt.Errorf("bad value in StructValue for key %q: %v", k, err)
  746. }
  747. target.Field(0).SetMapIndex(reflect.ValueOf(k), reflect.ValueOf(pv))
  748. }
  749. return nil
  750. case "ListValue":
  751. var s []json.RawMessage
  752. if err := json.Unmarshal(inputValue, &s); err != nil {
  753. return fmt.Errorf("bad ListValue: %v", err)
  754. }
  755. target.Field(0).Set(reflect.ValueOf(make([]*stpb.Value, len(s))))
  756. for i, sv := range s {
  757. if err := u.unmarshalValue(target.Field(0).Index(i), sv, prop); err != nil {
  758. return err
  759. }
  760. }
  761. return nil
  762. case "Value":
  763. ivStr := string(inputValue)
  764. if ivStr == "null" {
  765. target.Field(0).Set(reflect.ValueOf(&stpb.Value_NullValue{}))
  766. } else if v, err := strconv.ParseFloat(ivStr, 0); err == nil {
  767. target.Field(0).Set(reflect.ValueOf(&stpb.Value_NumberValue{v}))
  768. } else if v, err := unquote(ivStr); err == nil {
  769. target.Field(0).Set(reflect.ValueOf(&stpb.Value_StringValue{v}))
  770. } else if v, err := strconv.ParseBool(ivStr); err == nil {
  771. target.Field(0).Set(reflect.ValueOf(&stpb.Value_BoolValue{v}))
  772. } else if err := json.Unmarshal(inputValue, &[]json.RawMessage{}); err == nil {
  773. lv := &stpb.ListValue{}
  774. target.Field(0).Set(reflect.ValueOf(&stpb.Value_ListValue{lv}))
  775. return u.unmarshalValue(reflect.ValueOf(lv).Elem(), inputValue, prop)
  776. } else if err := json.Unmarshal(inputValue, &map[string]json.RawMessage{}); err == nil {
  777. sv := &stpb.Struct{}
  778. target.Field(0).Set(reflect.ValueOf(&stpb.Value_StructValue{sv}))
  779. return u.unmarshalValue(reflect.ValueOf(sv).Elem(), inputValue, prop)
  780. } else {
  781. return fmt.Errorf("unrecognized type for Value %q", ivStr)
  782. }
  783. return nil
  784. }
  785. }
  786. // Handle enums, which have an underlying type of int32,
  787. // and may appear as strings.
  788. // The case of an enum appearing as a number is handled
  789. // at the bottom of this function.
  790. if inputValue[0] == '"' && prop != nil && prop.Enum != "" {
  791. vmap := proto.EnumValueMap(prop.Enum)
  792. // Don't need to do unquoting; valid enum names
  793. // are from a limited character set.
  794. s := inputValue[1 : len(inputValue)-1]
  795. n, ok := vmap[string(s)]
  796. if !ok {
  797. return fmt.Errorf("unknown value %q for enum %s", s, prop.Enum)
  798. }
  799. if target.Kind() == reflect.Ptr { // proto2
  800. target.Set(reflect.New(targetType.Elem()))
  801. target = target.Elem()
  802. }
  803. if targetType.Kind() != reflect.Int32 {
  804. return fmt.Errorf("invalid target %q for enum %s", targetType.Kind(), prop.Enum)
  805. }
  806. target.SetInt(int64(n))
  807. return nil
  808. }
  809. // Handle nested messages.
  810. if targetType.Kind() == reflect.Struct {
  811. var jsonFields map[string]json.RawMessage
  812. if err := json.Unmarshal(inputValue, &jsonFields); err != nil {
  813. return err
  814. }
  815. consumeField := func(prop *proto.Properties) (json.RawMessage, bool) {
  816. // Be liberal in what names we accept; both orig_name and camelName are okay.
  817. fieldNames := acceptedJSONFieldNames(prop)
  818. vOrig, okOrig := jsonFields[fieldNames.orig]
  819. vCamel, okCamel := jsonFields[fieldNames.camel]
  820. if !okOrig && !okCamel {
  821. return nil, false
  822. }
  823. // If, for some reason, both are present in the data, favour the camelName.
  824. var raw json.RawMessage
  825. if okOrig {
  826. raw = vOrig
  827. delete(jsonFields, fieldNames.orig)
  828. }
  829. if okCamel {
  830. raw = vCamel
  831. delete(jsonFields, fieldNames.camel)
  832. }
  833. return raw, true
  834. }
  835. sprops := proto.GetProperties(targetType)
  836. for i := 0; i < target.NumField(); i++ {
  837. ft := target.Type().Field(i)
  838. if strings.HasPrefix(ft.Name, "XXX_") {
  839. continue
  840. }
  841. valueForField, ok := consumeField(sprops.Prop[i])
  842. if !ok {
  843. continue
  844. }
  845. if err := u.unmarshalValue(target.Field(i), valueForField, sprops.Prop[i]); err != nil {
  846. return err
  847. }
  848. }
  849. // Check for any oneof fields.
  850. if len(jsonFields) > 0 {
  851. for _, oop := range sprops.OneofTypes {
  852. raw, ok := consumeField(oop.Prop)
  853. if !ok {
  854. continue
  855. }
  856. nv := reflect.New(oop.Type.Elem())
  857. target.Field(oop.Field).Set(nv)
  858. if err := u.unmarshalValue(nv.Elem().Field(0), raw, oop.Prop); err != nil {
  859. return err
  860. }
  861. }
  862. }
  863. // Handle proto2 extensions.
  864. if len(jsonFields) > 0 {
  865. if ep, ok := target.Addr().Interface().(proto.Message); ok {
  866. for _, ext := range proto.RegisteredExtensions(ep) {
  867. name := fmt.Sprintf("[%s]", ext.Name)
  868. raw, ok := jsonFields[name]
  869. if !ok {
  870. continue
  871. }
  872. delete(jsonFields, name)
  873. nv := reflect.New(reflect.TypeOf(ext.ExtensionType).Elem())
  874. if err := u.unmarshalValue(nv.Elem(), raw, nil); err != nil {
  875. return err
  876. }
  877. if err := proto.SetExtension(ep, ext, nv.Interface()); err != nil {
  878. return err
  879. }
  880. }
  881. }
  882. }
  883. if !u.AllowUnknownFields && len(jsonFields) > 0 {
  884. // Pick any field to be the scapegoat.
  885. var f string
  886. for fname := range jsonFields {
  887. f = fname
  888. break
  889. }
  890. return fmt.Errorf("unknown field %q in %v", f, targetType)
  891. }
  892. return nil
  893. }
  894. // Handle arrays (which aren't encoded bytes)
  895. if targetType.Kind() == reflect.Slice && targetType.Elem().Kind() != reflect.Uint8 {
  896. var slc []json.RawMessage
  897. if err := json.Unmarshal(inputValue, &slc); err != nil {
  898. return err
  899. }
  900. if slc != nil {
  901. l := len(slc)
  902. target.Set(reflect.MakeSlice(targetType, l, l))
  903. for i := 0; i < l; i++ {
  904. if err := u.unmarshalValue(target.Index(i), slc[i], prop); err != nil {
  905. return err
  906. }
  907. }
  908. }
  909. return nil
  910. }
  911. // Handle maps (whose keys are always strings)
  912. if targetType.Kind() == reflect.Map {
  913. var mp map[string]json.RawMessage
  914. if err := json.Unmarshal(inputValue, &mp); err != nil {
  915. return err
  916. }
  917. if mp != nil {
  918. target.Set(reflect.MakeMap(targetType))
  919. for ks, raw := range mp {
  920. // Unmarshal map key. The core json library already decoded the key into a
  921. // string, so we handle that specially. Other types were quoted post-serialization.
  922. var k reflect.Value
  923. if targetType.Key().Kind() == reflect.String {
  924. k = reflect.ValueOf(ks)
  925. } else {
  926. k = reflect.New(targetType.Key()).Elem()
  927. var kprop *proto.Properties
  928. if prop != nil && prop.MapKeyProp != nil {
  929. kprop = prop.MapKeyProp
  930. }
  931. if err := u.unmarshalValue(k, json.RawMessage(ks), kprop); err != nil {
  932. return err
  933. }
  934. }
  935. // Unmarshal map value.
  936. v := reflect.New(targetType.Elem()).Elem()
  937. var vprop *proto.Properties
  938. if prop != nil && prop.MapValProp != nil {
  939. vprop = prop.MapValProp
  940. }
  941. if err := u.unmarshalValue(v, raw, vprop); err != nil {
  942. return err
  943. }
  944. target.SetMapIndex(k, v)
  945. }
  946. }
  947. return nil
  948. }
  949. // Non-finite numbers can be encoded as strings.
  950. isFloat := targetType.Kind() == reflect.Float32 || targetType.Kind() == reflect.Float64
  951. if isFloat {
  952. if num, ok := nonFinite[string(inputValue)]; ok {
  953. target.SetFloat(num)
  954. return nil
  955. }
  956. }
  957. // integers & floats can be encoded as strings. In this case we drop
  958. // the quotes and proceed as normal.
  959. isNum := targetType.Kind() == reflect.Int64 || targetType.Kind() == reflect.Uint64 ||
  960. targetType.Kind() == reflect.Int32 || targetType.Kind() == reflect.Uint32 ||
  961. targetType.Kind() == reflect.Float32 || targetType.Kind() == reflect.Float64
  962. if isNum && strings.HasPrefix(string(inputValue), `"`) {
  963. inputValue = inputValue[1 : len(inputValue)-1]
  964. }
  965. // Use the encoding/json for parsing other value types.
  966. return json.Unmarshal(inputValue, target.Addr().Interface())
  967. }
  968. func unquote(s string) (string, error) {
  969. var ret string
  970. err := json.Unmarshal([]byte(s), &ret)
  971. return ret, err
  972. }
  973. // jsonProperties returns parsed proto.Properties for the field and corrects JSONName attribute.
  974. func jsonProperties(f reflect.StructField, origName bool) *proto.Properties {
  975. var prop proto.Properties
  976. prop.Init(f.Type, f.Name, f.Tag.Get("protobuf"), &f)
  977. if origName || prop.JSONName == "" {
  978. prop.JSONName = prop.OrigName
  979. }
  980. return &prop
  981. }
  982. type fieldNames struct {
  983. orig, camel string
  984. }
  985. func acceptedJSONFieldNames(prop *proto.Properties) fieldNames {
  986. opts := fieldNames{orig: prop.OrigName, camel: prop.OrigName}
  987. if prop.JSONName != "" {
  988. opts.camel = prop.JSONName
  989. }
  990. return opts
  991. }
  992. // Writer wrapper inspired by https://blog.golang.org/errors-are-values
  993. type errWriter struct {
  994. writer io.Writer
  995. err error
  996. }
  997. func (w *errWriter) write(str string) {
  998. if w.err != nil {
  999. return
  1000. }
  1001. _, w.err = w.writer.Write([]byte(str))
  1002. }
  1003. // Map fields may have key types of non-float scalars, strings and enums.
  1004. // The easiest way to sort them in some deterministic order is to use fmt.
  1005. // If this turns out to be inefficient we can always consider other options,
  1006. // such as doing a Schwartzian transform.
  1007. //
  1008. // Numeric keys are sorted in numeric order per
  1009. // https://developers.google.com/protocol-buffers/docs/proto#maps.
  1010. type mapKeys []reflect.Value
  1011. func (s mapKeys) Len() int { return len(s) }
  1012. func (s mapKeys) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  1013. func (s mapKeys) Less(i, j int) bool {
  1014. if k := s[i].Kind(); k == s[j].Kind() {
  1015. switch k {
  1016. case reflect.Int32, reflect.Int64:
  1017. return s[i].Int() < s[j].Int()
  1018. case reflect.Uint32, reflect.Uint64:
  1019. return s[i].Uint() < s[j].Uint()
  1020. }
  1021. }
  1022. return fmt.Sprint(s[i].Interface()) < fmt.Sprint(s[j].Interface())
  1023. }
  1024. // checkRequiredFields returns an error if any required field in the given proto message is not set.
  1025. // This function is used by both Marshal and Unmarshal. While required fields only exist in a
  1026. // proto2 message, a proto3 message can contain proto2 message(s).
  1027. func checkRequiredFields(pb proto.Message) error {
  1028. // Most well-known type messages do not contain required fields. The "Any" type may contain
  1029. // a message that has required fields.
  1030. //
  1031. // When an Any message is being marshaled, the code will invoked proto.Unmarshal on Any.Value
  1032. // field in order to transform that into JSON, and that should have returned an error if a
  1033. // required field is not set in the embedded message.
  1034. //
  1035. // When an Any message is being unmarshaled, the code will have invoked proto.Marshal on the
  1036. // embedded message to store the serialized message in Any.Value field, and that should have
  1037. // returned an error if a required field is not set.
  1038. if _, ok := pb.(wkt); ok {
  1039. return nil
  1040. }
  1041. v := reflect.ValueOf(pb)
  1042. // Skip message if it is not a struct pointer.
  1043. if v.Kind() != reflect.Ptr {
  1044. return nil
  1045. }
  1046. v = v.Elem()
  1047. if v.Kind() != reflect.Struct {
  1048. return nil
  1049. }
  1050. for i := 0; i < v.NumField(); i++ {
  1051. field := v.Field(i)
  1052. sfield := v.Type().Field(i)
  1053. if sfield.PkgPath != "" {
  1054. // blank PkgPath means the field is exported; skip if not exported
  1055. continue
  1056. }
  1057. if strings.HasPrefix(sfield.Name, "XXX_") {
  1058. continue
  1059. }
  1060. // Oneof field is an interface implemented by wrapper structs containing the actual oneof
  1061. // field, i.e. an interface containing &T{real_value}.
  1062. if sfield.Tag.Get("protobuf_oneof") != "" {
  1063. if field.Kind() != reflect.Interface {
  1064. continue
  1065. }
  1066. v := field.Elem()
  1067. if v.Kind() != reflect.Ptr || v.IsNil() {
  1068. continue
  1069. }
  1070. v = v.Elem()
  1071. if v.Kind() != reflect.Struct || v.NumField() < 1 {
  1072. continue
  1073. }
  1074. field = v.Field(0)
  1075. sfield = v.Type().Field(0)
  1076. }
  1077. protoTag := sfield.Tag.Get("protobuf")
  1078. if protoTag == "" {
  1079. continue
  1080. }
  1081. var prop proto.Properties
  1082. prop.Init(sfield.Type, sfield.Name, protoTag, &sfield)
  1083. switch field.Kind() {
  1084. case reflect.Map:
  1085. if field.IsNil() {
  1086. continue
  1087. }
  1088. // Check each map value.
  1089. keys := field.MapKeys()
  1090. for _, k := range keys {
  1091. v := field.MapIndex(k)
  1092. if err := checkRequiredFieldsInValue(v); err != nil {
  1093. return err
  1094. }
  1095. }
  1096. case reflect.Slice:
  1097. // Handle non-repeated type, e.g. bytes.
  1098. if !prop.Repeated {
  1099. if prop.Required && field.IsNil() {
  1100. return fmt.Errorf("required field %q is not set", prop.Name)
  1101. }
  1102. continue
  1103. }
  1104. // Handle repeated type.
  1105. if field.IsNil() {
  1106. continue
  1107. }
  1108. // Check each slice item.
  1109. for i := 0; i < field.Len(); i++ {
  1110. v := field.Index(i)
  1111. if err := checkRequiredFieldsInValue(v); err != nil {
  1112. return err
  1113. }
  1114. }
  1115. case reflect.Ptr:
  1116. if field.IsNil() {
  1117. if prop.Required {
  1118. return fmt.Errorf("required field %q is not set", prop.Name)
  1119. }
  1120. continue
  1121. }
  1122. if err := checkRequiredFieldsInValue(field); err != nil {
  1123. return err
  1124. }
  1125. }
  1126. }
  1127. // Handle proto2 extensions.
  1128. for _, ext := range proto.RegisteredExtensions(pb) {
  1129. if !proto.HasExtension(pb, ext) {
  1130. continue
  1131. }
  1132. ep, err := proto.GetExtension(pb, ext)
  1133. if err != nil {
  1134. return err
  1135. }
  1136. err = checkRequiredFieldsInValue(reflect.ValueOf(ep))
  1137. if err != nil {
  1138. return err
  1139. }
  1140. }
  1141. return nil
  1142. }
  1143. func checkRequiredFieldsInValue(v reflect.Value) error {
  1144. if pm, ok := v.Interface().(proto.Message); ok {
  1145. return checkRequiredFields(pm)
  1146. }
  1147. return nil
  1148. }