text.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  1. // Go support for Protocol Buffers - Google's data interchange format
  2. //
  3. // Copyright 2010 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. package proto
  32. // Functions for writing the text protocol buffer format.
  33. import (
  34. "bufio"
  35. "bytes"
  36. "encoding"
  37. "errors"
  38. "fmt"
  39. "io"
  40. "log"
  41. "math"
  42. "reflect"
  43. "sort"
  44. "strings"
  45. )
  46. var (
  47. newline = []byte("\n")
  48. spaces = []byte(" ")
  49. endBraceNewline = []byte("}\n")
  50. backslashN = []byte{'\\', 'n'}
  51. backslashR = []byte{'\\', 'r'}
  52. backslashT = []byte{'\\', 't'}
  53. backslashDQ = []byte{'\\', '"'}
  54. backslashBS = []byte{'\\', '\\'}
  55. posInf = []byte("inf")
  56. negInf = []byte("-inf")
  57. nan = []byte("nan")
  58. )
  59. type writer interface {
  60. io.Writer
  61. WriteByte(byte) error
  62. }
  63. // textWriter is an io.Writer that tracks its indentation level.
  64. type textWriter struct {
  65. ind int
  66. complete bool // if the current position is a complete line
  67. compact bool // whether to write out as a one-liner
  68. w writer
  69. }
  70. func (w *textWriter) WriteString(s string) (n int, err error) {
  71. if !strings.Contains(s, "\n") {
  72. if !w.compact && w.complete {
  73. w.writeIndent()
  74. }
  75. w.complete = false
  76. return io.WriteString(w.w, s)
  77. }
  78. // WriteString is typically called without newlines, so this
  79. // codepath and its copy are rare. We copy to avoid
  80. // duplicating all of Write's logic here.
  81. return w.Write([]byte(s))
  82. }
  83. func (w *textWriter) Write(p []byte) (n int, err error) {
  84. newlines := bytes.Count(p, newline)
  85. if newlines == 0 {
  86. if !w.compact && w.complete {
  87. w.writeIndent()
  88. }
  89. n, err = w.w.Write(p)
  90. w.complete = false
  91. return n, err
  92. }
  93. frags := bytes.SplitN(p, newline, newlines+1)
  94. if w.compact {
  95. for i, frag := range frags {
  96. if i > 0 {
  97. if err := w.w.WriteByte(' '); err != nil {
  98. return n, err
  99. }
  100. n++
  101. }
  102. nn, err := w.w.Write(frag)
  103. n += nn
  104. if err != nil {
  105. return n, err
  106. }
  107. }
  108. return n, nil
  109. }
  110. for i, frag := range frags {
  111. if w.complete {
  112. w.writeIndent()
  113. }
  114. nn, err := w.w.Write(frag)
  115. n += nn
  116. if err != nil {
  117. return n, err
  118. }
  119. if i+1 < len(frags) {
  120. if err := w.w.WriteByte('\n'); err != nil {
  121. return n, err
  122. }
  123. n++
  124. }
  125. }
  126. w.complete = len(frags[len(frags)-1]) == 0
  127. return n, nil
  128. }
  129. func (w *textWriter) WriteByte(c byte) error {
  130. if w.compact && c == '\n' {
  131. c = ' '
  132. }
  133. if !w.compact && w.complete {
  134. w.writeIndent()
  135. }
  136. err := w.w.WriteByte(c)
  137. w.complete = c == '\n'
  138. return err
  139. }
  140. func (w *textWriter) indent() { w.ind++ }
  141. func (w *textWriter) unindent() {
  142. if w.ind == 0 {
  143. log.Print("proto: textWriter unindented too far")
  144. return
  145. }
  146. w.ind--
  147. }
  148. func writeName(w *textWriter, props *Properties) error {
  149. if _, err := w.WriteString(props.OrigName); err != nil {
  150. return err
  151. }
  152. if props.Wire != "group" {
  153. return w.WriteByte(':')
  154. }
  155. return nil
  156. }
  157. func requiresQuotes(u string) bool {
  158. // When type URL contains any characters except [0-9A-Za-z./\-]*, it must be quoted.
  159. for _, ch := range u {
  160. switch {
  161. case ch == '.' || ch == '/' || ch == '_':
  162. continue
  163. case '0' <= ch && ch <= '9':
  164. continue
  165. case 'A' <= ch && ch <= 'Z':
  166. continue
  167. case 'a' <= ch && ch <= 'z':
  168. continue
  169. default:
  170. return true
  171. }
  172. }
  173. return false
  174. }
  175. // isAny reports whether sv is a google.protobuf.Any message
  176. func isAny(sv reflect.Value) bool {
  177. type wkt interface {
  178. XXX_WellKnownType() string
  179. }
  180. t, ok := sv.Addr().Interface().(wkt)
  181. return ok && t.XXX_WellKnownType() == "Any"
  182. }
  183. // writeProto3Any writes an expanded google.protobuf.Any message.
  184. //
  185. // It returns (false, nil) if sv value can't be unmarshaled (e.g. because
  186. // required messages are not linked in).
  187. //
  188. // It returns (true, error) when sv was written in expanded format or an error
  189. // was encountered.
  190. func (tm *TextMarshaler) writeProto3Any(w *textWriter, sv reflect.Value) (bool, error) {
  191. turl := sv.FieldByName("TypeUrl")
  192. val := sv.FieldByName("Value")
  193. if !turl.IsValid() || !val.IsValid() {
  194. return true, errors.New("proto: invalid google.protobuf.Any message")
  195. }
  196. b, ok := val.Interface().([]byte)
  197. if !ok {
  198. return true, errors.New("proto: invalid google.protobuf.Any message")
  199. }
  200. parts := strings.Split(turl.String(), "/")
  201. mt := MessageType(parts[len(parts)-1])
  202. if mt == nil {
  203. return false, nil
  204. }
  205. m := reflect.New(mt.Elem())
  206. if err := Unmarshal(b, m.Interface().(Message)); err != nil {
  207. return false, nil
  208. }
  209. w.Write([]byte("["))
  210. u := turl.String()
  211. if requiresQuotes(u) {
  212. writeString(w, u)
  213. } else {
  214. w.Write([]byte(u))
  215. }
  216. if w.compact {
  217. w.Write([]byte("]:<"))
  218. } else {
  219. w.Write([]byte("]: <\n"))
  220. w.ind++
  221. }
  222. if err := tm.writeStruct(w, m.Elem()); err != nil {
  223. return true, err
  224. }
  225. if w.compact {
  226. w.Write([]byte("> "))
  227. } else {
  228. w.ind--
  229. w.Write([]byte(">\n"))
  230. }
  231. return true, nil
  232. }
  233. func (tm *TextMarshaler) writeStruct(w *textWriter, sv reflect.Value) error {
  234. if tm.ExpandAny && isAny(sv) {
  235. if canExpand, err := tm.writeProto3Any(w, sv); canExpand {
  236. return err
  237. }
  238. }
  239. st := sv.Type()
  240. sprops := GetProperties(st)
  241. for i := 0; i < sv.NumField(); i++ {
  242. fv := sv.Field(i)
  243. props := sprops.Prop[i]
  244. name := st.Field(i).Name
  245. if name == "XXX_NoUnkeyedLiteral" {
  246. continue
  247. }
  248. if strings.HasPrefix(name, "XXX_") {
  249. // There are two XXX_ fields:
  250. // XXX_unrecognized []byte
  251. // XXX_extensions map[int32]proto.Extension
  252. // The first is handled here;
  253. // the second is handled at the bottom of this function.
  254. if name == "XXX_unrecognized" && !fv.IsNil() {
  255. if err := writeUnknownStruct(w, fv.Interface().([]byte)); err != nil {
  256. return err
  257. }
  258. }
  259. continue
  260. }
  261. if fv.Kind() == reflect.Ptr && fv.IsNil() {
  262. // Field not filled in. This could be an optional field or
  263. // a required field that wasn't filled in. Either way, there
  264. // isn't anything we can show for it.
  265. continue
  266. }
  267. if fv.Kind() == reflect.Slice && fv.IsNil() {
  268. // Repeated field that is empty, or a bytes field that is unused.
  269. continue
  270. }
  271. if props.Repeated && fv.Kind() == reflect.Slice {
  272. // Repeated field.
  273. for j := 0; j < fv.Len(); j++ {
  274. if err := writeName(w, props); err != nil {
  275. return err
  276. }
  277. if !w.compact {
  278. if err := w.WriteByte(' '); err != nil {
  279. return err
  280. }
  281. }
  282. v := fv.Index(j)
  283. if v.Kind() == reflect.Ptr && v.IsNil() {
  284. // A nil message in a repeated field is not valid,
  285. // but we can handle that more gracefully than panicking.
  286. if _, err := w.Write([]byte("<nil>\n")); err != nil {
  287. return err
  288. }
  289. continue
  290. }
  291. if err := tm.writeAny(w, v, props); err != nil {
  292. return err
  293. }
  294. if err := w.WriteByte('\n'); err != nil {
  295. return err
  296. }
  297. }
  298. continue
  299. }
  300. if fv.Kind() == reflect.Map {
  301. // Map fields are rendered as a repeated struct with key/value fields.
  302. keys := fv.MapKeys()
  303. sort.Sort(mapKeys(keys))
  304. for _, key := range keys {
  305. val := fv.MapIndex(key)
  306. if err := writeName(w, props); err != nil {
  307. return err
  308. }
  309. if !w.compact {
  310. if err := w.WriteByte(' '); err != nil {
  311. return err
  312. }
  313. }
  314. // open struct
  315. if err := w.WriteByte('<'); err != nil {
  316. return err
  317. }
  318. if !w.compact {
  319. if err := w.WriteByte('\n'); err != nil {
  320. return err
  321. }
  322. }
  323. w.indent()
  324. // key
  325. if _, err := w.WriteString("key:"); err != nil {
  326. return err
  327. }
  328. if !w.compact {
  329. if err := w.WriteByte(' '); err != nil {
  330. return err
  331. }
  332. }
  333. if err := tm.writeAny(w, key, props.mkeyprop); err != nil {
  334. return err
  335. }
  336. if err := w.WriteByte('\n'); err != nil {
  337. return err
  338. }
  339. // nil values aren't legal, but we can avoid panicking because of them.
  340. if val.Kind() != reflect.Ptr || !val.IsNil() {
  341. // value
  342. if _, err := w.WriteString("value:"); err != nil {
  343. return err
  344. }
  345. if !w.compact {
  346. if err := w.WriteByte(' '); err != nil {
  347. return err
  348. }
  349. }
  350. if err := tm.writeAny(w, val, props.mvalprop); err != nil {
  351. return err
  352. }
  353. if err := w.WriteByte('\n'); err != nil {
  354. return err
  355. }
  356. }
  357. // close struct
  358. w.unindent()
  359. if err := w.WriteByte('>'); err != nil {
  360. return err
  361. }
  362. if err := w.WriteByte('\n'); err != nil {
  363. return err
  364. }
  365. }
  366. continue
  367. }
  368. if props.proto3 && fv.Kind() == reflect.Slice && fv.Len() == 0 {
  369. // empty bytes field
  370. continue
  371. }
  372. if fv.Kind() != reflect.Ptr && fv.Kind() != reflect.Slice {
  373. // proto3 non-repeated scalar field; skip if zero value
  374. if isProto3Zero(fv) {
  375. continue
  376. }
  377. }
  378. if fv.Kind() == reflect.Interface {
  379. // Check if it is a oneof.
  380. if st.Field(i).Tag.Get("protobuf_oneof") != "" {
  381. // fv is nil, or holds a pointer to generated struct.
  382. // That generated struct has exactly one field,
  383. // which has a protobuf struct tag.
  384. if fv.IsNil() {
  385. continue
  386. }
  387. inner := fv.Elem().Elem() // interface -> *T -> T
  388. tag := inner.Type().Field(0).Tag.Get("protobuf")
  389. props = new(Properties) // Overwrite the outer props var, but not its pointee.
  390. props.Parse(tag)
  391. // Write the value in the oneof, not the oneof itself.
  392. fv = inner.Field(0)
  393. // Special case to cope with malformed messages gracefully:
  394. // If the value in the oneof is a nil pointer, don't panic
  395. // in writeAny.
  396. if fv.Kind() == reflect.Ptr && fv.IsNil() {
  397. // Use errors.New so writeAny won't render quotes.
  398. msg := errors.New("/* nil */")
  399. fv = reflect.ValueOf(&msg).Elem()
  400. }
  401. }
  402. }
  403. if err := writeName(w, props); err != nil {
  404. return err
  405. }
  406. if !w.compact {
  407. if err := w.WriteByte(' '); err != nil {
  408. return err
  409. }
  410. }
  411. // Enums have a String method, so writeAny will work fine.
  412. if err := tm.writeAny(w, fv, props); err != nil {
  413. return err
  414. }
  415. if err := w.WriteByte('\n'); err != nil {
  416. return err
  417. }
  418. }
  419. // Extensions (the XXX_extensions field).
  420. pv := sv.Addr()
  421. if _, err := extendable(pv.Interface()); err == nil {
  422. if err := tm.writeExtensions(w, pv); err != nil {
  423. return err
  424. }
  425. }
  426. return nil
  427. }
  428. // writeRaw writes an uninterpreted raw message.
  429. func writeRaw(w *textWriter, b []byte) error {
  430. if err := w.WriteByte('<'); err != nil {
  431. return err
  432. }
  433. if !w.compact {
  434. if err := w.WriteByte('\n'); err != nil {
  435. return err
  436. }
  437. }
  438. w.indent()
  439. if err := writeUnknownStruct(w, b); err != nil {
  440. return err
  441. }
  442. w.unindent()
  443. return w.WriteByte('>')
  444. }
  445. // writeAny writes an arbitrary field.
  446. func (tm *TextMarshaler) writeAny(w *textWriter, v reflect.Value, props *Properties) error {
  447. v = reflect.Indirect(v)
  448. // Floats have special cases.
  449. if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 {
  450. x := v.Float()
  451. var b []byte
  452. switch {
  453. case math.IsInf(x, 1):
  454. b = posInf
  455. case math.IsInf(x, -1):
  456. b = negInf
  457. case math.IsNaN(x):
  458. b = nan
  459. }
  460. if b != nil {
  461. _, err := w.Write(b)
  462. return err
  463. }
  464. // Other values are handled below.
  465. }
  466. // We don't attempt to serialise every possible value type; only those
  467. // that can occur in protocol buffers.
  468. switch v.Kind() {
  469. case reflect.Slice:
  470. // Should only be a []byte; repeated fields are handled in writeStruct.
  471. if err := writeString(w, string(v.Bytes())); err != nil {
  472. return err
  473. }
  474. case reflect.String:
  475. if err := writeString(w, v.String()); err != nil {
  476. return err
  477. }
  478. case reflect.Struct:
  479. // Required/optional group/message.
  480. var bra, ket byte = '<', '>'
  481. if props != nil && props.Wire == "group" {
  482. bra, ket = '{', '}'
  483. }
  484. if err := w.WriteByte(bra); err != nil {
  485. return err
  486. }
  487. if !w.compact {
  488. if err := w.WriteByte('\n'); err != nil {
  489. return err
  490. }
  491. }
  492. w.indent()
  493. if v.CanAddr() {
  494. // Calling v.Interface on a struct causes the reflect package to
  495. // copy the entire struct. This is racy with the new Marshaler
  496. // since we atomically update the XXX_sizecache.
  497. //
  498. // Thus, we retrieve a pointer to the struct if possible to avoid
  499. // a race since v.Interface on the pointer doesn't copy the struct.
  500. //
  501. // If v is not addressable, then we are not worried about a race
  502. // since it implies that the binary Marshaler cannot possibly be
  503. // mutating this value.
  504. v = v.Addr()
  505. }
  506. if etm, ok := v.Interface().(encoding.TextMarshaler); ok {
  507. text, err := etm.MarshalText()
  508. if err != nil {
  509. return err
  510. }
  511. if _, err = w.Write(text); err != nil {
  512. return err
  513. }
  514. } else {
  515. if v.Kind() == reflect.Ptr {
  516. v = v.Elem()
  517. }
  518. if err := tm.writeStruct(w, v); err != nil {
  519. return err
  520. }
  521. }
  522. w.unindent()
  523. if err := w.WriteByte(ket); err != nil {
  524. return err
  525. }
  526. default:
  527. _, err := fmt.Fprint(w, v.Interface())
  528. return err
  529. }
  530. return nil
  531. }
  532. // equivalent to C's isprint.
  533. func isprint(c byte) bool {
  534. return c >= 0x20 && c < 0x7f
  535. }
  536. // writeString writes a string in the protocol buffer text format.
  537. // It is similar to strconv.Quote except we don't use Go escape sequences,
  538. // we treat the string as a byte sequence, and we use octal escapes.
  539. // These differences are to maintain interoperability with the other
  540. // languages' implementations of the text format.
  541. func writeString(w *textWriter, s string) error {
  542. // use WriteByte here to get any needed indent
  543. if err := w.WriteByte('"'); err != nil {
  544. return err
  545. }
  546. // Loop over the bytes, not the runes.
  547. for i := 0; i < len(s); i++ {
  548. var err error
  549. // Divergence from C++: we don't escape apostrophes.
  550. // There's no need to escape them, and the C++ parser
  551. // copes with a naked apostrophe.
  552. switch c := s[i]; c {
  553. case '\n':
  554. _, err = w.w.Write(backslashN)
  555. case '\r':
  556. _, err = w.w.Write(backslashR)
  557. case '\t':
  558. _, err = w.w.Write(backslashT)
  559. case '"':
  560. _, err = w.w.Write(backslashDQ)
  561. case '\\':
  562. _, err = w.w.Write(backslashBS)
  563. default:
  564. if isprint(c) {
  565. err = w.w.WriteByte(c)
  566. } else {
  567. _, err = fmt.Fprintf(w.w, "\\%03o", c)
  568. }
  569. }
  570. if err != nil {
  571. return err
  572. }
  573. }
  574. return w.WriteByte('"')
  575. }
  576. func writeUnknownStruct(w *textWriter, data []byte) (err error) {
  577. if !w.compact {
  578. if _, err := fmt.Fprintf(w, "/* %d unknown bytes */\n", len(data)); err != nil {
  579. return err
  580. }
  581. }
  582. b := NewBuffer(data)
  583. for b.index < len(b.buf) {
  584. x, err := b.DecodeVarint()
  585. if err != nil {
  586. _, err := fmt.Fprintf(w, "/* %v */\n", err)
  587. return err
  588. }
  589. wire, tag := x&7, x>>3
  590. if wire == WireEndGroup {
  591. w.unindent()
  592. if _, err := w.Write(endBraceNewline); err != nil {
  593. return err
  594. }
  595. continue
  596. }
  597. if _, err := fmt.Fprint(w, tag); err != nil {
  598. return err
  599. }
  600. if wire != WireStartGroup {
  601. if err := w.WriteByte(':'); err != nil {
  602. return err
  603. }
  604. }
  605. if !w.compact || wire == WireStartGroup {
  606. if err := w.WriteByte(' '); err != nil {
  607. return err
  608. }
  609. }
  610. switch wire {
  611. case WireBytes:
  612. buf, e := b.DecodeRawBytes(false)
  613. if e == nil {
  614. _, err = fmt.Fprintf(w, "%q", buf)
  615. } else {
  616. _, err = fmt.Fprintf(w, "/* %v */", e)
  617. }
  618. case WireFixed32:
  619. x, err = b.DecodeFixed32()
  620. err = writeUnknownInt(w, x, err)
  621. case WireFixed64:
  622. x, err = b.DecodeFixed64()
  623. err = writeUnknownInt(w, x, err)
  624. case WireStartGroup:
  625. err = w.WriteByte('{')
  626. w.indent()
  627. case WireVarint:
  628. x, err = b.DecodeVarint()
  629. err = writeUnknownInt(w, x, err)
  630. default:
  631. _, err = fmt.Fprintf(w, "/* unknown wire type %d */", wire)
  632. }
  633. if err != nil {
  634. return err
  635. }
  636. if err = w.WriteByte('\n'); err != nil {
  637. return err
  638. }
  639. }
  640. return nil
  641. }
  642. func writeUnknownInt(w *textWriter, x uint64, err error) error {
  643. if err == nil {
  644. _, err = fmt.Fprint(w, x)
  645. } else {
  646. _, err = fmt.Fprintf(w, "/* %v */", err)
  647. }
  648. return err
  649. }
  650. type int32Slice []int32
  651. func (s int32Slice) Len() int { return len(s) }
  652. func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] }
  653. func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  654. // writeExtensions writes all the extensions in pv.
  655. // pv is assumed to be a pointer to a protocol message struct that is extendable.
  656. func (tm *TextMarshaler) writeExtensions(w *textWriter, pv reflect.Value) error {
  657. emap := extensionMaps[pv.Type().Elem()]
  658. ep, _ := extendable(pv.Interface())
  659. // Order the extensions by ID.
  660. // This isn't strictly necessary, but it will give us
  661. // canonical output, which will also make testing easier.
  662. m, mu := ep.extensionsRead()
  663. if m == nil {
  664. return nil
  665. }
  666. mu.Lock()
  667. ids := make([]int32, 0, len(m))
  668. for id := range m {
  669. ids = append(ids, id)
  670. }
  671. sort.Sort(int32Slice(ids))
  672. mu.Unlock()
  673. for _, extNum := range ids {
  674. ext := m[extNum]
  675. var desc *ExtensionDesc
  676. if emap != nil {
  677. desc = emap[extNum]
  678. }
  679. if desc == nil {
  680. // Unknown extension.
  681. if err := writeUnknownStruct(w, ext.enc); err != nil {
  682. return err
  683. }
  684. continue
  685. }
  686. pb, err := GetExtension(ep, desc)
  687. if err != nil {
  688. return fmt.Errorf("failed getting extension: %v", err)
  689. }
  690. // Repeated extensions will appear as a slice.
  691. if !desc.repeated() {
  692. if err := tm.writeExtension(w, desc.Name, pb); err != nil {
  693. return err
  694. }
  695. } else {
  696. v := reflect.ValueOf(pb)
  697. for i := 0; i < v.Len(); i++ {
  698. if err := tm.writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil {
  699. return err
  700. }
  701. }
  702. }
  703. }
  704. return nil
  705. }
  706. func (tm *TextMarshaler) writeExtension(w *textWriter, name string, pb interface{}) error {
  707. if _, err := fmt.Fprintf(w, "[%s]:", name); err != nil {
  708. return err
  709. }
  710. if !w.compact {
  711. if err := w.WriteByte(' '); err != nil {
  712. return err
  713. }
  714. }
  715. if err := tm.writeAny(w, reflect.ValueOf(pb), nil); err != nil {
  716. return err
  717. }
  718. if err := w.WriteByte('\n'); err != nil {
  719. return err
  720. }
  721. return nil
  722. }
  723. func (w *textWriter) writeIndent() {
  724. if !w.complete {
  725. return
  726. }
  727. remain := w.ind * 2
  728. for remain > 0 {
  729. n := remain
  730. if n > len(spaces) {
  731. n = len(spaces)
  732. }
  733. w.w.Write(spaces[:n])
  734. remain -= n
  735. }
  736. w.complete = false
  737. }
  738. // TextMarshaler is a configurable text format marshaler.
  739. type TextMarshaler struct {
  740. Compact bool // use compact text format (one line).
  741. ExpandAny bool // expand google.protobuf.Any messages of known types
  742. }
  743. // Marshal writes a given protocol buffer in text format.
  744. // The only errors returned are from w.
  745. func (tm *TextMarshaler) Marshal(w io.Writer, pb Message) error {
  746. val := reflect.ValueOf(pb)
  747. if pb == nil || val.IsNil() {
  748. w.Write([]byte("<nil>"))
  749. return nil
  750. }
  751. var bw *bufio.Writer
  752. ww, ok := w.(writer)
  753. if !ok {
  754. bw = bufio.NewWriter(w)
  755. ww = bw
  756. }
  757. aw := &textWriter{
  758. w: ww,
  759. complete: true,
  760. compact: tm.Compact,
  761. }
  762. if etm, ok := pb.(encoding.TextMarshaler); ok {
  763. text, err := etm.MarshalText()
  764. if err != nil {
  765. return err
  766. }
  767. if _, err = aw.Write(text); err != nil {
  768. return err
  769. }
  770. if bw != nil {
  771. return bw.Flush()
  772. }
  773. return nil
  774. }
  775. // Dereference the received pointer so we don't have outer < and >.
  776. v := reflect.Indirect(val)
  777. if err := tm.writeStruct(aw, v); err != nil {
  778. return err
  779. }
  780. if bw != nil {
  781. return bw.Flush()
  782. }
  783. return nil
  784. }
  785. // Text is the same as Marshal, but returns the string directly.
  786. func (tm *TextMarshaler) Text(pb Message) string {
  787. var buf bytes.Buffer
  788. tm.Marshal(&buf, pb)
  789. return buf.String()
  790. }
  791. var (
  792. defaultTextMarshaler = TextMarshaler{}
  793. compactTextMarshaler = TextMarshaler{Compact: true}
  794. )
  795. // TODO: consider removing some of the Marshal functions below.
  796. // MarshalText writes a given protocol buffer in text format.
  797. // The only errors returned are from w.
  798. func MarshalText(w io.Writer, pb Message) error { return defaultTextMarshaler.Marshal(w, pb) }
  799. // MarshalTextString is the same as MarshalText, but returns the string directly.
  800. func MarshalTextString(pb Message) string { return defaultTextMarshaler.Text(pb) }
  801. // CompactText writes a given protocol buffer in compact text format (one line).
  802. func CompactText(w io.Writer, pb Message) error { return compactTextMarshaler.Marshal(w, pb) }
  803. // CompactTextString is the same as CompactText, but returns the string directly.
  804. func CompactTextString(pb Message) string { return compactTextMarshaler.Text(pb) }