text.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789
  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. "fmt"
  38. "io"
  39. "log"
  40. "math"
  41. "os"
  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. var (
  159. messageSetType = reflect.TypeOf((*MessageSet)(nil)).Elem()
  160. )
  161. // raw is the interface satisfied by RawMessage.
  162. type raw interface {
  163. Bytes() []byte
  164. }
  165. func writeStruct(w *textWriter, sv reflect.Value) error {
  166. if sv.Type() == messageSetType {
  167. return writeMessageSet(w, sv.Addr().Interface().(*MessageSet))
  168. }
  169. st := sv.Type()
  170. sprops := GetProperties(st)
  171. for i := 0; i < sv.NumField(); i++ {
  172. fv := sv.Field(i)
  173. props := sprops.Prop[i]
  174. name := st.Field(i).Name
  175. if strings.HasPrefix(name, "XXX_") {
  176. // There are two XXX_ fields:
  177. // XXX_unrecognized []byte
  178. // XXX_extensions map[int32]proto.Extension
  179. // The first is handled here;
  180. // the second is handled at the bottom of this function.
  181. if name == "XXX_unrecognized" && !fv.IsNil() {
  182. if err := writeUnknownStruct(w, fv.Interface().([]byte)); err != nil {
  183. return err
  184. }
  185. }
  186. continue
  187. }
  188. if fv.Kind() == reflect.Ptr && fv.IsNil() {
  189. // Field not filled in. This could be an optional field or
  190. // a required field that wasn't filled in. Either way, there
  191. // isn't anything we can show for it.
  192. continue
  193. }
  194. if fv.Kind() == reflect.Slice && fv.IsNil() {
  195. // Repeated field that is empty, or a bytes field that is unused.
  196. continue
  197. }
  198. if props.Repeated && fv.Kind() == reflect.Slice {
  199. // Repeated field.
  200. for j := 0; j < fv.Len(); j++ {
  201. if err := writeName(w, props); err != nil {
  202. return err
  203. }
  204. if !w.compact {
  205. if err := w.WriteByte(' '); err != nil {
  206. return err
  207. }
  208. }
  209. v := fv.Index(j)
  210. if v.Kind() == reflect.Ptr && v.IsNil() {
  211. // A nil message in a repeated field is not valid,
  212. // but we can handle that more gracefully than panicking.
  213. if _, err := w.Write([]byte("<nil>\n")); err != nil {
  214. return err
  215. }
  216. continue
  217. }
  218. if err := writeAny(w, v, props); err != nil {
  219. return err
  220. }
  221. if err := w.WriteByte('\n'); err != nil {
  222. return err
  223. }
  224. }
  225. continue
  226. }
  227. if fv.Kind() == reflect.Map {
  228. // Map fields are rendered as a repeated struct with key/value fields.
  229. keys := fv.MapKeys() // TODO: should we sort these for deterministic output?
  230. sort.Sort(mapKeys(keys))
  231. for _, key := range keys {
  232. val := fv.MapIndex(key)
  233. if err := writeName(w, props); err != nil {
  234. return err
  235. }
  236. if !w.compact {
  237. if err := w.WriteByte(' '); err != nil {
  238. return err
  239. }
  240. }
  241. // open struct
  242. if err := w.WriteByte('<'); err != nil {
  243. return err
  244. }
  245. if !w.compact {
  246. if err := w.WriteByte('\n'); err != nil {
  247. return err
  248. }
  249. }
  250. w.indent()
  251. // key
  252. if _, err := w.WriteString("key:"); err != nil {
  253. return err
  254. }
  255. if !w.compact {
  256. if err := w.WriteByte(' '); err != nil {
  257. return err
  258. }
  259. }
  260. if err := writeAny(w, key, props.mkeyprop); err != nil {
  261. return err
  262. }
  263. if err := w.WriteByte('\n'); err != nil {
  264. return err
  265. }
  266. // value
  267. if _, err := w.WriteString("value:"); err != nil {
  268. return err
  269. }
  270. if !w.compact {
  271. if err := w.WriteByte(' '); err != nil {
  272. return err
  273. }
  274. }
  275. if err := writeAny(w, val, props.mvalprop); err != nil {
  276. return err
  277. }
  278. if err := w.WriteByte('\n'); err != nil {
  279. return err
  280. }
  281. // close struct
  282. w.unindent()
  283. if err := w.WriteByte('>'); err != nil {
  284. return err
  285. }
  286. if err := w.WriteByte('\n'); err != nil {
  287. return err
  288. }
  289. }
  290. continue
  291. }
  292. if props.proto3 && fv.Kind() == reflect.Slice && fv.Len() == 0 {
  293. // empty bytes field
  294. continue
  295. }
  296. if fv.Kind() != reflect.Ptr && fv.Kind() != reflect.Slice {
  297. // proto3 non-repeated scalar field; skip if zero value
  298. switch fv.Kind() {
  299. case reflect.Bool:
  300. if !fv.Bool() {
  301. continue
  302. }
  303. case reflect.Int32, reflect.Int64:
  304. if fv.Int() == 0 {
  305. continue
  306. }
  307. case reflect.Uint32, reflect.Uint64:
  308. if fv.Uint() == 0 {
  309. continue
  310. }
  311. case reflect.Float32, reflect.Float64:
  312. if fv.Float() == 0 {
  313. continue
  314. }
  315. case reflect.String:
  316. if fv.String() == "" {
  317. continue
  318. }
  319. }
  320. }
  321. if err := writeName(w, props); err != nil {
  322. return err
  323. }
  324. if !w.compact {
  325. if err := w.WriteByte(' '); err != nil {
  326. return err
  327. }
  328. }
  329. if b, ok := fv.Interface().(raw); ok {
  330. if err := writeRaw(w, b.Bytes()); err != nil {
  331. return err
  332. }
  333. continue
  334. }
  335. // Enums have a String method, so writeAny will work fine.
  336. if err := writeAny(w, fv, props); err != nil {
  337. return err
  338. }
  339. if err := w.WriteByte('\n'); err != nil {
  340. return err
  341. }
  342. }
  343. // Extensions (the XXX_extensions field).
  344. pv := sv.Addr()
  345. if pv.Type().Implements(extendableProtoType) {
  346. if err := writeExtensions(w, pv); err != nil {
  347. return err
  348. }
  349. }
  350. return nil
  351. }
  352. // writeRaw writes an uninterpreted raw message.
  353. func writeRaw(w *textWriter, b []byte) error {
  354. if err := w.WriteByte('<'); err != nil {
  355. return err
  356. }
  357. if !w.compact {
  358. if err := w.WriteByte('\n'); err != nil {
  359. return err
  360. }
  361. }
  362. w.indent()
  363. if err := writeUnknownStruct(w, b); err != nil {
  364. return err
  365. }
  366. w.unindent()
  367. if err := w.WriteByte('>'); err != nil {
  368. return err
  369. }
  370. return nil
  371. }
  372. // writeAny writes an arbitrary field.
  373. func writeAny(w *textWriter, v reflect.Value, props *Properties) error {
  374. v = reflect.Indirect(v)
  375. // Floats have special cases.
  376. if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 {
  377. x := v.Float()
  378. var b []byte
  379. switch {
  380. case math.IsInf(x, 1):
  381. b = posInf
  382. case math.IsInf(x, -1):
  383. b = negInf
  384. case math.IsNaN(x):
  385. b = nan
  386. }
  387. if b != nil {
  388. _, err := w.Write(b)
  389. return err
  390. }
  391. // Other values are handled below.
  392. }
  393. // We don't attempt to serialise every possible value type; only those
  394. // that can occur in protocol buffers.
  395. switch v.Kind() {
  396. case reflect.Slice:
  397. // Should only be a []byte; repeated fields are handled in writeStruct.
  398. if err := writeString(w, string(v.Interface().([]byte))); err != nil {
  399. return err
  400. }
  401. case reflect.String:
  402. if err := writeString(w, v.String()); err != nil {
  403. return err
  404. }
  405. case reflect.Struct:
  406. // Required/optional group/message.
  407. var bra, ket byte = '<', '>'
  408. if props != nil && props.Wire == "group" {
  409. bra, ket = '{', '}'
  410. }
  411. if err := w.WriteByte(bra); err != nil {
  412. return err
  413. }
  414. if !w.compact {
  415. if err := w.WriteByte('\n'); err != nil {
  416. return err
  417. }
  418. }
  419. w.indent()
  420. if tm, ok := v.Interface().(encoding.TextMarshaler); ok {
  421. text, err := tm.MarshalText()
  422. if err != nil {
  423. return err
  424. }
  425. if _, err = w.Write(text); err != nil {
  426. return err
  427. }
  428. } else if err := writeStruct(w, v); err != nil {
  429. return err
  430. }
  431. w.unindent()
  432. if err := w.WriteByte(ket); err != nil {
  433. return err
  434. }
  435. default:
  436. _, err := fmt.Fprint(w, v.Interface())
  437. return err
  438. }
  439. return nil
  440. }
  441. // equivalent to C's isprint.
  442. func isprint(c byte) bool {
  443. return c >= 0x20 && c < 0x7f
  444. }
  445. // writeString writes a string in the protocol buffer text format.
  446. // It is similar to strconv.Quote except we don't use Go escape sequences,
  447. // we treat the string as a byte sequence, and we use octal escapes.
  448. // These differences are to maintain interoperability with the other
  449. // languages' implementations of the text format.
  450. func writeString(w *textWriter, s string) error {
  451. // use WriteByte here to get any needed indent
  452. if err := w.WriteByte('"'); err != nil {
  453. return err
  454. }
  455. // Loop over the bytes, not the runes.
  456. for i := 0; i < len(s); i++ {
  457. var err error
  458. // Divergence from C++: we don't escape apostrophes.
  459. // There's no need to escape them, and the C++ parser
  460. // copes with a naked apostrophe.
  461. switch c := s[i]; c {
  462. case '\n':
  463. _, err = w.w.Write(backslashN)
  464. case '\r':
  465. _, err = w.w.Write(backslashR)
  466. case '\t':
  467. _, err = w.w.Write(backslashT)
  468. case '"':
  469. _, err = w.w.Write(backslashDQ)
  470. case '\\':
  471. _, err = w.w.Write(backslashBS)
  472. default:
  473. if isprint(c) {
  474. err = w.w.WriteByte(c)
  475. } else {
  476. _, err = fmt.Fprintf(w.w, "\\%03o", c)
  477. }
  478. }
  479. if err != nil {
  480. return err
  481. }
  482. }
  483. return w.WriteByte('"')
  484. }
  485. func writeMessageSet(w *textWriter, ms *MessageSet) error {
  486. for _, item := range ms.Item {
  487. id := *item.TypeId
  488. if msd, ok := messageSetMap[id]; ok {
  489. // Known message set type.
  490. if _, err := fmt.Fprintf(w, "[%s]: <\n", msd.name); err != nil {
  491. return err
  492. }
  493. w.indent()
  494. pb := reflect.New(msd.t.Elem())
  495. if err := Unmarshal(item.Message, pb.Interface().(Message)); err != nil {
  496. if _, err := fmt.Fprintf(w, "/* bad message: %v */\n", err); err != nil {
  497. return err
  498. }
  499. } else {
  500. if err := writeStruct(w, pb.Elem()); err != nil {
  501. return err
  502. }
  503. }
  504. } else {
  505. // Unknown type.
  506. if _, err := fmt.Fprintf(w, "[%d]: <\n", id); err != nil {
  507. return err
  508. }
  509. w.indent()
  510. if err := writeUnknownStruct(w, item.Message); err != nil {
  511. return err
  512. }
  513. }
  514. w.unindent()
  515. if _, err := w.Write(gtNewline); err != nil {
  516. return err
  517. }
  518. }
  519. return nil
  520. }
  521. func writeUnknownStruct(w *textWriter, data []byte) (err error) {
  522. if !w.compact {
  523. if _, err := fmt.Fprintf(w, "/* %d unknown bytes */\n", len(data)); err != nil {
  524. return err
  525. }
  526. }
  527. b := NewBuffer(data)
  528. for b.index < len(b.buf) {
  529. x, err := b.DecodeVarint()
  530. if err != nil {
  531. _, err := fmt.Fprintf(w, "/* %v */\n", err)
  532. return err
  533. }
  534. wire, tag := x&7, x>>3
  535. if wire == WireEndGroup {
  536. w.unindent()
  537. if _, err := w.Write(endBraceNewline); err != nil {
  538. return err
  539. }
  540. continue
  541. }
  542. if _, err := fmt.Fprint(w, tag); err != nil {
  543. return err
  544. }
  545. if wire != WireStartGroup {
  546. if err := w.WriteByte(':'); err != nil {
  547. return err
  548. }
  549. }
  550. if !w.compact || wire == WireStartGroup {
  551. if err := w.WriteByte(' '); err != nil {
  552. return err
  553. }
  554. }
  555. switch wire {
  556. case WireBytes:
  557. buf, e := b.DecodeRawBytes(false)
  558. if e == nil {
  559. _, err = fmt.Fprintf(w, "%q", buf)
  560. } else {
  561. _, err = fmt.Fprintf(w, "/* %v */", e)
  562. }
  563. case WireFixed32:
  564. x, err = b.DecodeFixed32()
  565. err = writeUnknownInt(w, x, err)
  566. case WireFixed64:
  567. x, err = b.DecodeFixed64()
  568. err = writeUnknownInt(w, x, err)
  569. case WireStartGroup:
  570. err = w.WriteByte('{')
  571. w.indent()
  572. case WireVarint:
  573. x, err = b.DecodeVarint()
  574. err = writeUnknownInt(w, x, err)
  575. default:
  576. _, err = fmt.Fprintf(w, "/* unknown wire type %d */", wire)
  577. }
  578. if err != nil {
  579. return err
  580. }
  581. if err = w.WriteByte('\n'); err != nil {
  582. return err
  583. }
  584. }
  585. return nil
  586. }
  587. func writeUnknownInt(w *textWriter, x uint64, err error) error {
  588. if err == nil {
  589. _, err = fmt.Fprint(w, x)
  590. } else {
  591. _, err = fmt.Fprintf(w, "/* %v */", err)
  592. }
  593. return err
  594. }
  595. type int32Slice []int32
  596. func (s int32Slice) Len() int { return len(s) }
  597. func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] }
  598. func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  599. // writeExtensions writes all the extensions in pv.
  600. // pv is assumed to be a pointer to a protocol message struct that is extendable.
  601. func writeExtensions(w *textWriter, pv reflect.Value) error {
  602. emap := extensionMaps[pv.Type().Elem()]
  603. ep := pv.Interface().(extendableProto)
  604. // Order the extensions by ID.
  605. // This isn't strictly necessary, but it will give us
  606. // canonical output, which will also make testing easier.
  607. m := ep.ExtensionMap()
  608. ids := make([]int32, 0, len(m))
  609. for id := range m {
  610. ids = append(ids, id)
  611. }
  612. sort.Sort(int32Slice(ids))
  613. for _, extNum := range ids {
  614. ext := m[extNum]
  615. var desc *ExtensionDesc
  616. if emap != nil {
  617. desc = emap[extNum]
  618. }
  619. if desc == nil {
  620. // Unknown extension.
  621. if err := writeUnknownStruct(w, ext.enc); err != nil {
  622. return err
  623. }
  624. continue
  625. }
  626. pb, err := GetExtension(ep, desc)
  627. if err != nil {
  628. if _, err := fmt.Fprintln(os.Stderr, "proto: failed getting extension: ", err); err != nil {
  629. return err
  630. }
  631. continue
  632. }
  633. // Repeated extensions will appear as a slice.
  634. if !desc.repeated() {
  635. if err := writeExtension(w, desc.Name, pb); err != nil {
  636. return err
  637. }
  638. } else {
  639. v := reflect.ValueOf(pb)
  640. for i := 0; i < v.Len(); i++ {
  641. if err := writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil {
  642. return err
  643. }
  644. }
  645. }
  646. }
  647. return nil
  648. }
  649. func writeExtension(w *textWriter, name string, pb interface{}) error {
  650. if _, err := fmt.Fprintf(w, "[%s]:", name); err != nil {
  651. return err
  652. }
  653. if !w.compact {
  654. if err := w.WriteByte(' '); err != nil {
  655. return err
  656. }
  657. }
  658. if err := writeAny(w, reflect.ValueOf(pb), nil); err != nil {
  659. return err
  660. }
  661. if err := w.WriteByte('\n'); err != nil {
  662. return err
  663. }
  664. return nil
  665. }
  666. func (w *textWriter) writeIndent() {
  667. if !w.complete {
  668. return
  669. }
  670. remain := w.ind * 2
  671. for remain > 0 {
  672. n := remain
  673. if n > len(spaces) {
  674. n = len(spaces)
  675. }
  676. w.w.Write(spaces[:n])
  677. remain -= n
  678. }
  679. w.complete = false
  680. }
  681. func marshalText(w io.Writer, pb Message, compact bool) error {
  682. val := reflect.ValueOf(pb)
  683. if pb == nil || val.IsNil() {
  684. w.Write([]byte("<nil>"))
  685. return nil
  686. }
  687. var bw *bufio.Writer
  688. ww, ok := w.(writer)
  689. if !ok {
  690. bw = bufio.NewWriter(w)
  691. ww = bw
  692. }
  693. aw := &textWriter{
  694. w: ww,
  695. complete: true,
  696. compact: compact,
  697. }
  698. if tm, ok := pb.(encoding.TextMarshaler); ok {
  699. text, err := tm.MarshalText()
  700. if err != nil {
  701. return err
  702. }
  703. if _, err = aw.Write(text); err != nil {
  704. return err
  705. }
  706. if bw != nil {
  707. return bw.Flush()
  708. }
  709. return nil
  710. }
  711. // Dereference the received pointer so we don't have outer < and >.
  712. v := reflect.Indirect(val)
  713. if err := writeStruct(aw, v); err != nil {
  714. return err
  715. }
  716. if bw != nil {
  717. return bw.Flush()
  718. }
  719. return nil
  720. }
  721. // MarshalText writes a given protocol buffer in text format.
  722. // The only errors returned are from w.
  723. func MarshalText(w io.Writer, pb Message) error {
  724. return marshalText(w, pb, false)
  725. }
  726. // MarshalTextString is the same as MarshalText, but returns the string directly.
  727. func MarshalTextString(pb Message) string {
  728. var buf bytes.Buffer
  729. marshalText(&buf, pb, false)
  730. return buf.String()
  731. }
  732. // CompactText writes a given protocol buffer in compact text format (one line).
  733. func CompactText(w io.Writer, pb Message) error { return marshalText(w, pb, true) }
  734. // CompactTextString is the same as CompactText, but returns the string directly.
  735. func CompactTextString(pb Message) string {
  736. var buf bytes.Buffer
  737. marshalText(&buf, pb, true)
  738. return buf.String()
  739. }