text.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832
  1. // Copyright 2010 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package proto
  5. // Functions for writing the text protocol buffer format.
  6. import (
  7. "bufio"
  8. "bytes"
  9. "encoding"
  10. "errors"
  11. "fmt"
  12. "io"
  13. "log"
  14. "math"
  15. "reflect"
  16. "sort"
  17. "strings"
  18. protoV2 "google.golang.org/protobuf/proto"
  19. "google.golang.org/protobuf/reflect/protoreflect"
  20. )
  21. var (
  22. newline = []byte("\n")
  23. spaces = []byte(" ")
  24. endBraceNewline = []byte("}\n")
  25. backslashN = []byte{'\\', 'n'}
  26. backslashR = []byte{'\\', 'r'}
  27. backslashT = []byte{'\\', 't'}
  28. backslashDQ = []byte{'\\', '"'}
  29. backslashBS = []byte{'\\', '\\'}
  30. posInf = []byte("inf")
  31. negInf = []byte("-inf")
  32. nan = []byte("nan")
  33. )
  34. type writer interface {
  35. io.Writer
  36. WriteByte(byte) error
  37. }
  38. // textWriter is an io.Writer that tracks its indentation level.
  39. type textWriter struct {
  40. ind int
  41. complete bool // if the current position is a complete line
  42. compact bool // whether to write out as a one-liner
  43. w writer
  44. }
  45. func (w *textWriter) WriteString(s string) (n int, err error) {
  46. if !strings.Contains(s, "\n") {
  47. if !w.compact && w.complete {
  48. w.writeIndent()
  49. }
  50. w.complete = false
  51. return io.WriteString(w.w, s)
  52. }
  53. // WriteString is typically called without newlines, so this
  54. // codepath and its copy are rare. We copy to avoid
  55. // duplicating all of Write's logic here.
  56. return w.Write([]byte(s))
  57. }
  58. func (w *textWriter) Write(p []byte) (n int, err error) {
  59. newlines := bytes.Count(p, newline)
  60. if newlines == 0 {
  61. if !w.compact && w.complete {
  62. w.writeIndent()
  63. }
  64. n, err = w.w.Write(p)
  65. w.complete = false
  66. return n, err
  67. }
  68. frags := bytes.SplitN(p, newline, newlines+1)
  69. if w.compact {
  70. for i, frag := range frags {
  71. if i > 0 {
  72. if err := w.w.WriteByte(' '); err != nil {
  73. return n, err
  74. }
  75. n++
  76. }
  77. nn, err := w.w.Write(frag)
  78. n += nn
  79. if err != nil {
  80. return n, err
  81. }
  82. }
  83. return n, nil
  84. }
  85. for i, frag := range frags {
  86. if w.complete {
  87. w.writeIndent()
  88. }
  89. nn, err := w.w.Write(frag)
  90. n += nn
  91. if err != nil {
  92. return n, err
  93. }
  94. if i+1 < len(frags) {
  95. if err := w.w.WriteByte('\n'); err != nil {
  96. return n, err
  97. }
  98. n++
  99. }
  100. }
  101. w.complete = len(frags[len(frags)-1]) == 0
  102. return n, nil
  103. }
  104. func (w *textWriter) WriteByte(c byte) error {
  105. if w.compact && c == '\n' {
  106. c = ' '
  107. }
  108. if !w.compact && w.complete {
  109. w.writeIndent()
  110. }
  111. err := w.w.WriteByte(c)
  112. w.complete = c == '\n'
  113. return err
  114. }
  115. func (w *textWriter) indent() { w.ind++ }
  116. func (w *textWriter) unindent() {
  117. if w.ind == 0 {
  118. log.Print("proto: textWriter unindented too far")
  119. return
  120. }
  121. w.ind--
  122. }
  123. func writeName(w *textWriter, props *Properties) error {
  124. if _, err := w.WriteString(props.OrigName); err != nil {
  125. return err
  126. }
  127. if props.Wire != "group" {
  128. return w.WriteByte(':')
  129. }
  130. return nil
  131. }
  132. func requiresQuotes(u string) bool {
  133. // When type URL contains any characters except [0-9A-Za-z./\-]*, it must be quoted.
  134. for _, ch := range u {
  135. switch {
  136. case ch == '.' || ch == '/' || ch == '_':
  137. continue
  138. case '0' <= ch && ch <= '9':
  139. continue
  140. case 'A' <= ch && ch <= 'Z':
  141. continue
  142. case 'a' <= ch && ch <= 'z':
  143. continue
  144. default:
  145. return true
  146. }
  147. }
  148. return false
  149. }
  150. // isAny reports whether sv is a google.protobuf.Any message
  151. func isAny(sv reflect.Value) bool {
  152. switch m := sv.Addr().Interface().(type) {
  153. case interface{ XXX_WellKnownType() string }:
  154. return m.XXX_WellKnownType() == "Any"
  155. case protoV2.Message:
  156. return m.ProtoReflect().Descriptor().FullName() == "google.protobuf.Any"
  157. default:
  158. return false
  159. }
  160. }
  161. // writeProto3Any writes an expanded google.protobuf.Any message.
  162. //
  163. // It returns (false, nil) if sv value can't be unmarshaled (e.g. because
  164. // required messages are not linked in).
  165. //
  166. // It returns (true, error) when sv was written in expanded format or an error
  167. // was encountered.
  168. func (tm *textMarshaler) writeProto3Any(w *textWriter, sv reflect.Value) (bool, error) {
  169. turl := sv.FieldByName("TypeUrl")
  170. val := sv.FieldByName("Value")
  171. if !turl.IsValid() || !val.IsValid() {
  172. return true, errors.New("proto: invalid google.protobuf.Any message")
  173. }
  174. b, ok := val.Interface().([]byte)
  175. if !ok {
  176. return true, errors.New("proto: invalid google.protobuf.Any message")
  177. }
  178. parts := strings.Split(turl.String(), "/")
  179. mt := MessageType(parts[len(parts)-1])
  180. if mt == nil {
  181. return false, nil
  182. }
  183. m := reflect.New(mt.Elem())
  184. if err := Unmarshal(b, m.Interface().(Message)); err != nil {
  185. return false, nil
  186. }
  187. w.Write([]byte("["))
  188. u := turl.String()
  189. if requiresQuotes(u) {
  190. writeString(w, u)
  191. } else {
  192. w.Write([]byte(u))
  193. }
  194. if w.compact {
  195. w.Write([]byte("]:<"))
  196. } else {
  197. w.Write([]byte("]: <\n"))
  198. w.ind++
  199. }
  200. if err := tm.writeStruct(w, m.Elem()); err != nil {
  201. return true, err
  202. }
  203. if w.compact {
  204. w.Write([]byte("> "))
  205. } else {
  206. w.ind--
  207. w.Write([]byte(">\n"))
  208. }
  209. return true, nil
  210. }
  211. func (tm *textMarshaler) writeStruct(w *textWriter, sv reflect.Value) error {
  212. if tm.ExpandAny && isAny(sv) {
  213. if canExpand, err := tm.writeProto3Any(w, sv); canExpand {
  214. return err
  215. }
  216. }
  217. st := sv.Type()
  218. sprops := GetProperties(st)
  219. for i := 0; i < sv.NumField(); i++ {
  220. fv := sv.Field(i)
  221. props := sprops.Prop[i]
  222. f := st.Field(i)
  223. if strings.HasPrefix(f.Name, "XXX_") || f.PkgPath != "" {
  224. continue
  225. }
  226. if fv.Kind() == reflect.Ptr && fv.IsNil() {
  227. // Field not filled in. This could be an optional field or
  228. // a required field that wasn't filled in. Either way, there
  229. // isn't anything we can show for it.
  230. continue
  231. }
  232. if fv.Kind() == reflect.Slice && fv.IsNil() {
  233. // Repeated field that is empty, or a bytes field that is unused.
  234. continue
  235. }
  236. if props.Repeated && fv.Kind() == reflect.Slice {
  237. // Repeated field.
  238. for j := 0; j < fv.Len(); j++ {
  239. if err := writeName(w, props); err != nil {
  240. return err
  241. }
  242. if !w.compact {
  243. if err := w.WriteByte(' '); err != nil {
  244. return err
  245. }
  246. }
  247. v := fv.Index(j)
  248. if v.Kind() == reflect.Ptr && v.IsNil() {
  249. // A nil message in a repeated field is not valid,
  250. // but we can handle that more gracefully than panicking.
  251. if _, err := w.Write([]byte("<nil>\n")); err != nil {
  252. return err
  253. }
  254. continue
  255. }
  256. if err := tm.writeAny(w, v, props); err != nil {
  257. return err
  258. }
  259. if err := w.WriteByte('\n'); err != nil {
  260. return err
  261. }
  262. }
  263. continue
  264. }
  265. if fv.Kind() == reflect.Map {
  266. // Map fields are rendered as a repeated struct with key/value fields.
  267. keys := fv.MapKeys()
  268. sort.Sort(mapKeys(keys))
  269. for _, key := range keys {
  270. val := fv.MapIndex(key)
  271. if err := writeName(w, props); err != nil {
  272. return err
  273. }
  274. if !w.compact {
  275. if err := w.WriteByte(' '); err != nil {
  276. return err
  277. }
  278. }
  279. // open struct
  280. if err := w.WriteByte('<'); err != nil {
  281. return err
  282. }
  283. if !w.compact {
  284. if err := w.WriteByte('\n'); err != nil {
  285. return err
  286. }
  287. }
  288. w.indent()
  289. // key
  290. if _, err := w.WriteString("key:"); err != nil {
  291. return err
  292. }
  293. if !w.compact {
  294. if err := w.WriteByte(' '); err != nil {
  295. return err
  296. }
  297. }
  298. if err := tm.writeAny(w, key, props.MapKeyProp); err != nil {
  299. return err
  300. }
  301. if err := w.WriteByte('\n'); err != nil {
  302. return err
  303. }
  304. // nil values aren't legal, but we can avoid panicking because of them.
  305. if val.Kind() != reflect.Ptr || !val.IsNil() {
  306. // value
  307. if _, err := w.WriteString("value:"); err != nil {
  308. return err
  309. }
  310. if !w.compact {
  311. if err := w.WriteByte(' '); err != nil {
  312. return err
  313. }
  314. }
  315. if err := tm.writeAny(w, val, props.MapValProp); err != nil {
  316. return err
  317. }
  318. if err := w.WriteByte('\n'); err != nil {
  319. return err
  320. }
  321. }
  322. // close struct
  323. w.unindent()
  324. if err := w.WriteByte('>'); err != nil {
  325. return err
  326. }
  327. if err := w.WriteByte('\n'); err != nil {
  328. return err
  329. }
  330. }
  331. continue
  332. }
  333. if props.Proto3 && fv.Kind() == reflect.Slice && fv.Len() == 0 {
  334. // empty bytes field
  335. continue
  336. }
  337. if fv.Kind() != reflect.Ptr && fv.Kind() != reflect.Slice {
  338. // proto3 non-repeated scalar field; skip if zero value
  339. if isProto3Zero(fv) {
  340. continue
  341. }
  342. }
  343. if fv.Kind() == reflect.Interface {
  344. // Check if it is a oneof.
  345. if st.Field(i).Tag.Get("protobuf_oneof") != "" {
  346. // fv is nil, or holds a pointer to generated struct.
  347. // That generated struct has exactly one field,
  348. // which has a protobuf struct tag.
  349. if fv.IsNil() {
  350. continue
  351. }
  352. inner := fv.Elem().Elem() // interface -> *T -> T
  353. tag := inner.Type().Field(0).Tag.Get("protobuf")
  354. props = new(Properties) // Overwrite the outer props var, but not its pointee.
  355. props.Parse(tag)
  356. // Write the value in the oneof, not the oneof itself.
  357. fv = inner.Field(0)
  358. // Special case to cope with malformed messages gracefully:
  359. // If the value in the oneof is a nil pointer, don't panic
  360. // in writeAny.
  361. if fv.Kind() == reflect.Ptr && fv.IsNil() {
  362. // Use errors.New so writeAny won't render quotes.
  363. msg := errors.New("/* nil */")
  364. fv = reflect.ValueOf(&msg).Elem()
  365. }
  366. }
  367. }
  368. if err := writeName(w, props); err != nil {
  369. return err
  370. }
  371. if !w.compact {
  372. if err := w.WriteByte(' '); err != nil {
  373. return err
  374. }
  375. }
  376. // Enums have a String method, so writeAny will work fine.
  377. if err := tm.writeAny(w, fv, props); err != nil {
  378. return err
  379. }
  380. if err := w.WriteByte('\n'); err != nil {
  381. return err
  382. }
  383. }
  384. if fv := unknownFieldsValue(sv); !fv.IsNil() {
  385. if err := writeUnknownStruct(w, fv.Interface().([]byte)); err != nil {
  386. return err
  387. }
  388. }
  389. // Extensions (the XXX_extensions field).
  390. pv := sv.Addr()
  391. if _, err := extendable(pv.Interface()); err == nil {
  392. if err := tm.writeExtensions(w, pv); err != nil {
  393. return err
  394. }
  395. }
  396. return nil
  397. }
  398. // writeAny writes an arbitrary field.
  399. func (tm *textMarshaler) writeAny(w *textWriter, v reflect.Value, props *Properties) error {
  400. v = reflect.Indirect(v)
  401. // Floats have special cases.
  402. if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 {
  403. x := v.Float()
  404. var b []byte
  405. switch {
  406. case math.IsInf(x, 1):
  407. b = posInf
  408. case math.IsInf(x, -1):
  409. b = negInf
  410. case math.IsNaN(x):
  411. b = nan
  412. }
  413. if b != nil {
  414. _, err := w.Write(b)
  415. return err
  416. }
  417. // Other values are handled below.
  418. }
  419. // We don't attempt to serialise every possible value type; only those
  420. // that can occur in protocol buffers.
  421. switch v.Kind() {
  422. case reflect.Slice:
  423. // Should only be a []byte; repeated fields are handled in writeStruct.
  424. if err := writeString(w, string(v.Bytes())); err != nil {
  425. return err
  426. }
  427. case reflect.String:
  428. if err := writeString(w, v.String()); err != nil {
  429. return err
  430. }
  431. case reflect.Struct:
  432. // Required/optional group/message.
  433. var bra, ket byte = '<', '>'
  434. if props != nil && props.Wire == "group" {
  435. bra, ket = '{', '}'
  436. }
  437. if err := w.WriteByte(bra); err != nil {
  438. return err
  439. }
  440. if !w.compact {
  441. if err := w.WriteByte('\n'); err != nil {
  442. return err
  443. }
  444. }
  445. w.indent()
  446. if v.CanAddr() {
  447. // Calling v.Interface on a struct causes the reflect package to
  448. // copy the entire struct. This is racy with the new Marshaler
  449. // since we atomically update the XXX_sizecache.
  450. //
  451. // Thus, we retrieve a pointer to the struct if possible to avoid
  452. // a race since v.Interface on the pointer doesn't copy the struct.
  453. //
  454. // If v is not addressable, then we are not worried about a race
  455. // since it implies that the binary Marshaler cannot possibly be
  456. // mutating this value.
  457. v = v.Addr()
  458. }
  459. if etm, ok := v.Interface().(encoding.TextMarshaler); ok {
  460. text, err := etm.MarshalText()
  461. if err != nil {
  462. return err
  463. }
  464. if _, err = w.Write(text); err != nil {
  465. return err
  466. }
  467. } else {
  468. if v.Kind() == reflect.Ptr {
  469. v = v.Elem()
  470. }
  471. if err := tm.writeStruct(w, v); err != nil {
  472. return err
  473. }
  474. }
  475. w.unindent()
  476. if err := w.WriteByte(ket); err != nil {
  477. return err
  478. }
  479. default:
  480. _, err := fmt.Fprint(w, v.Interface())
  481. return err
  482. }
  483. return nil
  484. }
  485. // equivalent to C's isprint.
  486. func isprint(c byte) bool {
  487. return c >= 0x20 && c < 0x7f
  488. }
  489. // writeString writes a string in the protocol buffer text format.
  490. // It is similar to strconv.Quote except we don't use Go escape sequences,
  491. // we treat the string as a byte sequence, and we use octal escapes.
  492. // These differences are to maintain interoperability with the other
  493. // languages' implementations of the text format.
  494. func writeString(w *textWriter, s string) error {
  495. // use WriteByte here to get any needed indent
  496. if err := w.WriteByte('"'); err != nil {
  497. return err
  498. }
  499. // Loop over the bytes, not the runes.
  500. for i := 0; i < len(s); i++ {
  501. var err error
  502. // Divergence from C++: we don't escape apostrophes.
  503. // There's no need to escape them, and the C++ parser
  504. // copes with a naked apostrophe.
  505. switch c := s[i]; c {
  506. case '\n':
  507. _, err = w.w.Write(backslashN)
  508. case '\r':
  509. _, err = w.w.Write(backslashR)
  510. case '\t':
  511. _, err = w.w.Write(backslashT)
  512. case '"':
  513. _, err = w.w.Write(backslashDQ)
  514. case '\\':
  515. _, err = w.w.Write(backslashBS)
  516. default:
  517. if isprint(c) {
  518. err = w.w.WriteByte(c)
  519. } else {
  520. _, err = fmt.Fprintf(w.w, "\\%03o", c)
  521. }
  522. }
  523. if err != nil {
  524. return err
  525. }
  526. }
  527. return w.WriteByte('"')
  528. }
  529. func writeUnknownStruct(w *textWriter, data []byte) (err error) {
  530. if !w.compact {
  531. if _, err := fmt.Fprintf(w, "/* %d unknown bytes */\n", len(data)); err != nil {
  532. return err
  533. }
  534. }
  535. b := NewBuffer(data)
  536. for b.index < len(b.buf) {
  537. x, err := b.DecodeVarint()
  538. if err != nil {
  539. _, err := fmt.Fprintf(w, "/* %v */\n", err)
  540. return err
  541. }
  542. wire, tag := x&7, x>>3
  543. if wire == WireEndGroup {
  544. w.unindent()
  545. if _, err := w.Write(endBraceNewline); err != nil {
  546. return err
  547. }
  548. continue
  549. }
  550. if _, err := fmt.Fprint(w, tag); err != nil {
  551. return err
  552. }
  553. if wire != WireStartGroup {
  554. if err := w.WriteByte(':'); err != nil {
  555. return err
  556. }
  557. }
  558. if !w.compact || wire == WireStartGroup {
  559. if err := w.WriteByte(' '); err != nil {
  560. return err
  561. }
  562. }
  563. switch wire {
  564. case WireBytes:
  565. buf, e := b.DecodeRawBytes(false)
  566. if e == nil {
  567. _, err = fmt.Fprintf(w, "%q", buf)
  568. } else {
  569. _, err = fmt.Fprintf(w, "/* %v */", e)
  570. }
  571. case WireFixed32:
  572. x, err = b.DecodeFixed32()
  573. err = writeUnknownInt(w, x, err)
  574. case WireFixed64:
  575. x, err = b.DecodeFixed64()
  576. err = writeUnknownInt(w, x, err)
  577. case WireStartGroup:
  578. err = w.WriteByte('{')
  579. w.indent()
  580. case WireVarint:
  581. x, err = b.DecodeVarint()
  582. err = writeUnknownInt(w, x, err)
  583. default:
  584. _, err = fmt.Fprintf(w, "/* unknown wire type %d */", wire)
  585. }
  586. if err != nil {
  587. return err
  588. }
  589. if err = w.WriteByte('\n'); err != nil {
  590. return err
  591. }
  592. }
  593. return nil
  594. }
  595. func writeUnknownInt(w *textWriter, x uint64, err error) error {
  596. if err == nil {
  597. _, err = fmt.Fprint(w, x)
  598. } else {
  599. _, err = fmt.Fprintf(w, "/* %v */", err)
  600. }
  601. return err
  602. }
  603. type fieldNumSlice []protoreflect.FieldNumber
  604. func (s fieldNumSlice) Len() int { return len(s) }
  605. func (s fieldNumSlice) Less(i, j int) bool { return s[i] < s[j] }
  606. func (s fieldNumSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  607. // writeExtensions writes all the extensions in pv.
  608. // pv is assumed to be a pointer to a protocol message struct that is extendable.
  609. func (tm *textMarshaler) writeExtensions(w *textWriter, pv reflect.Value) error {
  610. emap := RegisteredExtensions(pv.Interface().(Message))
  611. ep, _ := extendable(pv.Interface())
  612. // Order the extensions by ID.
  613. // This isn't strictly necessary, but it will give us
  614. // canonical output, which will also make testing easier.
  615. if ep == nil {
  616. return nil
  617. }
  618. ids := make([]protoreflect.FieldNumber, 0, ep.Len())
  619. ep.Range(func(id protoreflect.FieldNumber, _ Extension) bool {
  620. ids = append(ids, id)
  621. return true
  622. })
  623. sort.Sort(fieldNumSlice(ids))
  624. for _, extNum := range ids {
  625. var desc *ExtensionDesc
  626. if emap != nil {
  627. desc = emap[int32(extNum)]
  628. }
  629. if desc == nil {
  630. continue
  631. }
  632. pb, err := GetExtension(pv.Interface().(Message), desc)
  633. if err != nil {
  634. return fmt.Errorf("failed getting extension: %v", err)
  635. }
  636. name := desc.Name
  637. if strings.HasSuffix(name, ".message_set_extension") && isMessageSet(pv.Type().Elem()) {
  638. name = strings.TrimSuffix(name, ".message_set_extension")
  639. }
  640. // Repeated extensions will appear as a slice.
  641. if !isRepeatedExtension(desc) {
  642. if err := tm.writeExtension(w, name, pb); err != nil {
  643. return err
  644. }
  645. } else {
  646. v := reflect.ValueOf(pb)
  647. for i := 0; i < v.Len(); i++ {
  648. if err := tm.writeExtension(w, name, v.Index(i).Interface()); err != nil {
  649. return err
  650. }
  651. }
  652. }
  653. }
  654. return nil
  655. }
  656. func (tm *textMarshaler) writeExtension(w *textWriter, name string, pb interface{}) error {
  657. if _, err := fmt.Fprintf(w, "[%s]:", name); err != nil {
  658. return err
  659. }
  660. if !w.compact {
  661. if err := w.WriteByte(' '); err != nil {
  662. return err
  663. }
  664. }
  665. if err := tm.writeAny(w, reflect.ValueOf(pb), nil); err != nil {
  666. return err
  667. }
  668. if err := w.WriteByte('\n'); err != nil {
  669. return err
  670. }
  671. return nil
  672. }
  673. func (w *textWriter) writeIndent() {
  674. if !w.complete {
  675. return
  676. }
  677. remain := w.ind * 2
  678. for remain > 0 {
  679. n := remain
  680. if n > len(spaces) {
  681. n = len(spaces)
  682. }
  683. w.w.Write(spaces[:n])
  684. remain -= n
  685. }
  686. w.complete = false
  687. }
  688. // textMarshaler is a configurable text format marshaler.
  689. type textMarshaler struct {
  690. Compact bool // use compact text format (one line).
  691. ExpandAny bool // expand google.protobuf.Any messages of known types
  692. }
  693. // Marshal writes a given protocol buffer in text format.
  694. // The only errors returned are from w.
  695. func (tm *textMarshaler) Marshal(w io.Writer, pb Message) error {
  696. val := reflect.ValueOf(pb)
  697. if pb == nil || val.IsNil() {
  698. w.Write([]byte("<nil>"))
  699. return nil
  700. }
  701. var bw *bufio.Writer
  702. ww, ok := w.(writer)
  703. if !ok {
  704. bw = bufio.NewWriter(w)
  705. ww = bw
  706. }
  707. aw := &textWriter{
  708. w: ww,
  709. complete: true,
  710. compact: tm.Compact,
  711. }
  712. if etm, ok := pb.(encoding.TextMarshaler); ok {
  713. text, err := etm.MarshalText()
  714. if err != nil {
  715. return err
  716. }
  717. if _, err = aw.Write(text); err != nil {
  718. return err
  719. }
  720. if bw != nil {
  721. return bw.Flush()
  722. }
  723. return nil
  724. }
  725. // Dereference the received pointer so we don't have outer < and >.
  726. v := reflect.Indirect(val)
  727. if err := tm.writeStruct(aw, v); err != nil {
  728. return err
  729. }
  730. if bw != nil {
  731. return bw.Flush()
  732. }
  733. return nil
  734. }
  735. // Text is the same as Marshal, but returns the string directly.
  736. func (tm *textMarshaler) Text(pb Message) string {
  737. var buf bytes.Buffer
  738. tm.Marshal(&buf, pb)
  739. return buf.String()
  740. }
  741. var (
  742. defaultTextMarshaler = textMarshaler{}
  743. compactTextMarshaler = textMarshaler{Compact: true}
  744. )
  745. // TODO: consider removing some of the Marshal functions below.
  746. // MarshalText writes a given protocol buffer in text format.
  747. // The only errors returned are from w.
  748. func MarshalText(w io.Writer, pb Message) error {
  749. if marshalTextAlt != nil {
  750. return marshalTextAlt(w, pb)
  751. }
  752. return defaultTextMarshaler.Marshal(w, pb)
  753. }
  754. // MarshalTextString is the same as MarshalText, but returns the string directly.
  755. func MarshalTextString(pb Message) string {
  756. if marshalTextStringAlt != nil {
  757. return marshalTextStringAlt(pb)
  758. }
  759. return defaultTextMarshaler.Text(pb)
  760. }
  761. // CompactText writes a given protocol buffer in compact text format (one line).
  762. func CompactText(w io.Writer, pb Message) error {
  763. if compactTextAlt != nil {
  764. return compactTextAlt(w, pb)
  765. }
  766. return compactTextMarshaler.Marshal(w, pb)
  767. }
  768. // CompactTextString is the same as CompactText, but returns the string directly.
  769. func CompactTextString(pb Message) string {
  770. if compactTextStringAlt != nil {
  771. return compactTextStringAlt(pb)
  772. }
  773. return compactTextMarshaler.Text(pb)
  774. }