TextFormat.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  1. #region Copyright notice and license
  2. // Protocol Buffers - Google's data interchange format
  3. // Copyright 2008 Google Inc. All rights reserved.
  4. // http://github.com/jskeet/dotnet-protobufs/
  5. // Original C++/Java/Python code:
  6. // http://code.google.com/p/protobuf/
  7. //
  8. // Redistribution and use in source and binary forms, with or without
  9. // modification, are permitted provided that the following conditions are
  10. // met:
  11. //
  12. // * Redistributions of source code must retain the above copyright
  13. // notice, this list of conditions and the following disclaimer.
  14. // * Redistributions in binary form must reproduce the above
  15. // copyright notice, this list of conditions and the following disclaimer
  16. // in the documentation and/or other materials provided with the
  17. // distribution.
  18. // * Neither the name of Google Inc. nor the names of its
  19. // contributors may be used to endorse or promote products derived from
  20. // this software without specific prior written permission.
  21. //
  22. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  23. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  24. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  25. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  26. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  27. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  28. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  29. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  30. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  31. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  32. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  33. #endregion
  34. using System;
  35. using System.Collections.Generic;
  36. using System.Globalization;
  37. using System.IO;
  38. using System.Text;
  39. using Google.ProtocolBuffers.Descriptors;
  40. using System.Collections;
  41. namespace Google.ProtocolBuffers {
  42. /// <summary>
  43. /// Provides ASCII text formatting support for messages.
  44. /// TODO(jonskeet): Parsing support.
  45. /// </summary>
  46. public static class TextFormat {
  47. /// <summary>
  48. /// Outputs a textual representation of the Protocol Message supplied into
  49. /// the parameter output.
  50. /// </summary>
  51. public static void Print(IMessage message, TextWriter output) {
  52. TextGenerator generator = new TextGenerator(output);
  53. Print(message, generator);
  54. }
  55. /// <summary>
  56. /// Outputs a textual representation of <paramref name="fields" /> to <paramref name="output"/>.
  57. /// </summary>
  58. public static void Print(UnknownFieldSet fields, TextWriter output) {
  59. TextGenerator generator = new TextGenerator(output);
  60. PrintUnknownFields(fields, generator);
  61. }
  62. public static string PrintToString(IMessage message) {
  63. StringWriter text = new StringWriter();
  64. Print(message, text);
  65. return text.ToString();
  66. }
  67. public static string PrintToString(UnknownFieldSet fields) {
  68. StringWriter text = new StringWriter();
  69. Print(fields, text);
  70. return text.ToString();
  71. }
  72. private static void Print(IMessage message, TextGenerator generator) {
  73. foreach (KeyValuePair<FieldDescriptor, object> entry in message.AllFields) {
  74. PrintField(entry.Key, entry.Value, generator);
  75. }
  76. PrintUnknownFields(message.UnknownFields, generator);
  77. }
  78. internal static void PrintField(FieldDescriptor field, object value, TextGenerator generator) {
  79. if (field.IsRepeated) {
  80. // Repeated field. Print each element.
  81. foreach (object element in (IEnumerable) value) {
  82. PrintSingleField(field, element, generator);
  83. }
  84. } else {
  85. PrintSingleField(field, value, generator);
  86. }
  87. }
  88. private static void PrintSingleField(FieldDescriptor field, Object value, TextGenerator generator) {
  89. if (field.IsExtension) {
  90. generator.Print("[");
  91. // We special-case MessageSet elements for compatibility with proto1.
  92. if (field.ContainingType.Options.MessageSetWireFormat
  93. && field.FieldType == FieldType.Message
  94. && field.IsOptional
  95. // object equality (TODO(jonskeet): Work out what this comment means!)
  96. && field.ExtensionScope == field.MessageType) {
  97. generator.Print(field.MessageType.FullName);
  98. } else {
  99. generator.Print(field.FullName);
  100. }
  101. generator.Print("]");
  102. } else {
  103. if (field.FieldType == FieldType.Group) {
  104. // Groups must be serialized with their original capitalization.
  105. generator.Print(field.MessageType.Name);
  106. } else {
  107. generator.Print(field.Name);
  108. }
  109. }
  110. if (field.MappedType == MappedType.Message) {
  111. generator.Print(" {\n");
  112. generator.Indent();
  113. } else {
  114. generator.Print(": ");
  115. }
  116. PrintFieldValue(field, value, generator);
  117. if (field.MappedType == MappedType.Message) {
  118. generator.Outdent();
  119. generator.Print("}");
  120. }
  121. generator.Print("\n");
  122. }
  123. private static void PrintFieldValue(FieldDescriptor field, object value, TextGenerator generator) {
  124. switch (field.FieldType) {
  125. case FieldType.Int32:
  126. case FieldType.Int64:
  127. case FieldType.SInt32:
  128. case FieldType.SInt64:
  129. case FieldType.SFixed32:
  130. case FieldType.SFixed64:
  131. case FieldType.Float:
  132. case FieldType.Double:
  133. case FieldType.UInt32:
  134. case FieldType.UInt64:
  135. case FieldType.Fixed32:
  136. case FieldType.Fixed64:
  137. // The simple Object.ToString converts using the current culture.
  138. // We want to always use the invariant culture so it's predictable.
  139. generator.Print(((IConvertible) value).ToString(CultureInfo.InvariantCulture));
  140. break;
  141. case FieldType.Bool:
  142. // Explicitly use the Java true/false
  143. generator.Print((bool) value ? "true" : "false");
  144. break;
  145. case FieldType.String:
  146. generator.Print("\"");
  147. generator.Print(EscapeText((string) value));
  148. generator.Print("\"");
  149. break;
  150. case FieldType.Bytes: {
  151. generator.Print("\"");
  152. generator.Print(EscapeBytes((ByteString) value));
  153. generator.Print("\"");
  154. break;
  155. }
  156. case FieldType.Enum: {
  157. if (value is IEnumLite && !(value is EnumValueDescriptor)) {
  158. throw new NotSupportedException("Lite enumerations are not supported.");
  159. }
  160. generator.Print(((EnumValueDescriptor)value).Name);
  161. break;
  162. }
  163. case FieldType.Message:
  164. case FieldType.Group:
  165. if (value is IMessageLite && !(value is IMessage)) {
  166. throw new NotSupportedException("Lite messages are not supported.");
  167. }
  168. Print((IMessage)value, generator);
  169. break;
  170. }
  171. }
  172. private static void PrintUnknownFields(UnknownFieldSet unknownFields, TextGenerator generator) {
  173. foreach (KeyValuePair<int, UnknownField> entry in unknownFields.FieldDictionary) {
  174. String prefix = entry.Key.ToString() + ": ";
  175. UnknownField field = entry.Value;
  176. foreach (ulong value in field.VarintList) {
  177. generator.Print(prefix);
  178. generator.Print(value.ToString());
  179. generator.Print("\n");
  180. }
  181. foreach (uint value in field.Fixed32List) {
  182. generator.Print(prefix);
  183. generator.Print(string.Format("0x{0:x8}", value));
  184. generator.Print("\n");
  185. }
  186. foreach (ulong value in field.Fixed64List) {
  187. generator.Print(prefix);
  188. generator.Print(string.Format("0x{0:x16}", value));
  189. generator.Print("\n");
  190. }
  191. foreach (ByteString value in field.LengthDelimitedList) {
  192. generator.Print(entry.Key.ToString());
  193. generator.Print(": \"");
  194. generator.Print(EscapeBytes(value));
  195. generator.Print("\"\n");
  196. }
  197. foreach (UnknownFieldSet value in field.GroupList) {
  198. generator.Print(entry.Key.ToString());
  199. generator.Print(" {\n");
  200. generator.Indent();
  201. PrintUnknownFields(value, generator);
  202. generator.Outdent();
  203. generator.Print("}\n");
  204. }
  205. }
  206. }
  207. internal static ulong ParseUInt64(string text) {
  208. return (ulong) ParseInteger(text, false, true);
  209. }
  210. internal static long ParseInt64(string text) {
  211. return ParseInteger(text, true, true);
  212. }
  213. internal static uint ParseUInt32(string text) {
  214. return (uint) ParseInteger(text, false, false);
  215. }
  216. internal static int ParseInt32(string text) {
  217. return (int) ParseInteger(text, true, false);
  218. }
  219. internal static float ParseFloat(string text) {
  220. switch (text) {
  221. case "-inf":
  222. case "-infinity":
  223. case "-inff":
  224. case "-infinityf":
  225. return float.NegativeInfinity;
  226. case "inf":
  227. case "infinity":
  228. case "inff":
  229. case "infinityf":
  230. return float.PositiveInfinity;
  231. case "nan":
  232. case "nanf":
  233. return float.NaN;
  234. default:
  235. return float.Parse(text, CultureInfo.InvariantCulture);
  236. }
  237. }
  238. internal static double ParseDouble(string text) {
  239. switch (text) {
  240. case "-inf":
  241. case "-infinity":
  242. return double.NegativeInfinity;
  243. case "inf":
  244. case "infinity":
  245. return double.PositiveInfinity;
  246. case "nan":
  247. return double.NaN;
  248. default:
  249. return double.Parse(text, CultureInfo.InvariantCulture);
  250. }
  251. }
  252. /// <summary>
  253. /// Parses an integer in hex (leading 0x), decimal (no prefix) or octal (leading 0).
  254. /// Only a negative sign is permitted, and it must come before the radix indicator.
  255. /// </summary>
  256. private static long ParseInteger(string text, bool isSigned, bool isLong) {
  257. string original = text;
  258. bool negative = false;
  259. if (text.StartsWith("-")) {
  260. if (!isSigned) {
  261. throw new FormatException("Number must be positive: " + original);
  262. }
  263. negative = true;
  264. text = text.Substring(1);
  265. }
  266. int radix = 10;
  267. if (text.StartsWith("0x")) {
  268. radix = 16;
  269. text = text.Substring(2);
  270. } else if (text.StartsWith("0")) {
  271. radix = 8;
  272. }
  273. ulong result;
  274. try {
  275. // Workaround for https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=278448
  276. // We should be able to use Convert.ToUInt64 for all cases.
  277. result = radix == 10 ? ulong.Parse(text) : Convert.ToUInt64(text, radix);
  278. } catch (OverflowException) {
  279. // Convert OverflowException to FormatException so there's a single exception type this method can throw.
  280. string numberDescription = string.Format("{0}-bit {1}signed integer", isLong ? 64 : 32, isSigned ? "" : "un");
  281. throw new FormatException("Number out of range for " + numberDescription + ": " + original);
  282. }
  283. if (negative) {
  284. ulong max = isLong ? 0x8000000000000000UL : 0x80000000L;
  285. if (result > max) {
  286. string numberDescription = string.Format("{0}-bit signed integer", isLong ? 64 : 32);
  287. throw new FormatException("Number out of range for " + numberDescription + ": " + original);
  288. }
  289. return -((long) result);
  290. } else {
  291. ulong max = isSigned
  292. ? (isLong ? (ulong) long.MaxValue : int.MaxValue)
  293. : (isLong ? ulong.MaxValue : uint.MaxValue);
  294. if (result > max) {
  295. string numberDescription = string.Format("{0}-bit {1}signed integer", isLong ? 64 : 32, isSigned ? "" : "un");
  296. throw new FormatException("Number out of range for " + numberDescription + ": " + original);
  297. }
  298. return (long) result;
  299. }
  300. }
  301. /// <summary>
  302. /// Tests a character to see if it's an octal digit.
  303. /// </summary>
  304. private static bool IsOctal(char c) {
  305. return '0' <= c && c <= '7';
  306. }
  307. /// <summary>
  308. /// Tests a character to see if it's a hex digit.
  309. /// </summary>
  310. private static bool IsHex(char c) {
  311. return ('0' <= c && c <= '9') ||
  312. ('a' <= c && c <= 'f') ||
  313. ('A' <= c && c <= 'F');
  314. }
  315. /// <summary>
  316. /// Interprets a character as a digit (in any base up to 36) and returns the
  317. /// numeric value.
  318. /// </summary>
  319. private static int ParseDigit(char c) {
  320. if ('0' <= c && c <= '9') {
  321. return c - '0';
  322. } else if ('a' <= c && c <= 'z') {
  323. return c - 'a' + 10;
  324. } else {
  325. return c - 'A' + 10;
  326. }
  327. }
  328. /// <summary>
  329. /// Unescapes a text string as escaped using <see cref="EscapeText(string)" />.
  330. /// Two-digit hex escapes (starting with "\x" are also recognised.
  331. /// </summary>
  332. internal static string UnescapeText(string input) {
  333. return UnescapeBytes(input).ToStringUtf8();
  334. }
  335. /// <summary>
  336. /// Like <see cref="EscapeBytes" /> but escapes a text string.
  337. /// The string is first encoded as UTF-8, then each byte escaped individually.
  338. /// The returned value is guaranteed to be entirely ASCII.
  339. /// </summary>
  340. internal static string EscapeText(string input) {
  341. return EscapeBytes(ByteString.CopyFromUtf8(input));
  342. }
  343. /// <summary>
  344. /// Escapes bytes in the format used in protocol buffer text format, which
  345. /// is the same as the format used for C string literals. All bytes
  346. /// that are not printable 7-bit ASCII characters are escaped, as well as
  347. /// backslash, single-quote, and double-quote characters. Characters for
  348. /// which no defined short-hand escape sequence is defined will be escaped
  349. /// using 3-digit octal sequences.
  350. /// The returned value is guaranteed to be entirely ASCII.
  351. /// </summary>
  352. internal static String EscapeBytes(ByteString input) {
  353. StringBuilder builder = new StringBuilder(input.Length);
  354. foreach (byte b in input) {
  355. switch (b) {
  356. // C# does not use \a or \v
  357. case 0x07: builder.Append("\\a" ); break;
  358. case (byte)'\b': builder.Append("\\b" ); break;
  359. case (byte)'\f': builder.Append("\\f" ); break;
  360. case (byte)'\n': builder.Append("\\n" ); break;
  361. case (byte)'\r': builder.Append("\\r" ); break;
  362. case (byte)'\t': builder.Append("\\t" ); break;
  363. case 0x0b: builder.Append("\\v" ); break;
  364. case (byte)'\\': builder.Append("\\\\"); break;
  365. case (byte)'\'': builder.Append("\\\'"); break;
  366. case (byte)'"' : builder.Append("\\\""); break;
  367. default:
  368. if (b >= 0x20 && b < 128) {
  369. builder.Append((char) b);
  370. } else {
  371. builder.Append('\\');
  372. builder.Append((char) ('0' + ((b >> 6) & 3)));
  373. builder.Append((char) ('0' + ((b >> 3) & 7)));
  374. builder.Append((char) ('0' + (b & 7)));
  375. }
  376. break;
  377. }
  378. }
  379. return builder.ToString();
  380. }
  381. /// <summary>
  382. /// Performs string unescaping from C style (octal, hex, form feeds, tab etc) into a byte string.
  383. /// </summary>
  384. internal static ByteString UnescapeBytes(string input) {
  385. byte[] result = new byte[input.Length];
  386. int pos = 0;
  387. for (int i = 0; i < input.Length; i++) {
  388. char c = input[i];
  389. if (c > 127 || c < 32) {
  390. throw new FormatException("Escaped string must only contain ASCII");
  391. }
  392. if (c != '\\') {
  393. result[pos++] = (byte) c;
  394. continue;
  395. }
  396. if (i + 1 >= input.Length) {
  397. throw new FormatException("Invalid escape sequence: '\\' at end of string.");
  398. }
  399. i++;
  400. c = input[i];
  401. if (c >= '0' && c <= '7') {
  402. // Octal escape.
  403. int code = ParseDigit(c);
  404. if (i + 1 < input.Length && IsOctal(input[i+1])) {
  405. i++;
  406. code = code * 8 + ParseDigit(input[i]);
  407. }
  408. if (i + 1 < input.Length && IsOctal(input[i+1])) {
  409. i++;
  410. code = code * 8 + ParseDigit(input[i]);
  411. }
  412. result[pos++] = (byte) code;
  413. } else {
  414. switch (c) {
  415. case 'a': result[pos++] = 0x07; break;
  416. case 'b': result[pos++] = (byte) '\b'; break;
  417. case 'f': result[pos++] = (byte) '\f'; break;
  418. case 'n': result[pos++] = (byte) '\n'; break;
  419. case 'r': result[pos++] = (byte) '\r'; break;
  420. case 't': result[pos++] = (byte) '\t'; break;
  421. case 'v': result[pos++] = 0x0b; break;
  422. case '\\': result[pos++] = (byte) '\\'; break;
  423. case '\'': result[pos++] = (byte) '\''; break;
  424. case '"': result[pos++] = (byte) '\"'; break;
  425. case 'x':
  426. // hex escape
  427. int code;
  428. if (i + 1 < input.Length && IsHex(input[i+1])) {
  429. i++;
  430. code = ParseDigit(input[i]);
  431. } else {
  432. throw new FormatException("Invalid escape sequence: '\\x' with no digits");
  433. }
  434. if (i + 1 < input.Length && IsHex(input[i+1])) {
  435. ++i;
  436. code = code * 16 + ParseDigit(input[i]);
  437. }
  438. result[pos++] = (byte)code;
  439. break;
  440. default:
  441. throw new FormatException("Invalid escape sequence: '\\" + c + "'");
  442. }
  443. }
  444. }
  445. return ByteString.CopyFrom(result, 0, pos);
  446. }
  447. public static void Merge(string text, IBuilder builder) {
  448. Merge(text, ExtensionRegistry.Empty, builder);
  449. }
  450. public static void Merge(TextReader reader, IBuilder builder) {
  451. Merge(reader, ExtensionRegistry.Empty, builder);
  452. }
  453. public static void Merge(TextReader reader, ExtensionRegistry registry, IBuilder builder) {
  454. Merge(reader.ReadToEnd(), registry, builder);
  455. }
  456. public static void Merge(string text, ExtensionRegistry registry, IBuilder builder) {
  457. TextTokenizer tokenizer = new TextTokenizer(text);
  458. while (!tokenizer.AtEnd) {
  459. MergeField(tokenizer, registry, builder);
  460. }
  461. }
  462. /// <summary>
  463. /// Parses a single field from the specified tokenizer and merges it into
  464. /// the builder.
  465. /// </summary>
  466. private static void MergeField(TextTokenizer tokenizer, ExtensionRegistry extensionRegistry,
  467. IBuilder builder) {
  468. FieldDescriptor field;
  469. MessageDescriptor type = builder.DescriptorForType;
  470. ExtensionInfo extension = null;
  471. if (tokenizer.TryConsume("[")) {
  472. // An extension.
  473. StringBuilder name = new StringBuilder(tokenizer.ConsumeIdentifier());
  474. while (tokenizer.TryConsume(".")) {
  475. name.Append(".");
  476. name.Append(tokenizer.ConsumeIdentifier());
  477. }
  478. extension = extensionRegistry[name.ToString()];
  479. if (extension == null) {
  480. throw tokenizer.CreateFormatExceptionPreviousToken("Extension \"" + name + "\" not found in the ExtensionRegistry.");
  481. } else if (extension.Descriptor.ContainingType != type) {
  482. throw tokenizer.CreateFormatExceptionPreviousToken("Extension \"" + name + "\" does not extend message type \"" +
  483. type.FullName + "\".");
  484. }
  485. tokenizer.Consume("]");
  486. field = extension.Descriptor;
  487. } else {
  488. String name = tokenizer.ConsumeIdentifier();
  489. field = type.FindDescriptor<FieldDescriptor>(name);
  490. // Group names are expected to be capitalized as they appear in the
  491. // .proto file, which actually matches their type names, not their field
  492. // names.
  493. if (field == null) {
  494. // Explicitly specify the invariant culture so that this code does not break when
  495. // executing in Turkey.
  496. String lowerName = name.ToLower(CultureInfo.InvariantCulture);
  497. field = type.FindDescriptor<FieldDescriptor>(lowerName);
  498. // If the case-insensitive match worked but the field is NOT a group,
  499. // TODO(jonskeet): What? Java comment ends here!
  500. if (field != null && field.FieldType != FieldType.Group) {
  501. field = null;
  502. }
  503. }
  504. // Again, special-case group names as described above.
  505. if (field != null && field.FieldType == FieldType.Group && field.MessageType.Name != name) {
  506. field = null;
  507. }
  508. if (field == null) {
  509. throw tokenizer.CreateFormatExceptionPreviousToken(
  510. "Message type \"" + type.FullName + "\" has no field named \"" + name + "\".");
  511. }
  512. }
  513. object value = null;
  514. if (field.MappedType == MappedType.Message) {
  515. tokenizer.TryConsume(":"); // optional
  516. String endToken;
  517. if (tokenizer.TryConsume("<")) {
  518. endToken = ">";
  519. } else {
  520. tokenizer.Consume("{");
  521. endToken = "}";
  522. }
  523. IBuilder subBuilder;
  524. if (extension == null) {
  525. subBuilder = builder.CreateBuilderForField(field);
  526. } else {
  527. subBuilder = extension.DefaultInstance.WeakCreateBuilderForType() as IBuilder;
  528. if (subBuilder == null)
  529. throw new NotSupportedException("Lite messages are not supported.");
  530. }
  531. while (!tokenizer.TryConsume(endToken)) {
  532. if (tokenizer.AtEnd) {
  533. throw tokenizer.CreateFormatException("Expected \"" + endToken + "\".");
  534. }
  535. MergeField(tokenizer, extensionRegistry, subBuilder);
  536. }
  537. value = subBuilder.WeakBuild();
  538. } else {
  539. tokenizer.Consume(":");
  540. switch (field.FieldType) {
  541. case FieldType.Int32:
  542. case FieldType.SInt32:
  543. case FieldType.SFixed32:
  544. value = tokenizer.ConsumeInt32();
  545. break;
  546. case FieldType.Int64:
  547. case FieldType.SInt64:
  548. case FieldType.SFixed64:
  549. value = tokenizer.ConsumeInt64();
  550. break;
  551. case FieldType.UInt32:
  552. case FieldType.Fixed32:
  553. value = tokenizer.ConsumeUInt32();
  554. break;
  555. case FieldType.UInt64:
  556. case FieldType.Fixed64:
  557. value = tokenizer.ConsumeUInt64();
  558. break;
  559. case FieldType.Float:
  560. value = tokenizer.ConsumeFloat();
  561. break;
  562. case FieldType.Double:
  563. value = tokenizer.ConsumeDouble();
  564. break;
  565. case FieldType.Bool:
  566. value = tokenizer.ConsumeBoolean();
  567. break;
  568. case FieldType.String:
  569. value = tokenizer.ConsumeString();
  570. break;
  571. case FieldType.Bytes:
  572. value = tokenizer.ConsumeByteString();
  573. break;
  574. case FieldType.Enum: {
  575. EnumDescriptor enumType = field.EnumType;
  576. if (tokenizer.LookingAtInteger()) {
  577. int number = tokenizer.ConsumeInt32();
  578. value = enumType.FindValueByNumber(number);
  579. if (value == null) {
  580. throw tokenizer.CreateFormatExceptionPreviousToken(
  581. "Enum type \"" + enumType.FullName +
  582. "\" has no value with number " + number + ".");
  583. }
  584. } else {
  585. String id = tokenizer.ConsumeIdentifier();
  586. value = enumType.FindValueByName(id);
  587. if (value == null) {
  588. throw tokenizer.CreateFormatExceptionPreviousToken(
  589. "Enum type \"" + enumType.FullName +
  590. "\" has no value named \"" + id + "\".");
  591. }
  592. }
  593. break;
  594. }
  595. case FieldType.Message:
  596. case FieldType.Group:
  597. throw new InvalidOperationException("Can't get here.");
  598. }
  599. }
  600. if (field.IsRepeated) {
  601. builder.WeakAddRepeatedField(field, value);
  602. } else {
  603. builder.SetField(field, value);
  604. }
  605. }
  606. }
  607. }