text.go 21 KB

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