text.go 19 KB

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