CodedInputStreamTest.cs 24 KB

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