CodedInputStreamTest.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  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.IO;
  37. using Google.ProtocolBuffers.Descriptors;
  38. using Google.ProtocolBuffers.TestProtos;
  39. using Xunit;
  40. namespace Google.ProtocolBuffers
  41. {
  42. public class CodedInputStreamTest
  43. {
  44. /// <summary>
  45. /// Helper to construct a byte array from a bunch of bytes. The inputs are
  46. /// actually ints so that I can use hex notation and not get stupid errors
  47. /// about precision.
  48. /// </summary>
  49. private static byte[] Bytes(params int[] bytesAsInts)
  50. {
  51. byte[] bytes = new byte[bytesAsInts.Length];
  52. for (int i = 0; i < bytesAsInts.Length; i++)
  53. {
  54. bytes[i] = (byte) bytesAsInts[i];
  55. }
  56. return bytes;
  57. }
  58. /// <summary>
  59. /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() and
  60. /// </summary>
  61. private static void AssertReadVarint(byte[] data, ulong value)
  62. {
  63. CodedInputStream input = CodedInputStream.CreateInstance(data);
  64. Assert.Equal((uint) value, input.ReadRawVarint32());
  65. input = CodedInputStream.CreateInstance(data);
  66. Assert.Equal(value, input.ReadRawVarint64());
  67. Assert.True(input.IsAtEnd);
  68. // Try different block sizes.
  69. for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2)
  70. {
  71. input = CodedInputStream.CreateInstance(new SmallBlockInputStream(data, bufferSize));
  72. Assert.Equal((uint) value, input.ReadRawVarint32());
  73. input = CodedInputStream.CreateInstance(new SmallBlockInputStream(data, bufferSize));
  74. Assert.Equal(value, input.ReadRawVarint64());
  75. Assert.True(input.IsAtEnd);
  76. }
  77. // Try reading directly from a MemoryStream. We want to verify that it
  78. // doesn't read past the end of the input, so write an extra byte - this
  79. // lets us test the position at the end.
  80. MemoryStream memoryStream = new MemoryStream();
  81. memoryStream.Write(data, 0, data.Length);
  82. memoryStream.WriteByte(0);
  83. memoryStream.Position = 0;
  84. Assert.Equal((uint) value, CodedInputStream.ReadRawVarint32(memoryStream));
  85. Assert.Equal(data.Length, memoryStream.Position);
  86. }
  87. /// <summary>
  88. /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() and
  89. /// expects them to fail with an InvalidProtocolBufferException whose
  90. /// description matches the given one.
  91. /// </summary>
  92. private static void AssertReadVarintFailure(InvalidProtocolBufferException expected, byte[] data)
  93. {
  94. CodedInputStream input = CodedInputStream.CreateInstance(data);
  95. var exception = Assert.Throws<InvalidProtocolBufferException>(() => input.ReadRawVarint32());
  96. Assert.Equal(expected.Message, exception.Message);
  97. input = CodedInputStream.CreateInstance(data);
  98. exception = Assert.Throws<InvalidProtocolBufferException>(() => input.ReadRawVarint64());
  99. Assert.Equal(expected.Message, exception.Message);
  100. // Make sure we get the same error when reading directly from a Stream.
  101. exception = Assert.Throws<InvalidProtocolBufferException>(() => CodedInputStream.ReadRawVarint32(new MemoryStream(data)));
  102. Assert.Equal(expected.Message, exception.Message);
  103. }
  104. [Fact]
  105. public void ReadVarint()
  106. {
  107. AssertReadVarint(Bytes(0x00), 0);
  108. AssertReadVarint(Bytes(0x01), 1);
  109. AssertReadVarint(Bytes(0x7f), 127);
  110. // 14882
  111. AssertReadVarint(Bytes(0xa2, 0x74), (0x22 << 0) | (0x74 << 7));
  112. // 2961488830
  113. AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x0b),
  114. (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
  115. (0x0bL << 28));
  116. // 64-bit
  117. // 7256456126
  118. AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x1b),
  119. (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
  120. (0x1bL << 28));
  121. // 41256202580718336
  122. AssertReadVarint(Bytes(0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49),
  123. (0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) |
  124. (0x43L << 28) | (0x49L << 35) | (0x24L << 42) | (0x49L << 49));
  125. // 11964378330978735131
  126. AssertReadVarint(Bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01),
  127. (0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) |
  128. (0x3bUL << 28) | (0x56UL << 35) | (0x00UL << 42) |
  129. (0x05UL << 49) | (0x26UL << 56) | (0x01UL << 63));
  130. // Failures
  131. AssertReadVarintFailure(
  132. InvalidProtocolBufferException.MalformedVarint(),
  133. Bytes(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,
  134. 0x00));
  135. AssertReadVarintFailure(
  136. InvalidProtocolBufferException.TruncatedMessage(),
  137. Bytes(0x80));
  138. }
  139. /// <summary>
  140. /// Parses the given bytes using ReadRawLittleEndian32() and checks
  141. /// that the result matches the given value.
  142. /// </summary>
  143. private static void AssertReadLittleEndian32(byte[] data, uint value)
  144. {
  145. CodedInputStream input = CodedInputStream.CreateInstance(data);
  146. Assert.Equal(value, input.ReadRawLittleEndian32());
  147. Assert.True(input.IsAtEnd);
  148. // Try different block sizes.
  149. for (int blockSize = 1; blockSize <= 16; blockSize *= 2)
  150. {
  151. input = CodedInputStream.CreateInstance(
  152. new SmallBlockInputStream(data, blockSize));
  153. Assert.Equal(value, input.ReadRawLittleEndian32());
  154. Assert.True(input.IsAtEnd);
  155. }
  156. }
  157. /// <summary>
  158. /// Parses the given bytes using ReadRawLittleEndian64() and checks
  159. /// that the result matches the given value.
  160. /// </summary>
  161. private static void AssertReadLittleEndian64(byte[] data, ulong value)
  162. {
  163. CodedInputStream input = CodedInputStream.CreateInstance(data);
  164. Assert.Equal(value, input.ReadRawLittleEndian64());
  165. Assert.True(input.IsAtEnd);
  166. // Try different block sizes.
  167. for (int blockSize = 1; blockSize <= 16; blockSize *= 2)
  168. {
  169. input = CodedInputStream.CreateInstance(
  170. new SmallBlockInputStream(data, blockSize));
  171. Assert.Equal(value, input.ReadRawLittleEndian64());
  172. Assert.True(input.IsAtEnd);
  173. }
  174. }
  175. [Fact]
  176. public void ReadLittleEndian()
  177. {
  178. AssertReadLittleEndian32(Bytes(0x78, 0x56, 0x34, 0x12), 0x12345678);
  179. AssertReadLittleEndian32(Bytes(0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef0);
  180. AssertReadLittleEndian64(Bytes(0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12),
  181. 0x123456789abcdef0L);
  182. AssertReadLittleEndian64(
  183. Bytes(0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef012345678UL);
  184. }
  185. [Fact]
  186. public void DecodeZigZag32()
  187. {
  188. Assert.Equal(0, CodedInputStream.DecodeZigZag32(0));
  189. Assert.Equal(-1, CodedInputStream.DecodeZigZag32(1));
  190. Assert.Equal(1, CodedInputStream.DecodeZigZag32(2));
  191. Assert.Equal(-2, CodedInputStream.DecodeZigZag32(3));
  192. Assert.Equal(0x3FFFFFFF, CodedInputStream.DecodeZigZag32(0x7FFFFFFE));
  193. Assert.Equal(unchecked((int) 0xC0000000), CodedInputStream.DecodeZigZag32(0x7FFFFFFF));
  194. Assert.Equal(0x7FFFFFFF, CodedInputStream.DecodeZigZag32(0xFFFFFFFE));
  195. Assert.Equal(unchecked((int) 0x80000000), CodedInputStream.DecodeZigZag32(0xFFFFFFFF));
  196. }
  197. [Fact]
  198. public void DecodeZigZag64()
  199. {
  200. Assert.Equal(0, CodedInputStream.DecodeZigZag64(0));
  201. Assert.Equal(-1, CodedInputStream.DecodeZigZag64(1));
  202. Assert.Equal(1, CodedInputStream.DecodeZigZag64(2));
  203. Assert.Equal(-2, CodedInputStream.DecodeZigZag64(3));
  204. Assert.Equal(0x000000003FFFFFFFL, CodedInputStream.DecodeZigZag64(0x000000007FFFFFFEL));
  205. Assert.Equal(unchecked((long) 0xFFFFFFFFC0000000L), CodedInputStream.DecodeZigZag64(0x000000007FFFFFFFL));
  206. Assert.Equal(0x000000007FFFFFFFL, CodedInputStream.DecodeZigZag64(0x00000000FFFFFFFEL));
  207. Assert.Equal(unchecked((long) 0xFFFFFFFF80000000L), CodedInputStream.DecodeZigZag64(0x00000000FFFFFFFFL));
  208. Assert.Equal(0x7FFFFFFFFFFFFFFFL, CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFEL));
  209. Assert.Equal(unchecked((long) 0x8000000000000000L), CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFFL));
  210. }
  211. [Fact]
  212. public void ReadWholeMessage()
  213. {
  214. TestAllTypes message = TestUtil.GetAllSet();
  215. byte[] rawBytes = message.ToByteArray();
  216. Assert.Equal(rawBytes.Length, message.SerializedSize);
  217. TestAllTypes message2 = TestAllTypes.ParseFrom(rawBytes);
  218. TestUtil.AssertAllFieldsSet(message2);
  219. // Try different block sizes.
  220. for (int blockSize = 1; blockSize < 256; blockSize *= 2)
  221. {
  222. message2 = TestAllTypes.ParseFrom(new SmallBlockInputStream(rawBytes, blockSize));
  223. TestUtil.AssertAllFieldsSet(message2);
  224. }
  225. }
  226. [Fact]
  227. public void SkipWholeMessage()
  228. {
  229. TestAllTypes message = TestUtil.GetAllSet();
  230. byte[] rawBytes = message.ToByteArray();
  231. // Create two parallel inputs. Parse one as unknown fields while using
  232. // skipField() to skip each field on the other. Expect the same tags.
  233. CodedInputStream input1 = CodedInputStream.CreateInstance(rawBytes);
  234. CodedInputStream input2 = CodedInputStream.CreateInstance(rawBytes);
  235. UnknownFieldSet.Builder unknownFields = UnknownFieldSet.CreateBuilder();
  236. uint tag;
  237. string name;
  238. while (input1.ReadTag(out tag, out name))
  239. {
  240. uint tag2;
  241. Assert.True(input2.ReadTag(out tag2, out name));
  242. Assert.Equal(tag, tag2);
  243. unknownFields.MergeFieldFrom(tag, input1);
  244. input2.SkipField();
  245. }
  246. }
  247. /// <summary>
  248. /// Test that a bug in SkipRawBytes has been fixed: if the skip
  249. /// skips exactly up to a limit, this should bnot break things
  250. /// </summary>
  251. [Fact]
  252. public void SkipRawBytesBug()
  253. {
  254. byte[] rawBytes = new byte[] {1, 2};
  255. CodedInputStream input = CodedInputStream.CreateInstance(rawBytes);
  256. int limit = input.PushLimit(1);
  257. input.SkipRawBytes(1);
  258. input.PopLimit(limit);
  259. Assert.Equal(2, input.ReadRawByte());
  260. }
  261. public void ReadHugeBlob()
  262. {
  263. // Allocate and initialize a 1MB blob.
  264. byte[] blob = new byte[1 << 20];
  265. for (int i = 0; i < blob.Length; i++)
  266. {
  267. blob[i] = (byte) i;
  268. }
  269. // Make a message containing it.
  270. TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
  271. TestUtil.SetAllFields(builder);
  272. builder.SetOptionalBytes(ByteString.CopyFrom(blob));
  273. TestAllTypes message = builder.Build();
  274. // Serialize and parse it. Make sure to parse from an InputStream, not
  275. // directly from a ByteString, so that CodedInputStream uses buffered
  276. // reading.
  277. TestAllTypes message2 = TestAllTypes.ParseFrom(message.ToByteString().CreateCodedInput());
  278. Assert.Equal(message.OptionalBytes, message2.OptionalBytes);
  279. // Make sure all the other fields were parsed correctly.
  280. TestAllTypes message3 = TestAllTypes.CreateBuilder(message2)
  281. .SetOptionalBytes(TestUtil.GetAllSet().OptionalBytes)
  282. .Build();
  283. TestUtil.AssertAllFieldsSet(message3);
  284. }
  285. [Fact]
  286. public void ReadMaliciouslyLargeBlob()
  287. {
  288. MemoryStream ms = new MemoryStream();
  289. CodedOutputStream output = CodedOutputStream.CreateInstance(ms);
  290. uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
  291. output.WriteRawVarint32(tag);
  292. output.WriteRawVarint32(0x7FFFFFFF);
  293. output.WriteRawBytes(new byte[32]); // Pad with a few random bytes.
  294. output.Flush();
  295. ms.Position = 0;
  296. CodedInputStream input = CodedInputStream.CreateInstance(ms);
  297. uint testtag;
  298. string ignore;
  299. Assert.True(input.ReadTag(out testtag, out ignore));
  300. Assert.Equal(tag, testtag);
  301. ByteString bytes = null;
  302. // TODO(jonskeet): Should this be ArgumentNullException instead?
  303. Assert.Throws<InvalidProtocolBufferException>(() => input.ReadBytes(ref bytes));
  304. }
  305. private static TestRecursiveMessage MakeRecursiveMessage(int depth)
  306. {
  307. if (depth == 0)
  308. {
  309. return TestRecursiveMessage.CreateBuilder().SetI(5).Build();
  310. }
  311. else
  312. {
  313. return TestRecursiveMessage.CreateBuilder()
  314. .SetA(MakeRecursiveMessage(depth - 1)).Build();
  315. }
  316. }
  317. private static void AssertMessageDepth(TestRecursiveMessage message, int depth)
  318. {
  319. if (depth == 0)
  320. {
  321. Assert.False(message.HasA);
  322. Assert.Equal(5, message.I);
  323. }
  324. else
  325. {
  326. Assert.True(message.HasA);
  327. AssertMessageDepth(message.A, depth - 1);
  328. }
  329. }
  330. [Fact]
  331. public void MaliciousRecursion()
  332. {
  333. ByteString data64 = MakeRecursiveMessage(64).ToByteString();
  334. ByteString data65 = MakeRecursiveMessage(65).ToByteString();
  335. AssertMessageDepth(TestRecursiveMessage.ParseFrom(data64), 64);
  336. Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.ParseFrom(data65));
  337. CodedInputStream input = data64.CreateCodedInput();
  338. input.SetRecursionLimit(8);
  339. Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.ParseFrom(input));
  340. }
  341. [Fact]
  342. public void SizeLimit()
  343. {
  344. // Have to use a Stream rather than ByteString.CreateCodedInput as SizeLimit doesn't
  345. // apply to the latter case.
  346. MemoryStream ms = new MemoryStream(TestUtil.GetAllSet().ToByteString().ToByteArray());
  347. CodedInputStream input = CodedInputStream.CreateInstance(ms);
  348. input.SetSizeLimit(16);
  349. Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.ParseFrom(input));
  350. }
  351. [Fact]
  352. public void ResetSizeCounter()
  353. {
  354. CodedInputStream input = CodedInputStream.CreateInstance(
  355. new SmallBlockInputStream(new byte[256], 8));
  356. input.SetSizeLimit(16);
  357. input.ReadRawBytes(16);
  358. Assert.Throws<InvalidProtocolBufferException>(() => input.ReadRawByte());
  359. input.ResetSizeCounter();
  360. input.ReadRawByte(); // No exception thrown.
  361. Assert.Throws<InvalidProtocolBufferException>(() => input.ReadRawBytes(16));
  362. }
  363. /// <summary>
  364. /// Tests that if we read an string that contains invalid UTF-8, no exception
  365. /// is thrown. Instead, the invalid bytes are replaced with the Unicode
  366. /// "replacement character" U+FFFD.
  367. /// </summary>
  368. [Fact]
  369. public void ReadInvalidUtf8()
  370. {
  371. MemoryStream ms = new MemoryStream();
  372. CodedOutputStream output = CodedOutputStream.CreateInstance(ms);
  373. uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
  374. output.WriteRawVarint32(tag);
  375. output.WriteRawVarint32(1);
  376. output.WriteRawBytes(new byte[] {0x80});
  377. output.Flush();
  378. ms.Position = 0;
  379. CodedInputStream input = CodedInputStream.CreateInstance(ms);
  380. uint testtag;
  381. string ignored;
  382. Assert.True(input.ReadTag(out testtag, out ignored));
  383. Assert.Equal(tag, testtag);
  384. string text = null;
  385. input.ReadString(ref text);
  386. Assert.Equal('\ufffd', text[0]);
  387. }
  388. /// <summary>
  389. /// A stream which limits the number of bytes it reads at a time.
  390. /// We use this to make sure that CodedInputStream doesn't screw up when
  391. /// reading in small blocks.
  392. /// </summary>
  393. private sealed class SmallBlockInputStream : MemoryStream
  394. {
  395. private readonly int blockSize;
  396. public SmallBlockInputStream(byte[] data, int blockSize)
  397. : base(data)
  398. {
  399. this.blockSize = blockSize;
  400. }
  401. public override int Read(byte[] buffer, int offset, int count)
  402. {
  403. return base.Read(buffer, offset, Math.Min(count, blockSize));
  404. }
  405. }
  406. enum TestNegEnum { None = 0, Value = -2 }
  407. [Fact]
  408. public void TestNegativeEnum()
  409. {
  410. byte[] bytes = new byte[10] { 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01 };
  411. CodedInputStream input = CodedInputStream.CreateInstance(bytes);
  412. object unk;
  413. TestNegEnum val = TestNegEnum.None;
  414. Assert.True(input.ReadEnum(ref val, out unk));
  415. Assert.True(input.IsAtEnd);
  416. Assert.Equal(TestNegEnum.Value, val);
  417. }
  418. [Fact]
  419. public void TestNegativeEnumPackedArray()
  420. {
  421. int arraySize = 1 + (10 * 5);
  422. int msgSize = 1 + 1 + arraySize;
  423. byte[] bytes = new byte[msgSize];
  424. CodedOutputStream output = CodedOutputStream.CreateInstance(bytes);
  425. output.WritePackedInt32Array(8, "", arraySize, new int[] { 0, -1, -2, -3, -4, -5 });
  426. Assert.Equal(0, output.SpaceLeft);
  427. CodedInputStream input = CodedInputStream.CreateInstance(bytes);
  428. uint tag;
  429. string name;
  430. Assert.True(input.ReadTag(out tag, out name));
  431. List<TestNegEnum> values = new List<TestNegEnum>();
  432. ICollection<object> unk;
  433. input.ReadEnumArray(tag, name, values, out unk);
  434. Assert.Equal(2, values.Count);
  435. Assert.Equal(TestNegEnum.None, values[0]);
  436. Assert.Equal(TestNegEnum.Value, values[1]);
  437. Assert.NotNull(unk);
  438. Assert.Equal(4, unk.Count);
  439. }
  440. [Fact]
  441. public void TestNegativeEnumArray()
  442. {
  443. int arraySize = 1 + 1 + (11 * 5);
  444. int msgSize = arraySize;
  445. byte[] bytes = new byte[msgSize];
  446. CodedOutputStream output = CodedOutputStream.CreateInstance(bytes);
  447. output.WriteInt32Array(8, "", new int[] { 0, -1, -2, -3, -4, -5 });
  448. Assert.Equal(0, output.SpaceLeft);
  449. CodedInputStream input = CodedInputStream.CreateInstance(bytes);
  450. uint tag;
  451. string name;
  452. Assert.True(input.ReadTag(out tag, out name));
  453. List<TestNegEnum> values = new List<TestNegEnum>();
  454. ICollection<object> unk;
  455. input.ReadEnumArray(tag, name, values, out unk);
  456. Assert.Equal(2, values.Count);
  457. Assert.Equal(TestNegEnum.None, values[0]);
  458. Assert.Equal(TestNegEnum.Value, values[1]);
  459. Assert.NotNull(unk);
  460. Assert.Equal(4, unk.Count);
  461. }
  462. //Issue 71: CodedInputStream.ReadBytes go to slow path unnecessarily
  463. [Fact]
  464. public void TestSlowPathAvoidance()
  465. {
  466. using (var ms = new MemoryStream())
  467. {
  468. CodedOutputStream output = CodedOutputStream.CreateInstance(ms);
  469. output.WriteField(FieldType.Bytes, 1, "bytes", ByteString.CopyFrom(new byte[100]));
  470. output.WriteField(FieldType.Bytes, 2, "bytes", ByteString.CopyFrom(new byte[100]));
  471. output.Flush();
  472. ms.Position = 0;
  473. CodedInputStream input = CodedInputStream.CreateInstance(ms, new byte[ms.Length / 2]);
  474. uint tag;
  475. string ignore;
  476. ByteString value;
  477. Assert.True(input.ReadTag(out tag, out ignore));
  478. Assert.Equal(1, WireFormat.GetTagFieldNumber(tag));
  479. value = ByteString.Empty;
  480. Assert.True(input.ReadBytes(ref value) && value.Length == 100);
  481. Assert.True(input.ReadTag(out tag, out ignore));
  482. Assert.Equal(2, WireFormat.GetTagFieldNumber(tag));
  483. value = ByteString.Empty;
  484. Assert.True(input.ReadBytes(ref value) && value.Length == 100);
  485. }
  486. }
  487. }
  488. }