text.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793
  1. // Extensions for Protocol Buffers to create more go like structures.
  2. //
  3. // Copyright (c) 2013, Vastech SA (PTY) LTD. All rights reserved.
  4. // http://github.com/gogo/protobuf/gogoproto
  5. //
  6. // Go support for Protocol Buffers - Google's data interchange format
  7. //
  8. // Copyright 2010 The Go Authors. All rights reserved.
  9. // https://github.com/golang/protobuf
  10. //
  11. // Redistribution and use in source and binary forms, with or without
  12. // modification, are permitted provided that the following conditions are
  13. // met:
  14. //
  15. // * Redistributions of source code must retain the above copyright
  16. // notice, this list of conditions and the following disclaimer.
  17. // * Redistributions in binary form must reproduce the above
  18. // copyright notice, this list of conditions and the following disclaimer
  19. // in the documentation and/or other materials provided with the
  20. // distribution.
  21. // * Neither the name of Google Inc. nor the names of its
  22. // contributors may be used to endorse or promote products derived from
  23. // this software without specific prior written permission.
  24. //
  25. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  26. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  27. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  28. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  29. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  30. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  31. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  32. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  33. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  34. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  35. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  36. package proto
  37. // Functions for writing the text protocol buffer format.
  38. import (
  39. "bufio"
  40. "bytes"
  41. "encoding"
  42. "errors"
  43. "fmt"
  44. "io"
  45. "log"
  46. "math"
  47. "reflect"
  48. "sort"
  49. "strings"
  50. )
  51. var (
  52. newline = []byte("\n")
  53. spaces = []byte(" ")
  54. gtNewline = []byte(">\n")
  55. endBraceNewline = []byte("}\n")
  56. backslashN = []byte{'\\', 'n'}
  57. backslashR = []byte{'\\', 'r'}
  58. backslashT = []byte{'\\', 't'}
  59. backslashDQ = []byte{'\\', '"'}
  60. backslashBS = []byte{'\\', '\\'}
  61. posInf = []byte("inf")
  62. negInf = []byte("-inf")
  63. nan = []byte("nan")
  64. )
  65. type writer interface {
  66. io.Writer
  67. WriteByte(byte) error
  68. }
  69. // textWriter is an io.Writer that tracks its indentation level.
  70. type textWriter struct {
  71. ind int
  72. complete bool // if the current position is a complete line
  73. compact bool // whether to write out as a one-liner
  74. w writer
  75. }
  76. func (w *textWriter) WriteString(s string) (n int, err error) {
  77. if !strings.Contains(s, "\n") {
  78. if !w.compact && w.complete {
  79. w.writeIndent()
  80. }
  81. w.complete = false
  82. return io.WriteString(w.w, s)
  83. }
  84. // WriteString is typically called without newlines, so this
  85. // codepath and its copy are rare. We copy to avoid
  86. // duplicating all of Write's logic here.
  87. return w.Write([]byte(s))
  88. }
  89. func (w *textWriter) Write(p []byte) (n int, err error) {
  90. newlines := bytes.Count(p, newline)
  91. if newlines == 0 {
  92. if !w.compact && w.complete {
  93. w.writeIndent()
  94. }
  95. n, err = w.w.Write(p)
  96. w.complete = false
  97. return n, err
  98. }
  99. frags := bytes.SplitN(p, newline, newlines+1)
  100. if w.compact {
  101. for i, frag := range frags {
  102. if i > 0 {
  103. if err := w.w.WriteByte(' '); err != nil {
  104. return n, err
  105. }
  106. n++
  107. }
  108. nn, err := w.w.Write(frag)
  109. n += nn
  110. if err != nil {
  111. return n, err
  112. }
  113. }
  114. return n, nil
  115. }
  116. for i, frag := range frags {
  117. if w.complete {
  118. w.writeIndent()
  119. }
  120. nn, err := w.w.Write(frag)
  121. n += nn
  122. if err != nil {
  123. return n, err
  124. }
  125. if i+1 < len(frags) {
  126. if err := w.w.WriteByte('\n'); err != nil {
  127. return n, err
  128. }
  129. n++
  130. }
  131. }
  132. w.complete = len(frags[len(frags)-1]) == 0
  133. return n, nil
  134. }
  135. func (w *textWriter) WriteByte(c byte) error {
  136. if w.compact && c == '\n' {
  137. c = ' '
  138. }
  139. if !w.compact && w.complete {
  140. w.writeIndent()
  141. }
  142. err := w.w.WriteByte(c)
  143. w.complete = c == '\n'
  144. return err
  145. }
  146. func (w *textWriter) indent() { w.ind++ }
  147. func (w *textWriter) unindent() {
  148. if w.ind == 0 {
  149. log.Printf("proto: textWriter unindented too far")
  150. return
  151. }
  152. w.ind--
  153. }
  154. func writeName(w *textWriter, props *Properties) error {
  155. if _, err := w.WriteString(props.OrigName); err != nil {
  156. return err
  157. }
  158. if props.Wire != "group" {
  159. return w.WriteByte(':')
  160. }
  161. return nil
  162. }
  163. // raw is the interface satisfied by RawMessage.
  164. type raw interface {
  165. Bytes() []byte
  166. }
  167. func writeStruct(w *textWriter, sv reflect.Value) error {
  168. st := sv.Type()
  169. sprops := GetProperties(st)
  170. for i := 0; i < sv.NumField(); i++ {
  171. fv := sv.Field(i)
  172. props := sprops.Prop[i]
  173. name := st.Field(i).Name
  174. if strings.HasPrefix(name, "XXX_") {
  175. // There are two XXX_ fields:
  176. // XXX_unrecognized []byte
  177. // XXX_extensions map[int32]proto.Extension
  178. // The first is handled here;
  179. // the second is handled at the bottom of this function.
  180. if name == "XXX_unrecognized" && !fv.IsNil() {
  181. if err := writeUnknownStruct(w, fv.Interface().([]byte)); err != nil {
  182. return err
  183. }
  184. }
  185. continue
  186. }
  187. if fv.Kind() == reflect.Ptr && fv.IsNil() {
  188. // Field not filled in. This could be an optional field or
  189. // a required field that wasn't filled in. Either way, there
  190. // isn't anything we can show for it.
  191. continue
  192. }
  193. if fv.Kind() == reflect.Slice && fv.IsNil() {
  194. // Repeated field that is empty, or a bytes field that is unused.
  195. continue
  196. }
  197. if props.Repeated && fv.Kind() == reflect.Slice {
  198. // Repeated field.
  199. for j := 0; j < fv.Len(); j++ {
  200. if err := writeName(w, props); err != nil {
  201. return err
  202. }
  203. if !w.compact {
  204. if err := w.WriteByte(' '); err != nil {
  205. return err
  206. }
  207. }
  208. v := fv.Index(j)
  209. if v.Kind() == reflect.Ptr && v.IsNil() {
  210. // A nil message in a repeated field is not valid,
  211. // but we can handle that more gracefully than panicking.
  212. if _, err := w.Write([]byte("<nil>\n")); err != nil {
  213. return err
  214. }
  215. continue
  216. }
  217. if len(props.Enum) > 0 {
  218. if err := writeEnum(w, v, props); err != nil {
  219. return err
  220. }
  221. } else if err := writeAny(w, v, props); err != nil {
  222. return err
  223. }
  224. if err := w.WriteByte('\n'); err != nil {
  225. return err
  226. }
  227. }
  228. continue
  229. }
  230. if fv.Kind() == reflect.Map {
  231. // Map fields are rendered as a repeated struct with key/value fields.
  232. keys := fv.MapKeys()
  233. sort.Sort(mapKeys(keys))
  234. for _, key := range keys {
  235. val := fv.MapIndex(key)
  236. if err := writeName(w, props); err != nil {
  237. return err
  238. }
  239. if !w.compact {
  240. if err := w.WriteByte(' '); err != nil {
  241. return err
  242. }
  243. }
  244. // open struct
  245. if err := w.WriteByte('<'); err != nil {
  246. return err
  247. }
  248. if !w.compact {
  249. if err := w.WriteByte('\n'); err != nil {
  250. return err
  251. }
  252. }
  253. w.indent()
  254. // key
  255. if _, err := w.WriteString("key:"); err != nil {
  256. return err
  257. }
  258. if !w.compact {
  259. if err := w.WriteByte(' '); err != nil {
  260. return err
  261. }
  262. }
  263. if err := writeAny(w, key, props.mkeyprop); err != nil {
  264. return err
  265. }
  266. if err := w.WriteByte('\n'); err != nil {
  267. return err
  268. }
  269. // nil values aren't legal, but we can avoid panicking because of them.
  270. if val.Kind() != reflect.Ptr || !val.IsNil() {
  271. // value
  272. if _, err := w.WriteString("value:"); err != nil {
  273. return err
  274. }
  275. if !w.compact {
  276. if err := w.WriteByte(' '); err != nil {
  277. return err
  278. }
  279. }
  280. if err := writeAny(w, val, props.mvalprop); err != nil {
  281. return err
  282. }
  283. if err := w.WriteByte('\n'); err != nil {
  284. return err
  285. }
  286. }
  287. // close struct
  288. w.unindent()
  289. if err := w.WriteByte('>'); err != nil {
  290. return err
  291. }
  292. if err := w.WriteByte('\n'); err != nil {
  293. return err
  294. }
  295. }
  296. continue
  297. }
  298. if props.proto3 && fv.Kind() == reflect.Slice && fv.Len() == 0 {
  299. // empty bytes field
  300. continue
  301. }
  302. if props.proto3 && fv.Kind() != reflect.Ptr && fv.Kind() != reflect.Slice {
  303. // proto3 non-repeated scalar field; skip if zero value
  304. if isProto3Zero(fv) {
  305. continue
  306. }
  307. }
  308. if fv.Kind() == reflect.Interface {
  309. // Check if it is a oneof.
  310. if st.Field(i).Tag.Get("protobuf_oneof") != "" {
  311. // fv is nil, or holds a pointer to generated struct.
  312. // That generated struct has exactly one field,
  313. // which has a protobuf struct tag.
  314. if fv.IsNil() {
  315. continue
  316. }
  317. inner := fv.Elem().Elem() // interface -> *T -> T
  318. tag := inner.Type().Field(0).Tag.Get("protobuf")
  319. props.Parse(tag) // Overwrite the outer props.
  320. // Write the value in the oneof, not the oneof itself.
  321. fv = inner.Field(0)
  322. // Special case to cope with malformed messages gracefully:
  323. // If the value in the oneof is a nil pointer, don't panic
  324. // in writeAny.
  325. if fv.Kind() == reflect.Ptr && fv.IsNil() {
  326. // Use errors.New so writeAny won't render quotes.
  327. msg := errors.New("/* nil */")
  328. fv = reflect.ValueOf(&msg).Elem()
  329. }
  330. }
  331. }
  332. if err := writeName(w, props); err != nil {
  333. return err
  334. }
  335. if !w.compact {
  336. if err := w.WriteByte(' '); err != nil {
  337. return err
  338. }
  339. }
  340. if b, ok := fv.Interface().(raw); ok {
  341. if err := writeRaw(w, b.Bytes()); err != nil {
  342. return err
  343. }
  344. continue
  345. }
  346. if len(props.Enum) > 0 {
  347. if err := writeEnum(w, fv, props); err != nil {
  348. return err
  349. }
  350. } else if err := writeAny(w, fv, props); err != nil {
  351. return err
  352. }
  353. if err := w.WriteByte('\n'); err != nil {
  354. return err
  355. }
  356. }
  357. // Extensions (the XXX_extensions field).
  358. pv := sv
  359. if pv.CanAddr() {
  360. pv = sv.Addr()
  361. } else {
  362. pv = reflect.New(sv.Type())
  363. pv.Elem().Set(sv)
  364. }
  365. if pv.Type().Implements(extendableProtoType) {
  366. if err := writeExtensions(w, pv); err != nil {
  367. return err
  368. }
  369. }
  370. return nil
  371. }
  372. // writeRaw writes an uninterpreted raw message.
  373. func writeRaw(w *textWriter, b []byte) error {
  374. if err := w.WriteByte('<'); err != nil {
  375. return err
  376. }
  377. if !w.compact {
  378. if err := w.WriteByte('\n'); err != nil {
  379. return err
  380. }
  381. }
  382. w.indent()
  383. if err := writeUnknownStruct(w, b); err != nil {
  384. return err
  385. }
  386. w.unindent()
  387. if err := w.WriteByte('>'); err != nil {
  388. return err
  389. }
  390. return nil
  391. }
  392. // writeAny writes an arbitrary field.
  393. func writeAny(w *textWriter, v reflect.Value, props *Properties) error {
  394. v = reflect.Indirect(v)
  395. if props != nil && len(props.CustomType) > 0 {
  396. custom, ok := v.Interface().(Marshaler)
  397. if ok {
  398. data, err := custom.Marshal()
  399. if err != nil {
  400. return err
  401. }
  402. if err := writeString(w, string(data)); err != nil {
  403. return err
  404. }
  405. return nil
  406. }
  407. }
  408. // Floats have special cases.
  409. if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 {
  410. x := v.Float()
  411. var b []byte
  412. switch {
  413. case math.IsInf(x, 1):
  414. b = posInf
  415. case math.IsInf(x, -1):
  416. b = negInf
  417. case math.IsNaN(x):
  418. b = nan
  419. }
  420. if b != nil {
  421. _, err := w.Write(b)
  422. return err
  423. }
  424. // Other values are handled below.
  425. }
  426. // We don't attempt to serialise every possible value type; only those
  427. // that can occur in protocol buffers.
  428. switch v.Kind() {
  429. case reflect.Slice:
  430. // Should only be a []byte; repeated fields are handled in writeStruct.
  431. if err := writeString(w, string(v.Bytes())); err != nil {
  432. return err
  433. }
  434. case reflect.String:
  435. if err := writeString(w, v.String()); err != nil {
  436. return err
  437. }
  438. case reflect.Struct:
  439. // Required/optional group/message.
  440. var bra, ket byte = '<', '>'
  441. if props != nil && props.Wire == "group" {
  442. bra, ket = '{', '}'
  443. }
  444. if err := w.WriteByte(bra); err != nil {
  445. return err
  446. }
  447. if !w.compact {
  448. if err := w.WriteByte('\n'); err != nil {
  449. return err
  450. }
  451. }
  452. w.indent()
  453. if tm, ok := v.Interface().(encoding.TextMarshaler); ok {
  454. text, err := tm.MarshalText()
  455. if err != nil {
  456. return err
  457. }
  458. if _, err = w.Write(text); err != nil {
  459. return err
  460. }
  461. } else if err := writeStruct(w, v); err != nil {
  462. return err
  463. }
  464. w.unindent()
  465. if err := w.WriteByte(ket); err != nil {
  466. return err
  467. }
  468. default:
  469. _, err := fmt.Fprint(w, v.Interface())
  470. return err
  471. }
  472. return nil
  473. }
  474. // equivalent to C's isprint.
  475. func isprint(c byte) bool {
  476. return c >= 0x20 && c < 0x7f
  477. }
  478. // writeString writes a string in the protocol buffer text format.
  479. // It is similar to strconv.Quote except we don't use Go escape sequences,
  480. // we treat the string as a byte sequence, and we use octal escapes.
  481. // These differences are to maintain interoperability with the other
  482. // languages' implementations of the text format.
  483. func writeString(w *textWriter, s string) error {
  484. // use WriteByte here to get any needed indent
  485. if err := w.WriteByte('"'); err != nil {
  486. return err
  487. }
  488. // Loop over the bytes, not the runes.
  489. for i := 0; i < len(s); i++ {
  490. var err error
  491. // Divergence from C++: we don't escape apostrophes.
  492. // There's no need to escape them, and the C++ parser
  493. // copes with a naked apostrophe.
  494. switch c := s[i]; c {
  495. case '\n':
  496. _, err = w.w.Write(backslashN)
  497. case '\r':
  498. _, err = w.w.Write(backslashR)
  499. case '\t':
  500. _, err = w.w.Write(backslashT)
  501. case '"':
  502. _, err = w.w.Write(backslashDQ)
  503. case '\\':
  504. _, err = w.w.Write(backslashBS)
  505. default:
  506. if isprint(c) {
  507. err = w.w.WriteByte(c)
  508. } else {
  509. _, err = fmt.Fprintf(w.w, "\\%03o", c)
  510. }
  511. }
  512. if err != nil {
  513. return err
  514. }
  515. }
  516. return w.WriteByte('"')
  517. }
  518. func writeUnknownStruct(w *textWriter, data []byte) (err error) {
  519. if !w.compact {
  520. if _, err := fmt.Fprintf(w, "/* %d unknown bytes */\n", len(data)); err != nil {
  521. return err
  522. }
  523. }
  524. b := NewBuffer(data)
  525. for b.index < len(b.buf) {
  526. x, err := b.DecodeVarint()
  527. if err != nil {
  528. _, ferr := fmt.Fprintf(w, "/* %v */\n", err)
  529. return ferr
  530. }
  531. wire, tag := x&7, x>>3
  532. if wire == WireEndGroup {
  533. w.unindent()
  534. if _, werr := w.Write(endBraceNewline); werr != nil {
  535. return werr
  536. }
  537. continue
  538. }
  539. if _, ferr := fmt.Fprint(w, tag); ferr != nil {
  540. return ferr
  541. }
  542. if wire != WireStartGroup {
  543. if err = w.WriteByte(':'); err != nil {
  544. return err
  545. }
  546. }
  547. if !w.compact || wire == WireStartGroup {
  548. if err = w.WriteByte(' '); err != nil {
  549. return err
  550. }
  551. }
  552. switch wire {
  553. case WireBytes:
  554. buf, e := b.DecodeRawBytes(false)
  555. if e == nil {
  556. _, err = fmt.Fprintf(w, "%q", buf)
  557. } else {
  558. _, err = fmt.Fprintf(w, "/* %v */", e)
  559. }
  560. case WireFixed32:
  561. x, err = b.DecodeFixed32()
  562. err = writeUnknownInt(w, x, err)
  563. case WireFixed64:
  564. x, err = b.DecodeFixed64()
  565. err = writeUnknownInt(w, x, err)
  566. case WireStartGroup:
  567. err = w.WriteByte('{')
  568. w.indent()
  569. case WireVarint:
  570. x, err = b.DecodeVarint()
  571. err = writeUnknownInt(w, x, err)
  572. default:
  573. _, err = fmt.Fprintf(w, "/* unknown wire type %d */", wire)
  574. }
  575. if err != nil {
  576. return err
  577. }
  578. if err := w.WriteByte('\n'); err != nil {
  579. return err
  580. }
  581. }
  582. return nil
  583. }
  584. func writeUnknownInt(w *textWriter, x uint64, err error) error {
  585. if err == nil {
  586. _, err = fmt.Fprint(w, x)
  587. } else {
  588. _, err = fmt.Fprintf(w, "/* %v */", err)
  589. }
  590. return err
  591. }
  592. type int32Slice []int32
  593. func (s int32Slice) Len() int { return len(s) }
  594. func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] }
  595. func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  596. // writeExtensions writes all the extensions in pv.
  597. // pv is assumed to be a pointer to a protocol message struct that is extendable.
  598. func writeExtensions(w *textWriter, pv reflect.Value) error {
  599. emap := extensionMaps[pv.Type().Elem()]
  600. ep := pv.Interface().(extendableProto)
  601. // Order the extensions by ID.
  602. // This isn't strictly necessary, but it will give us
  603. // canonical output, which will also make testing easier.
  604. var m map[int32]Extension
  605. if em, ok := ep.(extensionsMap); ok {
  606. m = em.ExtensionMap()
  607. } else if em, ok := ep.(extensionsBytes); ok {
  608. eb := em.GetExtensions()
  609. var err error
  610. m, err = BytesToExtensionsMap(*eb)
  611. if err != nil {
  612. return err
  613. }
  614. }
  615. ids := make([]int32, 0, len(m))
  616. for id := range m {
  617. ids = append(ids, id)
  618. }
  619. sort.Sort(int32Slice(ids))
  620. for _, extNum := range ids {
  621. ext := m[extNum]
  622. var desc *ExtensionDesc
  623. if emap != nil {
  624. desc = emap[extNum]
  625. }
  626. if desc == nil {
  627. // Unknown extension.
  628. if err := writeUnknownStruct(w, ext.enc); err != nil {
  629. return err
  630. }
  631. continue
  632. }
  633. pb, err := GetExtension(ep, desc)
  634. if err != nil {
  635. return fmt.Errorf("failed getting extension: %v", err)
  636. }
  637. // Repeated extensions will appear as a slice.
  638. if !desc.repeated() {
  639. if err := writeExtension(w, desc.Name, pb); err != nil {
  640. return err
  641. }
  642. } else {
  643. v := reflect.ValueOf(pb)
  644. for i := 0; i < v.Len(); i++ {
  645. if err := writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil {
  646. return err
  647. }
  648. }
  649. }
  650. }
  651. return nil
  652. }
  653. func writeExtension(w *textWriter, name string, pb interface{}) error {
  654. if _, err := fmt.Fprintf(w, "[%s]:", name); err != nil {
  655. return err
  656. }
  657. if !w.compact {
  658. if err := w.WriteByte(' '); err != nil {
  659. return err
  660. }
  661. }
  662. if err := writeAny(w, reflect.ValueOf(pb), nil); err != nil {
  663. return err
  664. }
  665. if err := w.WriteByte('\n'); err != nil {
  666. return err
  667. }
  668. return nil
  669. }
  670. func (w *textWriter) writeIndent() {
  671. if !w.complete {
  672. return
  673. }
  674. remain := w.ind * 2
  675. for remain > 0 {
  676. n := remain
  677. if n > len(spaces) {
  678. n = len(spaces)
  679. }
  680. w.w.Write(spaces[:n])
  681. remain -= n
  682. }
  683. w.complete = false
  684. }
  685. func marshalText(w io.Writer, pb Message, compact bool) error {
  686. val := reflect.ValueOf(pb)
  687. if pb == nil || val.IsNil() {
  688. w.Write([]byte("<nil>"))
  689. return nil
  690. }
  691. var bw *bufio.Writer
  692. ww, ok := w.(writer)
  693. if !ok {
  694. bw = bufio.NewWriter(w)
  695. ww = bw
  696. }
  697. aw := &textWriter{
  698. w: ww,
  699. complete: true,
  700. compact: compact,
  701. }
  702. if tm, ok := pb.(encoding.TextMarshaler); ok {
  703. text, err := tm.MarshalText()
  704. if err != nil {
  705. return err
  706. }
  707. if _, err = aw.Write(text); err != nil {
  708. return err
  709. }
  710. if bw != nil {
  711. return bw.Flush()
  712. }
  713. return nil
  714. }
  715. // Dereference the received pointer so we don't have outer < and >.
  716. v := reflect.Indirect(val)
  717. if err := writeStruct(aw, v); err != nil {
  718. return err
  719. }
  720. if bw != nil {
  721. return bw.Flush()
  722. }
  723. return nil
  724. }
  725. // MarshalText writes a given protocol buffer in text format.
  726. // The only errors returned are from w.
  727. func MarshalText(w io.Writer, pb Message) error {
  728. return marshalText(w, pb, false)
  729. }
  730. // MarshalTextString is the same as MarshalText, but returns the string directly.
  731. func MarshalTextString(pb Message) string {
  732. var buf bytes.Buffer
  733. marshalText(&buf, pb, false)
  734. return buf.String()
  735. }
  736. // CompactText writes a given protocol buffer in compact text format (one line).
  737. func CompactText(w io.Writer, pb Message) error { return marshalText(w, pb, true) }
  738. // CompactTextString is the same as CompactText, but returns the string directly.
  739. func CompactTextString(pb Message) string {
  740. var buf bytes.Buffer
  741. marshalText(&buf, pb, true)
  742. return buf.String()
  743. }