text_parser.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  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://code.google.com/p/gogoprotobuf/gogoproto
  5. //
  6. // Go support for Protocol Buffers - Google's data interchange format
  7. //
  8. // Copyright 2010 The Go Authors. All rights reserved.
  9. // http://code.google.com/p/goprotobuf/
  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 parsing the Text protocol buffer format.
  38. // TODO: message sets.
  39. import (
  40. "errors"
  41. "fmt"
  42. "reflect"
  43. "strconv"
  44. "strings"
  45. "unicode/utf8"
  46. )
  47. type ParseError struct {
  48. Message string
  49. Line int // 1-based line number
  50. Offset int // 0-based byte offset from start of input
  51. }
  52. func (p *ParseError) Error() string {
  53. if p.Line == 1 {
  54. // show offset only for first line
  55. return fmt.Sprintf("line 1.%d: %v", p.Offset, p.Message)
  56. }
  57. return fmt.Sprintf("line %d: %v", p.Line, p.Message)
  58. }
  59. type token struct {
  60. value string
  61. err *ParseError
  62. line int // line number
  63. offset int // byte number from start of input, not start of line
  64. unquoted string // the unquoted version of value, if it was a quoted string
  65. }
  66. func (t *token) String() string {
  67. if t.err == nil {
  68. return fmt.Sprintf("%q (line=%d, offset=%d)", t.value, t.line, t.offset)
  69. }
  70. return fmt.Sprintf("parse error: %v", t.err)
  71. }
  72. type textParser struct {
  73. s string // remaining input
  74. done bool // whether the parsing is finished (success or error)
  75. backed bool // whether back() was called
  76. offset, line int
  77. cur token
  78. }
  79. func newTextParser(s string) *textParser {
  80. p := new(textParser)
  81. p.s = s
  82. p.line = 1
  83. p.cur.line = 1
  84. return p
  85. }
  86. func (p *textParser) errorf(format string, a ...interface{}) *ParseError {
  87. pe := &ParseError{fmt.Sprintf(format, a...), p.cur.line, p.cur.offset}
  88. p.cur.err = pe
  89. p.done = true
  90. return pe
  91. }
  92. // Numbers and identifiers are matched by [-+._A-Za-z0-9]
  93. func isIdentOrNumberChar(c byte) bool {
  94. switch {
  95. case 'A' <= c && c <= 'Z', 'a' <= c && c <= 'z':
  96. return true
  97. case '0' <= c && c <= '9':
  98. return true
  99. }
  100. switch c {
  101. case '-', '+', '.', '_':
  102. return true
  103. }
  104. return false
  105. }
  106. func isWhitespace(c byte) bool {
  107. switch c {
  108. case ' ', '\t', '\n', '\r':
  109. return true
  110. }
  111. return false
  112. }
  113. func (p *textParser) skipWhitespace() {
  114. i := 0
  115. for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') {
  116. if p.s[i] == '#' {
  117. // comment; skip to end of line or input
  118. for i < len(p.s) && p.s[i] != '\n' {
  119. i++
  120. }
  121. if i == len(p.s) {
  122. break
  123. }
  124. }
  125. if p.s[i] == '\n' {
  126. p.line++
  127. }
  128. i++
  129. }
  130. p.offset += i
  131. p.s = p.s[i:len(p.s)]
  132. if len(p.s) == 0 {
  133. p.done = true
  134. }
  135. }
  136. func (p *textParser) advance() {
  137. // Skip whitespace
  138. p.skipWhitespace()
  139. if p.done {
  140. return
  141. }
  142. // Start of non-whitespace
  143. p.cur.err = nil
  144. p.cur.offset, p.cur.line = p.offset, p.line
  145. p.cur.unquoted = ""
  146. switch p.s[0] {
  147. case '<', '>', '{', '}', ':', '[', ']', ';', ',':
  148. // Single symbol
  149. p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)]
  150. case '"', '\'':
  151. // Quoted string
  152. i := 1
  153. for i < len(p.s) && p.s[i] != p.s[0] && p.s[i] != '\n' {
  154. if p.s[i] == '\\' && i+1 < len(p.s) {
  155. // skip escaped char
  156. i++
  157. }
  158. i++
  159. }
  160. if i >= len(p.s) || p.s[i] != p.s[0] {
  161. p.errorf("unmatched quote")
  162. return
  163. }
  164. unq, err := unquoteC(p.s[1:i], rune(p.s[0]))
  165. if err != nil {
  166. p.errorf("invalid quoted string %v", p.s[0:i+1])
  167. return
  168. }
  169. p.cur.value, p.s = p.s[0:i+1], p.s[i+1:len(p.s)]
  170. p.cur.unquoted = unq
  171. default:
  172. i := 0
  173. for i < len(p.s) && isIdentOrNumberChar(p.s[i]) {
  174. i++
  175. }
  176. if i == 0 {
  177. p.errorf("unexpected byte %#x", p.s[0])
  178. return
  179. }
  180. p.cur.value, p.s = p.s[0:i], p.s[i:len(p.s)]
  181. }
  182. p.offset += len(p.cur.value)
  183. }
  184. var (
  185. errBadUTF8 = errors.New("proto: bad UTF-8")
  186. errBadHex = errors.New("proto: bad hexadecimal")
  187. )
  188. func unquoteC(s string, quote rune) (string, error) {
  189. // This is based on C++'s tokenizer.cc.
  190. // Despite its name, this is *not* parsing C syntax.
  191. // For instance, "\0" is an invalid quoted string.
  192. // Avoid allocation in trivial cases.
  193. simple := true
  194. for _, r := range s {
  195. if r == '\\' || r == quote {
  196. simple = false
  197. break
  198. }
  199. }
  200. if simple {
  201. return s, nil
  202. }
  203. buf := make([]byte, 0, 3*len(s)/2)
  204. for len(s) > 0 {
  205. r, n := utf8.DecodeRuneInString(s)
  206. if r == utf8.RuneError && n == 1 {
  207. return "", errBadUTF8
  208. }
  209. s = s[n:]
  210. if r != '\\' {
  211. if r < utf8.RuneSelf {
  212. buf = append(buf, byte(r))
  213. } else {
  214. buf = append(buf, string(r)...)
  215. }
  216. continue
  217. }
  218. ch, tail, err := unescape(s)
  219. if err != nil {
  220. return "", err
  221. }
  222. buf = append(buf, ch...)
  223. s = tail
  224. }
  225. return string(buf), nil
  226. }
  227. func unescape(s string) (ch string, tail string, err error) {
  228. r, n := utf8.DecodeRuneInString(s)
  229. if r == utf8.RuneError && n == 1 {
  230. return "", "", errBadUTF8
  231. }
  232. s = s[n:]
  233. switch r {
  234. case 'a':
  235. return "\a", s, nil
  236. case 'b':
  237. return "\b", s, nil
  238. case 'f':
  239. return "\f", s, nil
  240. case 'n':
  241. return "\n", s, nil
  242. case 'r':
  243. return "\r", s, nil
  244. case 't':
  245. return "\t", s, nil
  246. case 'v':
  247. return "\v", s, nil
  248. case '?':
  249. return "?", s, nil // trigraph workaround
  250. case '\'', '"', '\\':
  251. return string(r), s, nil
  252. case '0', '1', '2', '3', '4', '5', '6', '7', 'x', 'X':
  253. if len(s) < 2 {
  254. return "", "", fmt.Errorf(`\%c requires 2 following digits`, r)
  255. }
  256. base := 8
  257. ss := s[:2]
  258. s = s[2:]
  259. if r == 'x' || r == 'X' {
  260. base = 16
  261. } else {
  262. ss = string(r) + ss
  263. }
  264. i, err := strconv.ParseUint(ss, base, 8)
  265. if err != nil {
  266. return "", "", err
  267. }
  268. return string([]byte{byte(i)}), s, nil
  269. case 'u', 'U':
  270. n := 4
  271. if r == 'U' {
  272. n = 8
  273. }
  274. if len(s) < n {
  275. return "", "", fmt.Errorf(`\%c requires %d digits`, r, n)
  276. }
  277. bs := make([]byte, n/2)
  278. for i := 0; i < n; i += 2 {
  279. a, ok1 := unhex(s[i])
  280. b, ok2 := unhex(s[i+1])
  281. if !ok1 || !ok2 {
  282. return "", "", errBadHex
  283. }
  284. bs[i/2] = a<<4 | b
  285. }
  286. s = s[n:]
  287. return string(bs), s, nil
  288. }
  289. return "", "", fmt.Errorf(`unknown escape \%c`, r)
  290. }
  291. // Adapted from src/pkg/strconv/quote.go.
  292. func unhex(b byte) (v byte, ok bool) {
  293. switch {
  294. case '0' <= b && b <= '9':
  295. return b - '0', true
  296. case 'a' <= b && b <= 'f':
  297. return b - 'a' + 10, true
  298. case 'A' <= b && b <= 'F':
  299. return b - 'A' + 10, true
  300. }
  301. return 0, false
  302. }
  303. // Back off the parser by one token. Can only be done between calls to next().
  304. // It makes the next advance() a no-op.
  305. func (p *textParser) back() { p.backed = true }
  306. // Advances the parser and returns the new current token.
  307. func (p *textParser) next() *token {
  308. if p.backed || p.done {
  309. p.backed = false
  310. return &p.cur
  311. }
  312. p.advance()
  313. if p.done {
  314. p.cur.value = ""
  315. } else if len(p.cur.value) > 0 && p.cur.value[0] == '"' {
  316. // Look for multiple quoted strings separated by whitespace,
  317. // and concatenate them.
  318. cat := p.cur
  319. for {
  320. p.skipWhitespace()
  321. if p.done || p.s[0] != '"' {
  322. break
  323. }
  324. p.advance()
  325. if p.cur.err != nil {
  326. return &p.cur
  327. }
  328. cat.value += " " + p.cur.value
  329. cat.unquoted += p.cur.unquoted
  330. }
  331. p.done = false // parser may have seen EOF, but we want to return cat
  332. p.cur = cat
  333. }
  334. return &p.cur
  335. }
  336. // Return an error indicating which required field was not set.
  337. func (p *textParser) missingRequiredFieldError(sv reflect.Value) *ParseError {
  338. st := sv.Type()
  339. sprops := GetProperties(st)
  340. for i := 0; i < st.NumField(); i++ {
  341. if !isNil(sv.Field(i)) {
  342. continue
  343. }
  344. props := sprops.Prop[i]
  345. if props.Required {
  346. return p.errorf("message %v missing required field %q", st, props.OrigName)
  347. }
  348. }
  349. return p.errorf("message %v missing required field", st) // should not happen
  350. }
  351. // Returns the index in the struct for the named field, as well as the parsed tag properties.
  352. func structFieldByName(st reflect.Type, name string) (int, *Properties, bool) {
  353. sprops := GetProperties(st)
  354. i, ok := sprops.decoderOrigNames[name]
  355. if ok {
  356. return i, sprops.Prop[i], true
  357. }
  358. return -1, nil, false
  359. }
  360. // Consume a ':' from the input stream (if the next token is a colon),
  361. // returning an error if a colon is needed but not present.
  362. func (p *textParser) checkForColon(props *Properties, typ reflect.Type) *ParseError {
  363. tok := p.next()
  364. if tok.err != nil {
  365. return tok.err
  366. }
  367. if tok.value != ":" {
  368. // Colon is optional when the field is a group or message.
  369. needColon := true
  370. switch props.Wire {
  371. case "group":
  372. needColon = false
  373. case "bytes":
  374. // A "bytes" field is either a message, a string, or a repeated field;
  375. // those three become *T, *string and []T respectively, so we can check for
  376. // this field being a pointer to a non-string.
  377. if typ.Kind() == reflect.Ptr {
  378. // *T or *string
  379. if typ.Elem().Kind() == reflect.String {
  380. break
  381. }
  382. } else if typ.Kind() == reflect.Slice {
  383. // []T or []*T
  384. if typ.Elem().Kind() != reflect.Ptr {
  385. break
  386. }
  387. }
  388. needColon = false
  389. }
  390. if needColon {
  391. return p.errorf("expected ':', found %q", tok.value)
  392. }
  393. p.back()
  394. }
  395. return nil
  396. }
  397. func (p *textParser) readStruct(sv reflect.Value, terminator string) *ParseError {
  398. st := sv.Type()
  399. reqCount := GetProperties(st).reqCount
  400. // A struct is a sequence of "name: value", terminated by one of
  401. // '>' or '}', or the end of the input. A name may also be
  402. // "[extension]".
  403. for {
  404. tok := p.next()
  405. if tok.err != nil {
  406. return tok.err
  407. }
  408. if tok.value == terminator {
  409. break
  410. }
  411. if tok.value == "[" {
  412. // Looks like an extension.
  413. //
  414. // TODO: Check whether we need to handle
  415. // namespace rooted names (e.g. ".something.Foo").
  416. tok = p.next()
  417. if tok.err != nil {
  418. return tok.err
  419. }
  420. var desc *ExtensionDesc
  421. // This could be faster, but it's functional.
  422. // TODO: Do something smarter than a linear scan.
  423. for _, d := range RegisteredExtensions(reflect.New(st).Interface().(Message)) {
  424. if d.Name == tok.value {
  425. desc = d
  426. break
  427. }
  428. }
  429. if desc == nil {
  430. return p.errorf("unrecognized extension %q", tok.value)
  431. }
  432. // Check the extension terminator.
  433. tok = p.next()
  434. if tok.err != nil {
  435. return tok.err
  436. }
  437. if tok.value != "]" {
  438. return p.errorf("unrecognized extension terminator %q", tok.value)
  439. }
  440. props := &Properties{}
  441. props.Parse(desc.Tag)
  442. typ := reflect.TypeOf(desc.ExtensionType)
  443. if err := p.checkForColon(props, typ); err != nil {
  444. return err
  445. }
  446. rep := desc.repeated()
  447. // Read the extension structure, and set it in
  448. // the value we're constructing.
  449. var ext reflect.Value
  450. if !rep {
  451. ext = reflect.New(typ).Elem()
  452. } else {
  453. ext = reflect.New(typ.Elem()).Elem()
  454. }
  455. if err := p.readAny(ext, props); err != nil {
  456. return err
  457. }
  458. ep := sv.Addr().Interface().(extendableProto)
  459. if !rep {
  460. SetExtension(ep, desc, ext.Interface())
  461. } else {
  462. old, err := GetExtension(ep, desc)
  463. var sl reflect.Value
  464. if err == nil {
  465. sl = reflect.ValueOf(old) // existing slice
  466. } else {
  467. sl = reflect.MakeSlice(typ, 0, 1)
  468. }
  469. sl = reflect.Append(sl, ext)
  470. SetExtension(ep, desc, sl.Interface())
  471. }
  472. } else {
  473. // This is a normal, non-extension field.
  474. fi, props, ok := structFieldByName(st, tok.value)
  475. if !ok {
  476. return p.errorf("unknown field name %q in %v", tok.value, st)
  477. }
  478. dst := sv.Field(fi)
  479. isDstNil := isNil(dst)
  480. // Check that it's not already set if it's not a repeated field.
  481. if !props.Repeated && !isDstNil && dst.Kind() == reflect.Ptr {
  482. return p.errorf("non-repeated field %q was repeated", tok.value)
  483. }
  484. if err := p.checkForColon(props, st.Field(fi).Type); err != nil {
  485. return err
  486. }
  487. // Parse into the field.
  488. if err := p.readAny(dst, props); err != nil {
  489. return err
  490. }
  491. if props.Required {
  492. reqCount--
  493. }
  494. }
  495. // For backward compatibility, permit a semicolon or comma after a field.
  496. tok = p.next()
  497. if tok.err != nil {
  498. return tok.err
  499. }
  500. if tok.value != ";" && tok.value != "," {
  501. p.back()
  502. }
  503. }
  504. if reqCount > 0 {
  505. return p.missingRequiredFieldError(sv)
  506. }
  507. return nil
  508. }
  509. func (p *textParser) readAny(v reflect.Value, props *Properties) *ParseError {
  510. tok := p.next()
  511. if tok.err != nil {
  512. return tok.err
  513. }
  514. if tok.value == "" {
  515. return p.errorf("unexpected EOF")
  516. }
  517. if len(props.CustomType) > 0 {
  518. if props.Repeated {
  519. t := reflect.TypeOf(v.Interface())
  520. if t.Kind() == reflect.Slice {
  521. tc := reflect.TypeOf(new(Marshaler))
  522. ok := t.Elem().Implements(tc.Elem())
  523. if ok {
  524. fv := v
  525. flen := fv.Len()
  526. if flen == fv.Cap() {
  527. nav := reflect.MakeSlice(v.Type(), flen, 2*flen+1)
  528. reflect.Copy(nav, fv)
  529. fv.Set(nav)
  530. }
  531. fv.SetLen(flen + 1)
  532. // Read one.
  533. p.back()
  534. return p.readAny(fv.Index(flen), props)
  535. }
  536. }
  537. }
  538. if reflect.TypeOf(v.Interface()).Kind() == reflect.Ptr {
  539. custom := reflect.New(props.ctype.Elem()).Interface().(Unmarshaler)
  540. err := custom.Unmarshal([]byte(tok.unquoted))
  541. if err != nil {
  542. return p.errorf("%v %v: %v", err, v.Type(), tok.value)
  543. }
  544. v.Set(reflect.ValueOf(custom))
  545. } else {
  546. custom := reflect.New(reflect.TypeOf(v.Interface())).Interface().(Unmarshaler)
  547. err := custom.Unmarshal([]byte(tok.unquoted))
  548. if err != nil {
  549. return p.errorf("%v %v: %v", err, v.Type(), tok.value)
  550. }
  551. v.Set(reflect.Indirect(reflect.ValueOf(custom)))
  552. }
  553. return nil
  554. }
  555. switch fv := v; fv.Kind() {
  556. case reflect.Slice:
  557. at := v.Type()
  558. if at.Elem().Kind() == reflect.Uint8 {
  559. // Special case for []byte
  560. if tok.value[0] != '"' && tok.value[0] != '\'' {
  561. // Deliberately written out here, as the error after
  562. // this switch statement would write "invalid []byte: ...",
  563. // which is not as user-friendly.
  564. return p.errorf("invalid string: %v", tok.value)
  565. }
  566. bytes := []byte(tok.unquoted)
  567. fv.Set(reflect.ValueOf(bytes))
  568. return nil
  569. }
  570. // Repeated field. May already exist.
  571. flen := fv.Len()
  572. if flen == fv.Cap() {
  573. nav := reflect.MakeSlice(at, flen, 2*flen+1)
  574. reflect.Copy(nav, fv)
  575. fv.Set(nav)
  576. }
  577. fv.SetLen(flen + 1)
  578. // Read one.
  579. p.back()
  580. return p.readAny(fv.Index(flen), props)
  581. case reflect.Bool:
  582. // Either "true", "false", 1 or 0.
  583. switch tok.value {
  584. case "true", "1":
  585. fv.SetBool(true)
  586. return nil
  587. case "false", "0":
  588. fv.SetBool(false)
  589. return nil
  590. }
  591. case reflect.Float32, reflect.Float64:
  592. v := tok.value
  593. // Ignore 'f' for compatibility with output generated by C++, but don't
  594. // remove 'f' when the value is "-inf" or "inf".
  595. if strings.HasSuffix(v, "f") && tok.value != "-inf" && tok.value != "inf" {
  596. v = v[:len(v)-1]
  597. }
  598. if f, err := strconv.ParseFloat(v, fv.Type().Bits()); err == nil {
  599. fv.SetFloat(f)
  600. return nil
  601. }
  602. case reflect.Int32:
  603. if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil {
  604. fv.SetInt(x)
  605. return nil
  606. }
  607. if len(props.Enum) == 0 {
  608. break
  609. }
  610. m, ok := enumValueMaps[props.Enum]
  611. if !ok {
  612. break
  613. }
  614. x, ok := m[tok.value]
  615. if !ok {
  616. break
  617. }
  618. fv.SetInt(int64(x))
  619. return nil
  620. case reflect.Int64:
  621. if x, err := strconv.ParseInt(tok.value, 0, 64); err == nil {
  622. fv.SetInt(x)
  623. return nil
  624. }
  625. case reflect.Ptr:
  626. // A basic field (indirected through pointer), or a repeated message/group
  627. p.back()
  628. fv.Set(reflect.New(fv.Type().Elem()))
  629. return p.readAny(fv.Elem(), props)
  630. case reflect.String:
  631. if tok.value[0] == '"' || tok.value[0] == '\'' {
  632. fv.SetString(tok.unquoted)
  633. return nil
  634. }
  635. case reflect.Struct:
  636. var terminator string
  637. switch tok.value {
  638. case "{":
  639. terminator = "}"
  640. case "<":
  641. terminator = ">"
  642. default:
  643. return p.errorf("expected '{' or '<', found %q", tok.value)
  644. }
  645. return p.readStruct(fv, terminator)
  646. case reflect.Uint32:
  647. if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil {
  648. fv.SetUint(uint64(x))
  649. return nil
  650. }
  651. case reflect.Uint64:
  652. if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil {
  653. fv.SetUint(x)
  654. return nil
  655. }
  656. }
  657. return p.errorf("invalid %v: %v", v.Type(), tok.value)
  658. }
  659. // UnmarshalText reads a protocol buffer in Text format. UnmarshalText resets pb
  660. // before starting to unmarshal, so any existing data in pb is always removed.
  661. func UnmarshalText(s string, pb Message) error {
  662. pb.Reset()
  663. v := reflect.ValueOf(pb)
  664. if pe := newTextParser(s).readStruct(v.Elem(), ""); pe != nil {
  665. return pe
  666. }
  667. return nil
  668. }