text.go 21 KB

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