text.go 18 KB

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