pack.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  1. // Copyright 2018 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 pack enables manual encoding and decoding of protobuf wire data.
  5. //
  6. // This package is intended for use in debugging and/or creation of test data.
  7. // Proper usage of this package requires knowledge of the wire format.
  8. //
  9. // See https://developers.google.com/protocol-buffers/docs/encoding.
  10. package pack
  11. import (
  12. "fmt"
  13. "io"
  14. "math"
  15. "path"
  16. "reflect"
  17. "strconv"
  18. "strings"
  19. "unicode"
  20. "unicode/utf8"
  21. "google.golang.org/protobuf/internal/encoding/wire"
  22. "google.golang.org/protobuf/reflect/protoreflect"
  23. )
  24. // Number is the field number; aliased from the wire package for convenience.
  25. type Number = wire.Number
  26. // Number type constants; copied from the wire package for convenience.
  27. const (
  28. MinValidNumber Number = wire.MinValidNumber
  29. FirstReservedNumber Number = wire.FirstReservedNumber
  30. LastReservedNumber Number = wire.LastReservedNumber
  31. MaxValidNumber Number = wire.MaxValidNumber
  32. )
  33. // Type is the wire type; aliased from the wire package for convenience.
  34. type Type = wire.Type
  35. // Wire type constants; copied from the wire package for convenience.
  36. const (
  37. VarintType Type = wire.VarintType
  38. Fixed32Type Type = wire.Fixed32Type
  39. Fixed64Type Type = wire.Fixed64Type
  40. BytesType Type = wire.BytesType
  41. StartGroupType Type = wire.StartGroupType
  42. EndGroupType Type = wire.EndGroupType
  43. )
  44. type (
  45. // Token is any other type (e.g., Message, Tag, Varint, Float32, etc).
  46. Token token
  47. // Message is an ordered sequence of Tokens, where certain tokens may
  48. // contain other tokens. It is functionally a concrete syntax tree that
  49. // losslessly represents any arbitrary wire data (including invalid input).
  50. Message []Token
  51. // Tag is a tuple of the field number and the wire type.
  52. Tag struct {
  53. Number Number
  54. Type Type
  55. }
  56. // Bool is a boolean.
  57. Bool bool
  58. // Varint is a signed varint using 64-bit two's complement encoding.
  59. Varint int64
  60. // Svarint is a signed varint using zig-zag encoding.
  61. Svarint int64
  62. // Uvarint is a unsigned varint.
  63. Uvarint uint64
  64. // Int32 is a signed 32-bit fixed-width integer.
  65. Int32 int32
  66. // Uint32 is an unsigned 32-bit fixed-width integer.
  67. Uint32 uint32
  68. // Float32 is a 32-bit fixed-width floating point number.
  69. Float32 float32
  70. // Int64 is a signed 64-bit fixed-width integer.
  71. Int64 int64
  72. // Uint64 is an unsigned 64-bit fixed-width integer.
  73. Uint64 uint64
  74. // Float64 is a 64-bit fixed-width floating point number.
  75. Float64 float64
  76. // String is a length-prefixed string.
  77. String string
  78. // Bytes is a length-prefixed bytes.
  79. Bytes []byte
  80. // LengthPrefix is a length-prefixed message.
  81. LengthPrefix Message
  82. // Denormalized is a denormalized varint value, where a varint is encoded
  83. // using more bytes than is strictly necessary. The number of extra bytes
  84. // alone is sufficient to losslessly represent the denormalized varint.
  85. //
  86. // The value may be one of Tag, Bool, Varint, Svarint, or Uvarint,
  87. // where the varint representation of each token is denormalized.
  88. //
  89. // Alternatively, the value may be one of String, Bytes, or LengthPrefix,
  90. // where the varint representation of the length-prefix is denormalized.
  91. Denormalized struct {
  92. Count uint // number of extra bytes
  93. Value Token
  94. }
  95. // Raw are bytes directly appended to output.
  96. Raw []byte
  97. )
  98. type token interface {
  99. isToken()
  100. }
  101. func (Message) isToken() {}
  102. func (Tag) isToken() {}
  103. func (Bool) isToken() {}
  104. func (Varint) isToken() {}
  105. func (Svarint) isToken() {}
  106. func (Uvarint) isToken() {}
  107. func (Int32) isToken() {}
  108. func (Uint32) isToken() {}
  109. func (Float32) isToken() {}
  110. func (Int64) isToken() {}
  111. func (Uint64) isToken() {}
  112. func (Float64) isToken() {}
  113. func (String) isToken() {}
  114. func (Bytes) isToken() {}
  115. func (LengthPrefix) isToken() {}
  116. func (Denormalized) isToken() {}
  117. func (Raw) isToken() {}
  118. // Size reports the size in bytes of the marshaled message.
  119. func (m Message) Size() int {
  120. var n int
  121. for _, v := range m {
  122. switch v := v.(type) {
  123. case Message:
  124. n += v.Size()
  125. case Tag:
  126. n += wire.SizeTag(v.Number)
  127. case Bool:
  128. n += wire.SizeVarint(wire.EncodeBool(false))
  129. case Varint:
  130. n += wire.SizeVarint(uint64(v))
  131. case Svarint:
  132. n += wire.SizeVarint(wire.EncodeZigZag(int64(v)))
  133. case Uvarint:
  134. n += wire.SizeVarint(uint64(v))
  135. case Int32, Uint32, Float32:
  136. n += wire.SizeFixed32()
  137. case Int64, Uint64, Float64:
  138. n += wire.SizeFixed64()
  139. case String:
  140. n += wire.SizeBytes(len(v))
  141. case Bytes:
  142. n += wire.SizeBytes(len(v))
  143. case LengthPrefix:
  144. n += wire.SizeBytes(Message(v).Size())
  145. case Denormalized:
  146. n += int(v.Count) + Message{v.Value}.Size()
  147. case Raw:
  148. n += len(v)
  149. default:
  150. panic(fmt.Sprintf("unknown type: %T", v))
  151. }
  152. }
  153. return n
  154. }
  155. // Message encodes a syntax tree into the protobuf wire format.
  156. //
  157. // Example message definition:
  158. // message MyMessage {
  159. // string field1 = 1;
  160. // int64 field2 = 2;
  161. // repeated float32 field3 = 3;
  162. // }
  163. //
  164. // Example encoded message:
  165. // b := Message{
  166. // Tag{1, BytesType}, String("Hello, world!"),
  167. // Tag{2, VarintType}, Varint(-10),
  168. // Tag{3, BytesType}, LengthPrefix{
  169. // Float32(1.1), Float32(2.2), Float32(3.3),
  170. // },
  171. // }.Marshal()
  172. //
  173. // Resulting wire data:
  174. // 0x0000 0a 0d 48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21 10 |..Hello, world!.|
  175. // 0x0010 f6 ff ff ff ff ff ff ff ff 01 1a 0c cd cc 8c 3f |...............?|
  176. // 0x0020 cd cc 0c 40 33 33 53 40 |...@33S@|
  177. func (m Message) Marshal() []byte {
  178. var out []byte
  179. for _, v := range m {
  180. switch v := v.(type) {
  181. case Message:
  182. out = append(out, v.Marshal()...)
  183. case Tag:
  184. out = wire.AppendTag(out, v.Number, v.Type)
  185. case Bool:
  186. out = wire.AppendVarint(out, wire.EncodeBool(bool(v)))
  187. case Varint:
  188. out = wire.AppendVarint(out, uint64(v))
  189. case Svarint:
  190. out = wire.AppendVarint(out, wire.EncodeZigZag(int64(v)))
  191. case Uvarint:
  192. out = wire.AppendVarint(out, uint64(v))
  193. case Int32:
  194. out = wire.AppendFixed32(out, uint32(v))
  195. case Uint32:
  196. out = wire.AppendFixed32(out, uint32(v))
  197. case Float32:
  198. out = wire.AppendFixed32(out, math.Float32bits(float32(v)))
  199. case Int64:
  200. out = wire.AppendFixed64(out, uint64(v))
  201. case Uint64:
  202. out = wire.AppendFixed64(out, uint64(v))
  203. case Float64:
  204. out = wire.AppendFixed64(out, math.Float64bits(float64(v)))
  205. case String:
  206. out = wire.AppendBytes(out, []byte(v))
  207. case Bytes:
  208. out = wire.AppendBytes(out, []byte(v))
  209. case LengthPrefix:
  210. out = wire.AppendBytes(out, Message(v).Marshal())
  211. case Denormalized:
  212. b := Message{v.Value}.Marshal()
  213. _, n := wire.ConsumeVarint(b)
  214. out = append(out, b[:n]...)
  215. for i := uint(0); i < v.Count; i++ {
  216. out[len(out)-1] |= 0x80 // set continuation bit on previous
  217. out = append(out, 0)
  218. }
  219. out = append(out, b[n:]...)
  220. case Raw:
  221. return append(out, v...)
  222. default:
  223. panic(fmt.Sprintf("unknown type: %T", v))
  224. }
  225. }
  226. return out
  227. }
  228. // Unmarshal parses the input protobuf wire data as a syntax tree.
  229. // Any parsing error results in the remainder of the input being
  230. // concatenated to the message as a Raw type.
  231. //
  232. // Each tag (a tuple of the field number and wire type) encountered is
  233. // inserted into the syntax tree as a Tag.
  234. //
  235. // The contents of each wire type is mapped to the following Go types:
  236. // VarintType => Uvarint
  237. // Fixed32Type => Uint32
  238. // Fixed64Type => Uint64
  239. // BytesType => Bytes
  240. // GroupType => Message
  241. //
  242. // Since the wire format is not self-describing, this function cannot parse
  243. // sub-messages and will leave them as the Bytes type. Further manual parsing
  244. // can be performed as such:
  245. // var m, m1, m2 Message
  246. // m.Unmarshal(b)
  247. // m1.Unmarshal(m[3].(Bytes))
  248. // m[3] = LengthPrefix(m1)
  249. // m2.Unmarshal(m[3].(LengthPrefix)[1].(Bytes))
  250. // m[3].(LengthPrefix)[1] = LengthPrefix(m2)
  251. //
  252. // Unmarshal is useful for debugging the protobuf wire format.
  253. func (m *Message) Unmarshal(in []byte) {
  254. m.UnmarshalDescriptor(in, nil)
  255. }
  256. // UnmarshalDescriptor parses the input protobuf wire data as a syntax tree
  257. // using the provided message descriptor for more accurate parsing of fields.
  258. // It operates like Unmarshal, but may use a wider range of Go types to
  259. // represent the wire data.
  260. //
  261. // The contents of each wire type is mapped to one of the following Go types:
  262. // VarintType => Bool, Varint, Svarint, Uvarint
  263. // Fixed32Type => Int32, Uint32, Float32
  264. // Fixed64Type => Uint32, Uint64, Float64
  265. // BytesType => String, Bytes, LengthPrefix
  266. // GroupType => Message
  267. //
  268. // If the field is unknown, it uses the same mapping as Unmarshal.
  269. // Known sub-messages are parsed as a Message and packed repeated fields are
  270. // parsed as a LengthPrefix.
  271. func (m *Message) UnmarshalDescriptor(in []byte, desc protoreflect.MessageDescriptor) {
  272. p := parser{in: in, out: *m}
  273. p.parseMessage(desc, false)
  274. *m = p.out
  275. }
  276. type parser struct {
  277. in []byte
  278. out []Token
  279. }
  280. func (p *parser) parseMessage(msgDesc protoreflect.MessageDescriptor, group bool) {
  281. for len(p.in) > 0 {
  282. v, n := wire.ConsumeVarint(p.in)
  283. num, typ := wire.DecodeTag(v)
  284. if n < 0 || num < 0 || v > math.MaxUint32 {
  285. p.out, p.in = append(p.out, Raw(p.in)), nil
  286. return
  287. }
  288. if typ == EndGroupType && group {
  289. return // if inside a group, then stop
  290. }
  291. p.out, p.in = append(p.out, Tag{num, typ}), p.in[n:]
  292. if m := n - wire.SizeVarint(v); m > 0 {
  293. p.out[len(p.out)-1] = Denormalized{uint(m), p.out[len(p.out)-1]}
  294. }
  295. // If descriptor is available, use it for more accurate parsing.
  296. var isPacked bool
  297. var kind protoreflect.Kind
  298. var subDesc protoreflect.MessageDescriptor
  299. if msgDesc != nil && !msgDesc.IsPlaceholder() {
  300. if fieldDesc := msgDesc.Fields().ByNumber(num); fieldDesc != nil {
  301. isPacked = fieldDesc.IsPacked()
  302. kind = fieldDesc.Kind()
  303. switch kind {
  304. case protoreflect.MessageKind, protoreflect.GroupKind:
  305. subDesc = fieldDesc.Message()
  306. if subDesc == nil || subDesc.IsPlaceholder() {
  307. kind = 0
  308. }
  309. }
  310. }
  311. }
  312. switch typ {
  313. case VarintType:
  314. p.parseVarint(kind)
  315. case Fixed32Type:
  316. p.parseFixed32(kind)
  317. case Fixed64Type:
  318. p.parseFixed64(kind)
  319. case BytesType:
  320. p.parseBytes(isPacked, kind, subDesc)
  321. case StartGroupType:
  322. p.parseGroup(subDesc)
  323. case EndGroupType:
  324. // Handled above.
  325. default:
  326. p.out, p.in = append(p.out, Raw(p.in)), nil
  327. }
  328. }
  329. }
  330. func (p *parser) parseVarint(kind protoreflect.Kind) {
  331. v, n := wire.ConsumeVarint(p.in)
  332. if n < 0 {
  333. p.out, p.in = append(p.out, Raw(p.in)), nil
  334. return
  335. }
  336. switch kind {
  337. case protoreflect.BoolKind:
  338. switch v {
  339. case 0:
  340. p.out, p.in = append(p.out, Bool(false)), p.in[n:]
  341. case 1:
  342. p.out, p.in = append(p.out, Bool(true)), p.in[n:]
  343. default:
  344. p.out, p.in = append(p.out, Uvarint(v)), p.in[n:]
  345. }
  346. case protoreflect.Int32Kind, protoreflect.Int64Kind:
  347. p.out, p.in = append(p.out, Varint(v)), p.in[n:]
  348. case protoreflect.Sint32Kind, protoreflect.Sint64Kind:
  349. p.out, p.in = append(p.out, Svarint(wire.DecodeZigZag(v))), p.in[n:]
  350. default:
  351. p.out, p.in = append(p.out, Uvarint(v)), p.in[n:]
  352. }
  353. if m := n - wire.SizeVarint(v); m > 0 {
  354. p.out[len(p.out)-1] = Denormalized{uint(m), p.out[len(p.out)-1]}
  355. }
  356. }
  357. func (p *parser) parseFixed32(kind protoreflect.Kind) {
  358. v, n := wire.ConsumeFixed32(p.in)
  359. if n < 0 {
  360. p.out, p.in = append(p.out, Raw(p.in)), nil
  361. return
  362. }
  363. switch kind {
  364. case protoreflect.FloatKind:
  365. p.out, p.in = append(p.out, Float32(math.Float32frombits(v))), p.in[n:]
  366. case protoreflect.Sfixed32Kind:
  367. p.out, p.in = append(p.out, Int32(v)), p.in[n:]
  368. default:
  369. p.out, p.in = append(p.out, Uint32(v)), p.in[n:]
  370. }
  371. }
  372. func (p *parser) parseFixed64(kind protoreflect.Kind) {
  373. v, n := wire.ConsumeFixed64(p.in)
  374. if n < 0 {
  375. p.out, p.in = append(p.out, Raw(p.in)), nil
  376. return
  377. }
  378. switch kind {
  379. case protoreflect.DoubleKind:
  380. p.out, p.in = append(p.out, Float64(math.Float64frombits(v))), p.in[n:]
  381. case protoreflect.Sfixed64Kind:
  382. p.out, p.in = append(p.out, Int64(v)), p.in[n:]
  383. default:
  384. p.out, p.in = append(p.out, Uint64(v)), p.in[n:]
  385. }
  386. }
  387. func (p *parser) parseBytes(isPacked bool, kind protoreflect.Kind, desc protoreflect.MessageDescriptor) {
  388. v, n := wire.ConsumeVarint(p.in)
  389. if n < 0 {
  390. p.out, p.in = append(p.out, Raw(p.in)), nil
  391. return
  392. }
  393. p.out, p.in = append(p.out, Uvarint(v)), p.in[n:]
  394. if m := n - wire.SizeVarint(v); m > 0 {
  395. p.out[len(p.out)-1] = Denormalized{uint(m), p.out[len(p.out)-1]}
  396. }
  397. if v > uint64(len(p.in)) {
  398. p.out, p.in = append(p.out, Raw(p.in)), nil
  399. return
  400. }
  401. p.out = p.out[:len(p.out)-1] // subsequent tokens contain prefix-length
  402. if isPacked {
  403. p.parsePacked(int(v), kind)
  404. } else {
  405. switch kind {
  406. case protoreflect.MessageKind:
  407. p2 := parser{in: p.in[:v]}
  408. p2.parseMessage(desc, false)
  409. p.out, p.in = append(p.out, LengthPrefix(p2.out)), p.in[v:]
  410. case protoreflect.StringKind:
  411. p.out, p.in = append(p.out, String(p.in[:v])), p.in[v:]
  412. default:
  413. p.out, p.in = append(p.out, Bytes(p.in[:v])), p.in[v:]
  414. }
  415. }
  416. if m := n - wire.SizeVarint(v); m > 0 {
  417. p.out[len(p.out)-1] = Denormalized{uint(m), p.out[len(p.out)-1]}
  418. }
  419. }
  420. func (p *parser) parsePacked(n int, kind protoreflect.Kind) {
  421. p2 := parser{in: p.in[:n]}
  422. for len(p2.in) > 0 {
  423. switch kind {
  424. case protoreflect.BoolKind, protoreflect.EnumKind,
  425. protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Uint32Kind,
  426. protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Uint64Kind:
  427. p2.parseVarint(kind)
  428. case protoreflect.Fixed32Kind, protoreflect.Sfixed32Kind, protoreflect.FloatKind:
  429. p2.parseFixed32(kind)
  430. case protoreflect.Fixed64Kind, protoreflect.Sfixed64Kind, protoreflect.DoubleKind:
  431. p2.parseFixed64(kind)
  432. default:
  433. panic(fmt.Sprintf("invalid packed kind: %v", kind))
  434. }
  435. }
  436. p.out, p.in = append(p.out, LengthPrefix(p2.out)), p.in[n:]
  437. }
  438. func (p *parser) parseGroup(desc protoreflect.MessageDescriptor) {
  439. p2 := parser{in: p.in}
  440. p2.parseMessage(desc, true)
  441. if len(p2.out) > 0 {
  442. p.out = append(p.out, Message(p2.out))
  443. }
  444. p.in = p2.in
  445. // Append the trailing end group.
  446. v, n := wire.ConsumeVarint(p.in)
  447. if num, typ := wire.DecodeTag(v); typ == EndGroupType {
  448. p.out, p.in = append(p.out, Tag{num, typ}), p.in[n:]
  449. if m := n - wire.SizeVarint(v); m > 0 {
  450. p.out[len(p.out)-1] = Denormalized{uint(m), p.out[len(p.out)-1]}
  451. }
  452. }
  453. }
  454. // Format implements a custom formatter to visualize the syntax tree.
  455. // Using "%#v" formats the Message in Go source code.
  456. func (m Message) Format(s fmt.State, r rune) {
  457. switch r {
  458. case 'x':
  459. io.WriteString(s, fmt.Sprintf("%x", m.Marshal()))
  460. case 'X':
  461. io.WriteString(s, fmt.Sprintf("%X", m.Marshal()))
  462. case 'v':
  463. switch {
  464. case s.Flag('#'):
  465. io.WriteString(s, m.format(true, true))
  466. case s.Flag('+'):
  467. io.WriteString(s, m.format(false, true))
  468. default:
  469. io.WriteString(s, m.format(false, false))
  470. }
  471. default:
  472. panic("invalid verb: " + string(r))
  473. }
  474. }
  475. // format formats the message.
  476. // If source is enabled, this emits valid Go source.
  477. // If multi is enabled, the output may span multiple lines.
  478. func (m Message) format(source, multi bool) string {
  479. var ss []string
  480. var prefix, nextPrefix string
  481. for _, v := range m {
  482. // Ensure certain tokens have preceding or succeeding newlines.
  483. prefix, nextPrefix = nextPrefix, " "
  484. if multi {
  485. switch v := v.(type) {
  486. case Tag: // only has preceding newline
  487. prefix = "\n"
  488. case Denormalized: // only has preceding newline
  489. if _, ok := v.Value.(Tag); ok {
  490. prefix = "\n"
  491. }
  492. case Message, Raw: // has preceding and succeeding newlines
  493. prefix, nextPrefix = "\n", "\n"
  494. }
  495. }
  496. s := formatToken(v, source, multi)
  497. ss = append(ss, prefix+s+",")
  498. }
  499. var s string
  500. if len(ss) > 0 {
  501. s = strings.TrimSpace(strings.Join(ss, ""))
  502. if multi {
  503. s = "\n\t" + strings.Join(strings.Split(s, "\n"), "\n\t") + "\n"
  504. } else {
  505. s = strings.TrimSuffix(s, ",")
  506. }
  507. }
  508. s = fmt.Sprintf("%T{%s}", m, s)
  509. if !source {
  510. s = trimPackage(s)
  511. }
  512. return s
  513. }
  514. // formatToken formats a single token.
  515. func formatToken(t Token, source, multi bool) (s string) {
  516. switch v := t.(type) {
  517. case Message:
  518. s = v.format(source, multi)
  519. case LengthPrefix:
  520. s = formatPacked(v, source, multi)
  521. if s == "" {
  522. ms := Message(v).format(source, multi)
  523. s = fmt.Sprintf("%T(%s)", v, ms)
  524. }
  525. case Tag:
  526. s = fmt.Sprintf("%T{%d, %s}", v, v.Number, formatType(v.Type, source))
  527. case Bool, Varint, Svarint, Uvarint, Int32, Uint32, Float32, Int64, Uint64, Float64:
  528. if source {
  529. // Print floats in a way that preserves exact precision.
  530. if f, _ := v.(Float32); math.IsNaN(float64(f)) || math.IsInf(float64(f), 0) {
  531. switch {
  532. case f > 0:
  533. s = fmt.Sprintf("%T(math.Inf(+1))", v)
  534. case f < 0:
  535. s = fmt.Sprintf("%T(math.Inf(-1))", v)
  536. case math.Float32bits(float32(math.NaN())) == math.Float32bits(float32(f)):
  537. s = fmt.Sprintf("%T(math.NaN())", v)
  538. default:
  539. s = fmt.Sprintf("%T(math.Float32frombits(0x%08x))", v, math.Float32bits(float32(f)))
  540. }
  541. break
  542. }
  543. if f, _ := v.(Float64); math.IsNaN(float64(f)) || math.IsInf(float64(f), 0) {
  544. switch {
  545. case f > 0:
  546. s = fmt.Sprintf("%T(math.Inf(+1))", v)
  547. case f < 0:
  548. s = fmt.Sprintf("%T(math.Inf(-1))", v)
  549. case math.Float64bits(float64(math.NaN())) == math.Float64bits(float64(f)):
  550. s = fmt.Sprintf("%T(math.NaN())", v)
  551. default:
  552. s = fmt.Sprintf("%T(math.Float64frombits(0x%08x))", v, math.Float64bits(float64(f)))
  553. }
  554. break
  555. }
  556. }
  557. s = fmt.Sprintf("%T(%v)", v, v)
  558. case String, Bytes, Raw:
  559. s = fmt.Sprintf("%s", v)
  560. s = fmt.Sprintf("%T(%s)", v, formatString(s))
  561. case Denormalized:
  562. s = fmt.Sprintf("%T{+%d, %v}", v, v.Count, formatToken(v.Value, source, multi))
  563. default:
  564. panic(fmt.Sprintf("unknown type: %T", v))
  565. }
  566. if !source {
  567. s = trimPackage(s)
  568. }
  569. return s
  570. }
  571. // formatPacked returns a non-empty string if LengthPrefix looks like a packed
  572. // repeated field of primitives.
  573. func formatPacked(v LengthPrefix, source, multi bool) string {
  574. var ss []string
  575. for _, v := range v {
  576. switch v.(type) {
  577. case Bool, Varint, Svarint, Uvarint, Int32, Uint32, Float32, Int64, Uint64, Float64, Denormalized, Raw:
  578. if v, ok := v.(Denormalized); ok {
  579. switch v.Value.(type) {
  580. case Bool, Varint, Svarint, Uvarint:
  581. default:
  582. return ""
  583. }
  584. }
  585. ss = append(ss, formatToken(v, source, multi))
  586. default:
  587. return ""
  588. }
  589. }
  590. s := fmt.Sprintf("%T{%s}", v, strings.Join(ss, ", "))
  591. if !source {
  592. s = trimPackage(s)
  593. }
  594. return s
  595. }
  596. // formatType returns the name for Type.
  597. func formatType(t Type, source bool) (s string) {
  598. switch t {
  599. case VarintType:
  600. s = pkg + ".VarintType"
  601. case Fixed32Type:
  602. s = pkg + ".Fixed32Type"
  603. case Fixed64Type:
  604. s = pkg + ".Fixed64Type"
  605. case BytesType:
  606. s = pkg + ".BytesType"
  607. case StartGroupType:
  608. s = pkg + ".StartGroupType"
  609. case EndGroupType:
  610. s = pkg + ".EndGroupType"
  611. default:
  612. s = fmt.Sprintf("Type(%d)", t)
  613. }
  614. if !source {
  615. s = strings.TrimSuffix(trimPackage(s), "Type")
  616. }
  617. return s
  618. }
  619. // formatString returns a quoted string for s.
  620. func formatString(s string) string {
  621. // Use quoted string if it the same length as a raw string literal.
  622. // Otherwise, attempt to use the raw string form.
  623. qs := strconv.Quote(s)
  624. if len(qs) == 1+len(s)+1 {
  625. return qs
  626. }
  627. // Disallow newlines to ensure output is a single line.
  628. // Disallow non-printable runes for readability purposes.
  629. rawInvalid := func(r rune) bool {
  630. return r == '`' || r == '\n' || r == utf8.RuneError || !unicode.IsPrint(r)
  631. }
  632. if strings.IndexFunc(s, rawInvalid) < 0 {
  633. return "`" + s + "`"
  634. }
  635. return qs
  636. }
  637. var pkg = path.Base(reflect.TypeOf(Tag{}).PkgPath())
  638. func trimPackage(s string) string {
  639. return strings.TrimPrefix(strings.TrimPrefix(s, pkg), ".")
  640. }