text.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  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 = new(Properties) // Overwrite the outer props var, but not its pointee.
  320. props.Parse(tag)
  321. // Write the value in the oneof, not the oneof itself.
  322. fv = inner.Field(0)
  323. // Special case to cope with malformed messages gracefully:
  324. // If the value in the oneof is a nil pointer, don't panic
  325. // in writeAny.
  326. if fv.Kind() == reflect.Ptr && fv.IsNil() {
  327. // Use errors.New so writeAny won't render quotes.
  328. msg := errors.New("/* nil */")
  329. fv = reflect.ValueOf(&msg).Elem()
  330. }
  331. }
  332. }
  333. if err := writeName(w, props); err != nil {
  334. return err
  335. }
  336. if !w.compact {
  337. if err := w.WriteByte(' '); err != nil {
  338. return err
  339. }
  340. }
  341. if b, ok := fv.Interface().(raw); ok {
  342. if err := writeRaw(w, b.Bytes()); err != nil {
  343. return err
  344. }
  345. continue
  346. }
  347. if len(props.Enum) > 0 {
  348. if err := writeEnum(w, fv, props); err != nil {
  349. return err
  350. }
  351. } else if err := writeAny(w, fv, props); err != nil {
  352. return err
  353. }
  354. if err := w.WriteByte('\n'); err != nil {
  355. return err
  356. }
  357. }
  358. // Extensions (the XXX_extensions field).
  359. pv := sv
  360. if pv.CanAddr() {
  361. pv = sv.Addr()
  362. } else {
  363. pv = reflect.New(sv.Type())
  364. pv.Elem().Set(sv)
  365. }
  366. if pv.Type().Implements(extendableProtoType) {
  367. if err := writeExtensions(w, pv); err != nil {
  368. return err
  369. }
  370. }
  371. return nil
  372. }
  373. // writeRaw writes an uninterpreted raw message.
  374. func writeRaw(w *textWriter, b []byte) error {
  375. if err := w.WriteByte('<'); err != nil {
  376. return err
  377. }
  378. if !w.compact {
  379. if err := w.WriteByte('\n'); err != nil {
  380. return err
  381. }
  382. }
  383. w.indent()
  384. if err := writeUnknownStruct(w, b); err != nil {
  385. return err
  386. }
  387. w.unindent()
  388. if err := w.WriteByte('>'); err != nil {
  389. return err
  390. }
  391. return nil
  392. }
  393. // writeAny writes an arbitrary field.
  394. func writeAny(w *textWriter, v reflect.Value, props *Properties) error {
  395. v = reflect.Indirect(v)
  396. if props != nil && len(props.CustomType) > 0 {
  397. custom, ok := v.Interface().(Marshaler)
  398. if ok {
  399. data, err := custom.Marshal()
  400. if err != nil {
  401. return err
  402. }
  403. if err := writeString(w, string(data)); err != nil {
  404. return err
  405. }
  406. return nil
  407. }
  408. }
  409. // Floats have special cases.
  410. if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 {
  411. x := v.Float()
  412. var b []byte
  413. switch {
  414. case math.IsInf(x, 1):
  415. b = posInf
  416. case math.IsInf(x, -1):
  417. b = negInf
  418. case math.IsNaN(x):
  419. b = nan
  420. }
  421. if b != nil {
  422. _, err := w.Write(b)
  423. return err
  424. }
  425. // Other values are handled below.
  426. }
  427. // We don't attempt to serialise every possible value type; only those
  428. // that can occur in protocol buffers.
  429. switch v.Kind() {
  430. case reflect.Slice:
  431. // Should only be a []byte; repeated fields are handled in writeStruct.
  432. if err := writeString(w, string(v.Bytes())); err != nil {
  433. return err
  434. }
  435. case reflect.String:
  436. if err := writeString(w, v.String()); err != nil {
  437. return err
  438. }
  439. case reflect.Struct:
  440. // Required/optional group/message.
  441. var bra, ket byte = '<', '>'
  442. if props != nil && props.Wire == "group" {
  443. bra, ket = '{', '}'
  444. }
  445. if err := w.WriteByte(bra); err != nil {
  446. return err
  447. }
  448. if !w.compact {
  449. if err := w.WriteByte('\n'); err != nil {
  450. return err
  451. }
  452. }
  453. w.indent()
  454. if tm, ok := v.Interface().(encoding.TextMarshaler); ok {
  455. text, err := tm.MarshalText()
  456. if err != nil {
  457. return err
  458. }
  459. if _, err = w.Write(text); err != nil {
  460. return err
  461. }
  462. } else if err := writeStruct(w, v); err != nil {
  463. return err
  464. }
  465. w.unindent()
  466. if err := w.WriteByte(ket); err != nil {
  467. return err
  468. }
  469. default:
  470. _, err := fmt.Fprint(w, v.Interface())
  471. return err
  472. }
  473. return nil
  474. }
  475. // equivalent to C's isprint.
  476. func isprint(c byte) bool {
  477. return c >= 0x20 && c < 0x7f
  478. }
  479. // writeString writes a string in the protocol buffer text format.
  480. // It is similar to strconv.Quote except we don't use Go escape sequences,
  481. // we treat the string as a byte sequence, and we use octal escapes.
  482. // These differences are to maintain interoperability with the other
  483. // languages' implementations of the text format.
  484. func writeString(w *textWriter, s string) error {
  485. // use WriteByte here to get any needed indent
  486. if err := w.WriteByte('"'); err != nil {
  487. return err
  488. }
  489. // Loop over the bytes, not the runes.
  490. for i := 0; i < len(s); i++ {
  491. var err error
  492. // Divergence from C++: we don't escape apostrophes.
  493. // There's no need to escape them, and the C++ parser
  494. // copes with a naked apostrophe.
  495. switch c := s[i]; c {
  496. case '\n':
  497. _, err = w.w.Write(backslashN)
  498. case '\r':
  499. _, err = w.w.Write(backslashR)
  500. case '\t':
  501. _, err = w.w.Write(backslashT)
  502. case '"':
  503. _, err = w.w.Write(backslashDQ)
  504. case '\\':
  505. _, err = w.w.Write(backslashBS)
  506. default:
  507. if isprint(c) {
  508. err = w.w.WriteByte(c)
  509. } else {
  510. _, err = fmt.Fprintf(w.w, "\\%03o", c)
  511. }
  512. }
  513. if err != nil {
  514. return err
  515. }
  516. }
  517. return w.WriteByte('"')
  518. }
  519. func writeUnknownStruct(w *textWriter, data []byte) (err error) {
  520. if !w.compact {
  521. if _, err := fmt.Fprintf(w, "/* %d unknown bytes */\n", len(data)); err != nil {
  522. return err
  523. }
  524. }
  525. b := NewBuffer(data)
  526. for b.index < len(b.buf) {
  527. x, err := b.DecodeVarint()
  528. if err != nil {
  529. _, ferr := fmt.Fprintf(w, "/* %v */\n", err)
  530. return ferr
  531. }
  532. wire, tag := x&7, x>>3
  533. if wire == WireEndGroup {
  534. w.unindent()
  535. if _, werr := w.Write(endBraceNewline); werr != nil {
  536. return werr
  537. }
  538. continue
  539. }
  540. if _, ferr := fmt.Fprint(w, tag); ferr != nil {
  541. return ferr
  542. }
  543. if wire != WireStartGroup {
  544. if err = w.WriteByte(':'); err != nil {
  545. return err
  546. }
  547. }
  548. if !w.compact || wire == WireStartGroup {
  549. if err = w.WriteByte(' '); err != nil {
  550. return err
  551. }
  552. }
  553. switch wire {
  554. case WireBytes:
  555. buf, e := b.DecodeRawBytes(false)
  556. if e == nil {
  557. _, err = fmt.Fprintf(w, "%q", buf)
  558. } else {
  559. _, err = fmt.Fprintf(w, "/* %v */", e)
  560. }
  561. case WireFixed32:
  562. x, err = b.DecodeFixed32()
  563. err = writeUnknownInt(w, x, err)
  564. case WireFixed64:
  565. x, err = b.DecodeFixed64()
  566. err = writeUnknownInt(w, x, err)
  567. case WireStartGroup:
  568. err = w.WriteByte('{')
  569. w.indent()
  570. case WireVarint:
  571. x, err = b.DecodeVarint()
  572. err = writeUnknownInt(w, x, err)
  573. default:
  574. _, err = fmt.Fprintf(w, "/* unknown wire type %d */", wire)
  575. }
  576. if err != nil {
  577. return err
  578. }
  579. if err := w.WriteByte('\n'); err != nil {
  580. return err
  581. }
  582. }
  583. return nil
  584. }
  585. func writeUnknownInt(w *textWriter, x uint64, err error) error {
  586. if err == nil {
  587. _, err = fmt.Fprint(w, x)
  588. } else {
  589. _, err = fmt.Fprintf(w, "/* %v */", err)
  590. }
  591. return err
  592. }
  593. type int32Slice []int32
  594. func (s int32Slice) Len() int { return len(s) }
  595. func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] }
  596. func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  597. // writeExtensions writes all the extensions in pv.
  598. // pv is assumed to be a pointer to a protocol message struct that is extendable.
  599. func writeExtensions(w *textWriter, pv reflect.Value) error {
  600. emap := extensionMaps[pv.Type().Elem()]
  601. ep := pv.Interface().(extendableProto)
  602. // Order the extensions by ID.
  603. // This isn't strictly necessary, but it will give us
  604. // canonical output, which will also make testing easier.
  605. var m map[int32]Extension
  606. if em, ok := ep.(extensionsMap); ok {
  607. m = em.ExtensionMap()
  608. } else if em, ok := ep.(extensionsBytes); ok {
  609. eb := em.GetExtensions()
  610. var err error
  611. m, err = BytesToExtensionsMap(*eb)
  612. if err != nil {
  613. return err
  614. }
  615. }
  616. ids := make([]int32, 0, len(m))
  617. for id := range m {
  618. ids = append(ids, id)
  619. }
  620. sort.Sort(int32Slice(ids))
  621. for _, extNum := range ids {
  622. ext := m[extNum]
  623. var desc *ExtensionDesc
  624. if emap != nil {
  625. desc = emap[extNum]
  626. }
  627. if desc == nil {
  628. // Unknown extension.
  629. if err := writeUnknownStruct(w, ext.enc); err != nil {
  630. return err
  631. }
  632. continue
  633. }
  634. pb, err := GetExtension(ep, desc)
  635. if err != nil {
  636. return fmt.Errorf("failed getting extension: %v", err)
  637. }
  638. // Repeated extensions will appear as a slice.
  639. if !desc.repeated() {
  640. if err := writeExtension(w, desc.Name, pb); err != nil {
  641. return err
  642. }
  643. } else {
  644. v := reflect.ValueOf(pb)
  645. for i := 0; i < v.Len(); i++ {
  646. if err := writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil {
  647. return err
  648. }
  649. }
  650. }
  651. }
  652. return nil
  653. }
  654. func writeExtension(w *textWriter, name string, pb interface{}) error {
  655. if _, err := fmt.Fprintf(w, "[%s]:", name); err != nil {
  656. return err
  657. }
  658. if !w.compact {
  659. if err := w.WriteByte(' '); err != nil {
  660. return err
  661. }
  662. }
  663. if err := writeAny(w, reflect.ValueOf(pb), nil); err != nil {
  664. return err
  665. }
  666. if err := w.WriteByte('\n'); err != nil {
  667. return err
  668. }
  669. return nil
  670. }
  671. func (w *textWriter) writeIndent() {
  672. if !w.complete {
  673. return
  674. }
  675. remain := w.ind * 2
  676. for remain > 0 {
  677. n := remain
  678. if n > len(spaces) {
  679. n = len(spaces)
  680. }
  681. w.w.Write(spaces[:n])
  682. remain -= n
  683. }
  684. w.complete = false
  685. }
  686. // TextMarshaler is a configurable text format marshaler.
  687. type TextMarshaler struct {
  688. Compact bool // use compact text format (one line).
  689. }
  690. // Marshal writes a given protocol buffer in text format.
  691. // The only errors returned are from w.
  692. func (m *TextMarshaler) Marshal(w io.Writer, pb Message) error {
  693. val := reflect.ValueOf(pb)
  694. if pb == nil || val.IsNil() {
  695. w.Write([]byte("<nil>"))
  696. return nil
  697. }
  698. var bw *bufio.Writer
  699. ww, ok := w.(writer)
  700. if !ok {
  701. bw = bufio.NewWriter(w)
  702. ww = bw
  703. }
  704. aw := &textWriter{
  705. w: ww,
  706. complete: true,
  707. compact: m.Compact,
  708. }
  709. if tm, ok := pb.(encoding.TextMarshaler); ok {
  710. text, err := tm.MarshalText()
  711. if err != nil {
  712. return err
  713. }
  714. if _, err = aw.Write(text); err != nil {
  715. return err
  716. }
  717. if bw != nil {
  718. return bw.Flush()
  719. }
  720. return nil
  721. }
  722. // Dereference the received pointer so we don't have outer < and >.
  723. v := reflect.Indirect(val)
  724. if err := writeStruct(aw, v); err != nil {
  725. return err
  726. }
  727. if bw != nil {
  728. return bw.Flush()
  729. }
  730. return nil
  731. }
  732. // Text is the same as Marshal, but returns the string directly.
  733. func (m *TextMarshaler) Text(pb Message) string {
  734. var buf bytes.Buffer
  735. m.Marshal(&buf, pb)
  736. return buf.String()
  737. }
  738. var (
  739. defaultTextMarshaler = TextMarshaler{}
  740. compactTextMarshaler = TextMarshaler{Compact: true}
  741. )
  742. // TODO: consider removing some of the Marshal functions below.
  743. // MarshalText writes a given protocol buffer in text format.
  744. // The only errors returned are from w.
  745. func MarshalText(w io.Writer, pb Message) error { return defaultTextMarshaler.Marshal(w, pb) }
  746. // MarshalTextString is the same as MarshalText, but returns the string directly.
  747. func MarshalTextString(pb Message) string { return defaultTextMarshaler.Text(pb) }
  748. // CompactText writes a given protocol buffer in compact text format (one line).
  749. func CompactText(w io.Writer, pb Message) error { return compactTextMarshaler.Marshal(w, pb) }
  750. // CompactTextString is the same as CompactText, but returns the string directly.
  751. func CompactTextString(pb Message) string { return compactTextMarshaler.Text(pb) }