diff options
Diffstat (limited to 'third_party/protobuf/3.4.0/csharp/compatibility_tests/v3.0.0/src')
7 files changed, 2106 insertions, 2106 deletions
diff --git a/third_party/protobuf/3.4.0/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/ByteStringTest.cs b/third_party/protobuf/3.4.0/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/ByteStringTest.cs index 685e130a74..8935b7829d 100644 --- a/third_party/protobuf/3.4.0/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/ByteStringTest.cs +++ b/third_party/protobuf/3.4.0/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/ByteStringTest.cs @@ -1,171 +1,171 @@ -#region Copyright notice and license
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-#endregion
-
-using System;
-using System.Text;
-using NUnit.Framework;
-
-namespace Google.Protobuf
-{
- public class ByteStringTest
- {
- [Test]
- public void Equality()
- {
- ByteString b1 = ByteString.CopyFrom(1, 2, 3);
- ByteString b2 = ByteString.CopyFrom(1, 2, 3);
- ByteString b3 = ByteString.CopyFrom(1, 2, 4);
- ByteString b4 = ByteString.CopyFrom(1, 2, 3, 4);
- EqualityTester.AssertEquality(b1, b1);
- EqualityTester.AssertEquality(b1, b2);
- EqualityTester.AssertInequality(b1, b3);
- EqualityTester.AssertInequality(b1, b4);
- EqualityTester.AssertInequality(b1, null);
-#pragma warning disable 1718 // Deliberately calling ==(b1, b1) and !=(b1, b1)
- Assert.IsTrue(b1 == b1);
- Assert.IsTrue(b1 == b2);
- Assert.IsFalse(b1 == b3);
- Assert.IsFalse(b1 == b4);
- Assert.IsFalse(b1 == null);
- Assert.IsTrue((ByteString) null == null);
- Assert.IsFalse(b1 != b1);
- Assert.IsFalse(b1 != b2);
-#pragma warning disable 1718
- Assert.IsTrue(b1 != b3);
- Assert.IsTrue(b1 != b4);
- Assert.IsTrue(b1 != null);
- Assert.IsFalse((ByteString) null != null);
- }
-
- [Test]
- public void EmptyByteStringHasZeroSize()
- {
- Assert.AreEqual(0, ByteString.Empty.Length);
- }
-
- [Test]
- public void CopyFromStringWithExplicitEncoding()
- {
- ByteString bs = ByteString.CopyFrom("AB", Encoding.Unicode);
- Assert.AreEqual(4, bs.Length);
- Assert.AreEqual(65, bs[0]);
- Assert.AreEqual(0, bs[1]);
- Assert.AreEqual(66, bs[2]);
- Assert.AreEqual(0, bs[3]);
- }
-
- [Test]
- public void IsEmptyWhenEmpty()
- {
- Assert.IsTrue(ByteString.CopyFromUtf8("").IsEmpty);
- }
-
- [Test]
- public void IsEmptyWhenNotEmpty()
- {
- Assert.IsFalse(ByteString.CopyFromUtf8("X").IsEmpty);
- }
-
- [Test]
- public void CopyFromByteArrayCopiesContents()
- {
- byte[] data = new byte[1];
- data[0] = 10;
- ByteString bs = ByteString.CopyFrom(data);
- Assert.AreEqual(10, bs[0]);
- data[0] = 5;
- Assert.AreEqual(10, bs[0]);
- }
-
- [Test]
- public void ToByteArrayCopiesContents()
- {
- ByteString bs = ByteString.CopyFromUtf8("Hello");
- byte[] data = bs.ToByteArray();
- Assert.AreEqual((byte)'H', data[0]);
- Assert.AreEqual((byte)'H', bs[0]);
- data[0] = 0;
- Assert.AreEqual(0, data[0]);
- Assert.AreEqual((byte)'H', bs[0]);
- }
-
- [Test]
- public void CopyFromUtf8UsesUtf8()
- {
- ByteString bs = ByteString.CopyFromUtf8("\u20ac");
- Assert.AreEqual(3, bs.Length);
- Assert.AreEqual(0xe2, bs[0]);
- Assert.AreEqual(0x82, bs[1]);
- Assert.AreEqual(0xac, bs[2]);
- }
-
- [Test]
- public void CopyFromPortion()
- {
- byte[] data = new byte[] {0, 1, 2, 3, 4, 5, 6};
- ByteString bs = ByteString.CopyFrom(data, 2, 3);
- Assert.AreEqual(3, bs.Length);
- Assert.AreEqual(2, bs[0]);
- Assert.AreEqual(3, bs[1]);
- }
-
- [Test]
- public void ToStringUtf8()
- {
- ByteString bs = ByteString.CopyFromUtf8("\u20ac");
- Assert.AreEqual("\u20ac", bs.ToStringUtf8());
- }
-
- [Test]
- public void ToStringWithExplicitEncoding()
- {
- ByteString bs = ByteString.CopyFrom("\u20ac", Encoding.Unicode);
- Assert.AreEqual("\u20ac", bs.ToString(Encoding.Unicode));
- }
-
- [Test]
- public void FromBase64_WithText()
- {
- byte[] data = new byte[] {0, 1, 2, 3, 4, 5, 6};
- string base64 = Convert.ToBase64String(data);
- ByteString bs = ByteString.FromBase64(base64);
- Assert.AreEqual(data, bs.ToByteArray());
- }
-
- [Test]
- public void FromBase64_Empty()
- {
- // Optimization which also fixes issue 61.
- Assert.AreSame(ByteString.Empty, ByteString.FromBase64(""));
- }
- }
+#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + +using System; +using System.Text; +using NUnit.Framework; + +namespace Google.Protobuf +{ + public class ByteStringTest + { + [Test] + public void Equality() + { + ByteString b1 = ByteString.CopyFrom(1, 2, 3); + ByteString b2 = ByteString.CopyFrom(1, 2, 3); + ByteString b3 = ByteString.CopyFrom(1, 2, 4); + ByteString b4 = ByteString.CopyFrom(1, 2, 3, 4); + EqualityTester.AssertEquality(b1, b1); + EqualityTester.AssertEquality(b1, b2); + EqualityTester.AssertInequality(b1, b3); + EqualityTester.AssertInequality(b1, b4); + EqualityTester.AssertInequality(b1, null); +#pragma warning disable 1718 // Deliberately calling ==(b1, b1) and !=(b1, b1) + Assert.IsTrue(b1 == b1); + Assert.IsTrue(b1 == b2); + Assert.IsFalse(b1 == b3); + Assert.IsFalse(b1 == b4); + Assert.IsFalse(b1 == null); + Assert.IsTrue((ByteString) null == null); + Assert.IsFalse(b1 != b1); + Assert.IsFalse(b1 != b2); +#pragma warning disable 1718 + Assert.IsTrue(b1 != b3); + Assert.IsTrue(b1 != b4); + Assert.IsTrue(b1 != null); + Assert.IsFalse((ByteString) null != null); + } + + [Test] + public void EmptyByteStringHasZeroSize() + { + Assert.AreEqual(0, ByteString.Empty.Length); + } + + [Test] + public void CopyFromStringWithExplicitEncoding() + { + ByteString bs = ByteString.CopyFrom("AB", Encoding.Unicode); + Assert.AreEqual(4, bs.Length); + Assert.AreEqual(65, bs[0]); + Assert.AreEqual(0, bs[1]); + Assert.AreEqual(66, bs[2]); + Assert.AreEqual(0, bs[3]); + } + + [Test] + public void IsEmptyWhenEmpty() + { + Assert.IsTrue(ByteString.CopyFromUtf8("").IsEmpty); + } + + [Test] + public void IsEmptyWhenNotEmpty() + { + Assert.IsFalse(ByteString.CopyFromUtf8("X").IsEmpty); + } + + [Test] + public void CopyFromByteArrayCopiesContents() + { + byte[] data = new byte[1]; + data[0] = 10; + ByteString bs = ByteString.CopyFrom(data); + Assert.AreEqual(10, bs[0]); + data[0] = 5; + Assert.AreEqual(10, bs[0]); + } + + [Test] + public void ToByteArrayCopiesContents() + { + ByteString bs = ByteString.CopyFromUtf8("Hello"); + byte[] data = bs.ToByteArray(); + Assert.AreEqual((byte)'H', data[0]); + Assert.AreEqual((byte)'H', bs[0]); + data[0] = 0; + Assert.AreEqual(0, data[0]); + Assert.AreEqual((byte)'H', bs[0]); + } + + [Test] + public void CopyFromUtf8UsesUtf8() + { + ByteString bs = ByteString.CopyFromUtf8("\u20ac"); + Assert.AreEqual(3, bs.Length); + Assert.AreEqual(0xe2, bs[0]); + Assert.AreEqual(0x82, bs[1]); + Assert.AreEqual(0xac, bs[2]); + } + + [Test] + public void CopyFromPortion() + { + byte[] data = new byte[] {0, 1, 2, 3, 4, 5, 6}; + ByteString bs = ByteString.CopyFrom(data, 2, 3); + Assert.AreEqual(3, bs.Length); + Assert.AreEqual(2, bs[0]); + Assert.AreEqual(3, bs[1]); + } + + [Test] + public void ToStringUtf8() + { + ByteString bs = ByteString.CopyFromUtf8("\u20ac"); + Assert.AreEqual("\u20ac", bs.ToStringUtf8()); + } + + [Test] + public void ToStringWithExplicitEncoding() + { + ByteString bs = ByteString.CopyFrom("\u20ac", Encoding.Unicode); + Assert.AreEqual("\u20ac", bs.ToString(Encoding.Unicode)); + } + + [Test] + public void FromBase64_WithText() + { + byte[] data = new byte[] {0, 1, 2, 3, 4, 5, 6}; + string base64 = Convert.ToBase64String(data); + ByteString bs = ByteString.FromBase64(base64); + Assert.AreEqual(data, bs.ToByteArray()); + } + + [Test] + public void FromBase64_Empty() + { + // Optimization which also fixes issue 61. + Assert.AreSame(ByteString.Empty, ByteString.FromBase64("")); + } + } }
\ No newline at end of file diff --git a/third_party/protobuf/3.4.0/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/CodedInputStreamTest.cs b/third_party/protobuf/3.4.0/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/CodedInputStreamTest.cs index ff44895c06..db0a180949 100644 --- a/third_party/protobuf/3.4.0/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/CodedInputStreamTest.cs +++ b/third_party/protobuf/3.4.0/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/CodedInputStreamTest.cs @@ -1,598 +1,598 @@ -#region Copyright notice and license
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-#endregion
-
-using System;
-using System.IO;
-using Google.Protobuf.TestProtos;
-using NUnit.Framework;
-
-namespace Google.Protobuf
-{
- public class CodedInputStreamTest
- {
- /// <summary>
- /// Helper to construct a byte array from a bunch of bytes. The inputs are
- /// actually ints so that I can use hex notation and not get stupid errors
- /// about precision.
- /// </summary>
- private static byte[] Bytes(params int[] bytesAsInts)
- {
- byte[] bytes = new byte[bytesAsInts.Length];
- for (int i = 0; i < bytesAsInts.Length; i++)
- {
- bytes[i] = (byte) bytesAsInts[i];
- }
- return bytes;
- }
-
- /// <summary>
- /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64()
- /// </summary>
- private static void AssertReadVarint(byte[] data, ulong value)
- {
- CodedInputStream input = new CodedInputStream(data);
- Assert.AreEqual((uint) value, input.ReadRawVarint32());
-
- input = new CodedInputStream(data);
- Assert.AreEqual(value, input.ReadRawVarint64());
- Assert.IsTrue(input.IsAtEnd);
-
- // Try different block sizes.
- for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2)
- {
- input = new CodedInputStream(new SmallBlockInputStream(data, bufferSize));
- Assert.AreEqual((uint) value, input.ReadRawVarint32());
-
- input = new CodedInputStream(new SmallBlockInputStream(data, bufferSize));
- Assert.AreEqual(value, input.ReadRawVarint64());
- Assert.IsTrue(input.IsAtEnd);
- }
-
- // Try reading directly from a MemoryStream. We want to verify that it
- // doesn't read past the end of the input, so write an extra byte - this
- // lets us test the position at the end.
- MemoryStream memoryStream = new MemoryStream();
- memoryStream.Write(data, 0, data.Length);
- memoryStream.WriteByte(0);
- memoryStream.Position = 0;
- Assert.AreEqual((uint) value, CodedInputStream.ReadRawVarint32(memoryStream));
- Assert.AreEqual(data.Length, memoryStream.Position);
- }
-
- /// <summary>
- /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() and
- /// expects them to fail with an InvalidProtocolBufferException whose
- /// description matches the given one.
- /// </summary>
- private static void AssertReadVarintFailure(InvalidProtocolBufferException expected, byte[] data)
- {
- CodedInputStream input = new CodedInputStream(data);
- var exception = Assert.Throws<InvalidProtocolBufferException>(() => input.ReadRawVarint32());
- Assert.AreEqual(expected.Message, exception.Message);
-
- input = new CodedInputStream(data);
- exception = Assert.Throws<InvalidProtocolBufferException>(() => input.ReadRawVarint64());
- Assert.AreEqual(expected.Message, exception.Message);
-
- // Make sure we get the same error when reading directly from a Stream.
- exception = Assert.Throws<InvalidProtocolBufferException>(() => CodedInputStream.ReadRawVarint32(new MemoryStream(data)));
- Assert.AreEqual(expected.Message, exception.Message);
- }
-
- [Test]
- public void ReadVarint()
- {
- AssertReadVarint(Bytes(0x00), 0);
- AssertReadVarint(Bytes(0x01), 1);
- AssertReadVarint(Bytes(0x7f), 127);
- // 14882
- AssertReadVarint(Bytes(0xa2, 0x74), (0x22 << 0) | (0x74 << 7));
- // 2961488830
- AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x0b),
- (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
- (0x0bL << 28));
-
- // 64-bit
- // 7256456126
- AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x1b),
- (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
- (0x1bL << 28));
- // 41256202580718336
- AssertReadVarint(Bytes(0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49),
- (0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) |
- (0x43L << 28) | (0x49L << 35) | (0x24L << 42) | (0x49L << 49));
- // 11964378330978735131
- AssertReadVarint(Bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01),
- (0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) |
- (0x3bUL << 28) | (0x56UL << 35) | (0x00UL << 42) |
- (0x05UL << 49) | (0x26UL << 56) | (0x01UL << 63));
-
- // Failures
- AssertReadVarintFailure(
- InvalidProtocolBufferException.MalformedVarint(),
- Bytes(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,
- 0x00));
- AssertReadVarintFailure(
- InvalidProtocolBufferException.TruncatedMessage(),
- Bytes(0x80));
- }
-
- /// <summary>
- /// Parses the given bytes using ReadRawLittleEndian32() and checks
- /// that the result matches the given value.
- /// </summary>
- private static void AssertReadLittleEndian32(byte[] data, uint value)
- {
- CodedInputStream input = new CodedInputStream(data);
- Assert.AreEqual(value, input.ReadRawLittleEndian32());
- Assert.IsTrue(input.IsAtEnd);
-
- // Try different block sizes.
- for (int blockSize = 1; blockSize <= 16; blockSize *= 2)
- {
- input = new CodedInputStream(
- new SmallBlockInputStream(data, blockSize));
- Assert.AreEqual(value, input.ReadRawLittleEndian32());
- Assert.IsTrue(input.IsAtEnd);
- }
- }
-
- /// <summary>
- /// Parses the given bytes using ReadRawLittleEndian64() and checks
- /// that the result matches the given value.
- /// </summary>
- private static void AssertReadLittleEndian64(byte[] data, ulong value)
- {
- CodedInputStream input = new CodedInputStream(data);
- Assert.AreEqual(value, input.ReadRawLittleEndian64());
- Assert.IsTrue(input.IsAtEnd);
-
- // Try different block sizes.
- for (int blockSize = 1; blockSize <= 16; blockSize *= 2)
- {
- input = new CodedInputStream(
- new SmallBlockInputStream(data, blockSize));
- Assert.AreEqual(value, input.ReadRawLittleEndian64());
- Assert.IsTrue(input.IsAtEnd);
- }
- }
-
- [Test]
- public void ReadLittleEndian()
- {
- AssertReadLittleEndian32(Bytes(0x78, 0x56, 0x34, 0x12), 0x12345678);
- AssertReadLittleEndian32(Bytes(0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef0);
-
- AssertReadLittleEndian64(Bytes(0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12),
- 0x123456789abcdef0L);
- AssertReadLittleEndian64(
- Bytes(0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef012345678UL);
- }
-
- [Test]
- public void DecodeZigZag32()
- {
- Assert.AreEqual(0, CodedInputStream.DecodeZigZag32(0));
- Assert.AreEqual(-1, CodedInputStream.DecodeZigZag32(1));
- Assert.AreEqual(1, CodedInputStream.DecodeZigZag32(2));
- Assert.AreEqual(-2, CodedInputStream.DecodeZigZag32(3));
- Assert.AreEqual(0x3FFFFFFF, CodedInputStream.DecodeZigZag32(0x7FFFFFFE));
- Assert.AreEqual(unchecked((int) 0xC0000000), CodedInputStream.DecodeZigZag32(0x7FFFFFFF));
- Assert.AreEqual(0x7FFFFFFF, CodedInputStream.DecodeZigZag32(0xFFFFFFFE));
- Assert.AreEqual(unchecked((int) 0x80000000), CodedInputStream.DecodeZigZag32(0xFFFFFFFF));
- }
-
- [Test]
- public void DecodeZigZag64()
- {
- Assert.AreEqual(0, CodedInputStream.DecodeZigZag64(0));
- Assert.AreEqual(-1, CodedInputStream.DecodeZigZag64(1));
- Assert.AreEqual(1, CodedInputStream.DecodeZigZag64(2));
- Assert.AreEqual(-2, CodedInputStream.DecodeZigZag64(3));
- Assert.AreEqual(0x000000003FFFFFFFL, CodedInputStream.DecodeZigZag64(0x000000007FFFFFFEL));
- Assert.AreEqual(unchecked((long) 0xFFFFFFFFC0000000L), CodedInputStream.DecodeZigZag64(0x000000007FFFFFFFL));
- Assert.AreEqual(0x000000007FFFFFFFL, CodedInputStream.DecodeZigZag64(0x00000000FFFFFFFEL));
- Assert.AreEqual(unchecked((long) 0xFFFFFFFF80000000L), CodedInputStream.DecodeZigZag64(0x00000000FFFFFFFFL));
- Assert.AreEqual(0x7FFFFFFFFFFFFFFFL, CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFEL));
- Assert.AreEqual(unchecked((long) 0x8000000000000000L), CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFFL));
- }
-
- [Test]
- public void ReadWholeMessage_VaryingBlockSizes()
- {
- TestAllTypes message = SampleMessages.CreateFullTestAllTypes();
-
- byte[] rawBytes = message.ToByteArray();
- Assert.AreEqual(rawBytes.Length, message.CalculateSize());
- TestAllTypes message2 = TestAllTypes.Parser.ParseFrom(rawBytes);
- Assert.AreEqual(message, message2);
-
- // Try different block sizes.
- for (int blockSize = 1; blockSize < 256; blockSize *= 2)
- {
- message2 = TestAllTypes.Parser.ParseFrom(new SmallBlockInputStream(rawBytes, blockSize));
- Assert.AreEqual(message, message2);
- }
- }
-
- [Test]
- public void ReadHugeBlob()
- {
- // Allocate and initialize a 1MB blob.
- byte[] blob = new byte[1 << 20];
- for (int i = 0; i < blob.Length; i++)
- {
- blob[i] = (byte) i;
- }
-
- // Make a message containing it.
- var message = new TestAllTypes { SingleBytes = ByteString.CopyFrom(blob) };
-
- // Serialize and parse it. Make sure to parse from an InputStream, not
- // directly from a ByteString, so that CodedInputStream uses buffered
- // reading.
- TestAllTypes message2 = TestAllTypes.Parser.ParseFrom(message.ToByteString());
-
- Assert.AreEqual(message, message2);
- }
-
- [Test]
- public void ReadMaliciouslyLargeBlob()
- {
- MemoryStream ms = new MemoryStream();
- CodedOutputStream output = new CodedOutputStream(ms);
-
- uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
- output.WriteRawVarint32(tag);
- output.WriteRawVarint32(0x7FFFFFFF);
- output.WriteRawBytes(new byte[32]); // Pad with a few random bytes.
- output.Flush();
- ms.Position = 0;
-
- CodedInputStream input = new CodedInputStream(ms);
- Assert.AreEqual(tag, input.ReadTag());
-
- Assert.Throws<InvalidProtocolBufferException>(() => input.ReadBytes());
- }
-
- internal static TestRecursiveMessage MakeRecursiveMessage(int depth)
- {
- if (depth == 0)
- {
- return new TestRecursiveMessage { I = 5 };
- }
- else
- {
- return new TestRecursiveMessage { A = MakeRecursiveMessage(depth - 1) };
- }
- }
-
- internal static void AssertMessageDepth(TestRecursiveMessage message, int depth)
- {
- if (depth == 0)
- {
- Assert.IsNull(message.A);
- Assert.AreEqual(5, message.I);
- }
- else
- {
- Assert.IsNotNull(message.A);
- AssertMessageDepth(message.A, depth - 1);
- }
- }
-
- [Test]
- public void MaliciousRecursion()
- {
- ByteString data64 = MakeRecursiveMessage(64).ToByteString();
- ByteString data65 = MakeRecursiveMessage(65).ToByteString();
-
- AssertMessageDepth(TestRecursiveMessage.Parser.ParseFrom(data64), 64);
-
- Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(data65));
-
- CodedInputStream input = CodedInputStream.CreateWithLimits(new MemoryStream(data64.ToByteArray()), 1000000, 63);
- Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(input));
- }
-
- [Test]
- public void SizeLimit()
- {
- // Have to use a Stream rather than ByteString.CreateCodedInput as SizeLimit doesn't
- // apply to the latter case.
- MemoryStream ms = new MemoryStream(SampleMessages.CreateFullTestAllTypes().ToByteArray());
- CodedInputStream input = CodedInputStream.CreateWithLimits(ms, 16, 100);
- Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseFrom(input));
- }
-
- /// <summary>
- /// Tests that if we read an string that contains invalid UTF-8, no exception
- /// is thrown. Instead, the invalid bytes are replaced with the Unicode
- /// "replacement character" U+FFFD.
- /// </summary>
- [Test]
- public void ReadInvalidUtf8()
- {
- MemoryStream ms = new MemoryStream();
- CodedOutputStream output = new CodedOutputStream(ms);
-
- uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
- output.WriteRawVarint32(tag);
- output.WriteRawVarint32(1);
- output.WriteRawBytes(new byte[] {0x80});
- output.Flush();
- ms.Position = 0;
-
- CodedInputStream input = new CodedInputStream(ms);
-
- Assert.AreEqual(tag, input.ReadTag());
- string text = input.ReadString();
- Assert.AreEqual('\ufffd', text[0]);
- }
-
- /// <summary>
- /// A stream which limits the number of bytes it reads at a time.
- /// We use this to make sure that CodedInputStream doesn't screw up when
- /// reading in small blocks.
- /// </summary>
- private sealed class SmallBlockInputStream : MemoryStream
- {
- private readonly int blockSize;
-
- public SmallBlockInputStream(byte[] data, int blockSize)
- : base(data)
- {
- this.blockSize = blockSize;
- }
-
- public override int Read(byte[] buffer, int offset, int count)
- {
- return base.Read(buffer, offset, Math.Min(count, blockSize));
- }
- }
-
- [Test]
- public void TestNegativeEnum()
- {
- byte[] bytes = { 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01 };
- CodedInputStream input = new CodedInputStream(bytes);
- Assert.AreEqual((int)SampleEnum.NegativeValue, input.ReadEnum());
- Assert.IsTrue(input.IsAtEnd);
- }
-
- //Issue 71: CodedInputStream.ReadBytes go to slow path unnecessarily
- [Test]
- public void TestSlowPathAvoidance()
- {
- using (var ms = new MemoryStream())
- {
- CodedOutputStream output = new CodedOutputStream(ms);
- output.WriteTag(1, WireFormat.WireType.LengthDelimited);
- output.WriteBytes(ByteString.CopyFrom(new byte[100]));
- output.WriteTag(2, WireFormat.WireType.LengthDelimited);
- output.WriteBytes(ByteString.CopyFrom(new byte[100]));
- output.Flush();
-
- ms.Position = 0;
- CodedInputStream input = new CodedInputStream(ms, new byte[ms.Length / 2], 0, 0, false);
-
- uint tag = input.ReadTag();
- Assert.AreEqual(1, WireFormat.GetTagFieldNumber(tag));
- Assert.AreEqual(100, input.ReadBytes().Length);
-
- tag = input.ReadTag();
- Assert.AreEqual(2, WireFormat.GetTagFieldNumber(tag));
- Assert.AreEqual(100, input.ReadBytes().Length);
- }
- }
-
- [Test]
- public void Tag0Throws()
- {
- var input = new CodedInputStream(new byte[] { 0 });
- Assert.Throws<InvalidProtocolBufferException>(() => input.ReadTag());
- }
-
- [Test]
- public void SkipGroup()
- {
- // Create an output stream with a group in:
- // Field 1: string "field 1"
- // Field 2: group containing:
- // Field 1: fixed int32 value 100
- // Field 2: string "ignore me"
- // Field 3: nested group containing
- // Field 1: fixed int64 value 1000
- // Field 3: string "field 3"
- var stream = new MemoryStream();
- var output = new CodedOutputStream(stream);
- output.WriteTag(1, WireFormat.WireType.LengthDelimited);
- output.WriteString("field 1");
-
- // The outer group...
- output.WriteTag(2, WireFormat.WireType.StartGroup);
- output.WriteTag(1, WireFormat.WireType.Fixed32);
- output.WriteFixed32(100);
- output.WriteTag(2, WireFormat.WireType.LengthDelimited);
- output.WriteString("ignore me");
- // The nested group...
- output.WriteTag(3, WireFormat.WireType.StartGroup);
- output.WriteTag(1, WireFormat.WireType.Fixed64);
- output.WriteFixed64(1000);
- // Note: Not sure the field number is relevant for end group...
- output.WriteTag(3, WireFormat.WireType.EndGroup);
-
- // End the outer group
- output.WriteTag(2, WireFormat.WireType.EndGroup);
-
- output.WriteTag(3, WireFormat.WireType.LengthDelimited);
- output.WriteString("field 3");
- output.Flush();
- stream.Position = 0;
-
- // Now act like a generated client
- var input = new CodedInputStream(stream);
- Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited), input.ReadTag());
- Assert.AreEqual("field 1", input.ReadString());
- Assert.AreEqual(WireFormat.MakeTag(2, WireFormat.WireType.StartGroup), input.ReadTag());
- input.SkipLastField(); // Should consume the whole group, including the nested one.
- Assert.AreEqual(WireFormat.MakeTag(3, WireFormat.WireType.LengthDelimited), input.ReadTag());
- Assert.AreEqual("field 3", input.ReadString());
- }
-
- [Test]
- public void SkipGroup_WrongEndGroupTag()
- {
- // Create an output stream with:
- // Field 1: string "field 1"
- // Start group 2
- // Field 3: fixed int32
- // End group 4 (should give an error)
- var stream = new MemoryStream();
- var output = new CodedOutputStream(stream);
- output.WriteTag(1, WireFormat.WireType.LengthDelimited);
- output.WriteString("field 1");
-
- // The outer group...
- output.WriteTag(2, WireFormat.WireType.StartGroup);
- output.WriteTag(3, WireFormat.WireType.Fixed32);
- output.WriteFixed32(100);
- output.WriteTag(4, WireFormat.WireType.EndGroup);
- output.Flush();
- stream.Position = 0;
-
- // Now act like a generated client
- var input = new CodedInputStream(stream);
- Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited), input.ReadTag());
- Assert.AreEqual("field 1", input.ReadString());
- Assert.AreEqual(WireFormat.MakeTag(2, WireFormat.WireType.StartGroup), input.ReadTag());
- Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField);
- }
-
- [Test]
- public void RogueEndGroupTag()
- {
- // If we have an end-group tag without a leading start-group tag, generated
- // code will just call SkipLastField... so that should fail.
-
- var stream = new MemoryStream();
- var output = new CodedOutputStream(stream);
- output.WriteTag(1, WireFormat.WireType.EndGroup);
- output.Flush();
- stream.Position = 0;
-
- var input = new CodedInputStream(stream);
- Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.EndGroup), input.ReadTag());
- Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField);
- }
-
- [Test]
- public void EndOfStreamReachedWhileSkippingGroup()
- {
- var stream = new MemoryStream();
- var output = new CodedOutputStream(stream);
- output.WriteTag(1, WireFormat.WireType.StartGroup);
- output.WriteTag(2, WireFormat.WireType.StartGroup);
- output.WriteTag(2, WireFormat.WireType.EndGroup);
-
- output.Flush();
- stream.Position = 0;
-
- // Now act like a generated client
- var input = new CodedInputStream(stream);
- input.ReadTag();
- Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField);
- }
-
- [Test]
- public void RecursionLimitAppliedWhileSkippingGroup()
- {
- var stream = new MemoryStream();
- var output = new CodedOutputStream(stream);
- for (int i = 0; i < CodedInputStream.DefaultRecursionLimit + 1; i++)
- {
- output.WriteTag(1, WireFormat.WireType.StartGroup);
- }
- for (int i = 0; i < CodedInputStream.DefaultRecursionLimit + 1; i++)
- {
- output.WriteTag(1, WireFormat.WireType.EndGroup);
- }
- output.Flush();
- stream.Position = 0;
-
- // Now act like a generated client
- var input = new CodedInputStream(stream);
- Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.StartGroup), input.ReadTag());
- Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField);
- }
-
- [Test]
- public void Construction_Invalid()
- {
- Assert.Throws<ArgumentNullException>(() => new CodedInputStream((byte[]) null));
- Assert.Throws<ArgumentNullException>(() => new CodedInputStream(null, 0, 0));
- Assert.Throws<ArgumentNullException>(() => new CodedInputStream((Stream) null));
- Assert.Throws<ArgumentOutOfRangeException>(() => new CodedInputStream(new byte[10], 100, 0));
- Assert.Throws<ArgumentOutOfRangeException>(() => new CodedInputStream(new byte[10], 5, 10));
- }
-
- [Test]
- public void CreateWithLimits_InvalidLimits()
- {
- var stream = new MemoryStream();
- Assert.Throws<ArgumentOutOfRangeException>(() => CodedInputStream.CreateWithLimits(stream, 0, 1));
- Assert.Throws<ArgumentOutOfRangeException>(() => CodedInputStream.CreateWithLimits(stream, 1, 0));
- }
-
- [Test]
- public void Dispose_DisposesUnderlyingStream()
- {
- var memoryStream = new MemoryStream();
- Assert.IsTrue(memoryStream.CanRead);
- using (var cis = new CodedInputStream(memoryStream))
- {
- }
- Assert.IsFalse(memoryStream.CanRead); // Disposed
- }
-
- [Test]
- public void Dispose_WithLeaveOpen()
- {
- var memoryStream = new MemoryStream();
- Assert.IsTrue(memoryStream.CanRead);
- using (var cis = new CodedInputStream(memoryStream, true))
- {
- }
- Assert.IsTrue(memoryStream.CanRead); // We left the stream open
- }
- }
+#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + +using System; +using System.IO; +using Google.Protobuf.TestProtos; +using NUnit.Framework; + +namespace Google.Protobuf +{ + public class CodedInputStreamTest + { + /// <summary> + /// Helper to construct a byte array from a bunch of bytes. The inputs are + /// actually ints so that I can use hex notation and not get stupid errors + /// about precision. + /// </summary> + private static byte[] Bytes(params int[] bytesAsInts) + { + byte[] bytes = new byte[bytesAsInts.Length]; + for (int i = 0; i < bytesAsInts.Length; i++) + { + bytes[i] = (byte) bytesAsInts[i]; + } + return bytes; + } + + /// <summary> + /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() + /// </summary> + private static void AssertReadVarint(byte[] data, ulong value) + { + CodedInputStream input = new CodedInputStream(data); + Assert.AreEqual((uint) value, input.ReadRawVarint32()); + + input = new CodedInputStream(data); + Assert.AreEqual(value, input.ReadRawVarint64()); + Assert.IsTrue(input.IsAtEnd); + + // Try different block sizes. + for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2) + { + input = new CodedInputStream(new SmallBlockInputStream(data, bufferSize)); + Assert.AreEqual((uint) value, input.ReadRawVarint32()); + + input = new CodedInputStream(new SmallBlockInputStream(data, bufferSize)); + Assert.AreEqual(value, input.ReadRawVarint64()); + Assert.IsTrue(input.IsAtEnd); + } + + // Try reading directly from a MemoryStream. We want to verify that it + // doesn't read past the end of the input, so write an extra byte - this + // lets us test the position at the end. + MemoryStream memoryStream = new MemoryStream(); + memoryStream.Write(data, 0, data.Length); + memoryStream.WriteByte(0); + memoryStream.Position = 0; + Assert.AreEqual((uint) value, CodedInputStream.ReadRawVarint32(memoryStream)); + Assert.AreEqual(data.Length, memoryStream.Position); + } + + /// <summary> + /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() and + /// expects them to fail with an InvalidProtocolBufferException whose + /// description matches the given one. + /// </summary> + private static void AssertReadVarintFailure(InvalidProtocolBufferException expected, byte[] data) + { + CodedInputStream input = new CodedInputStream(data); + var exception = Assert.Throws<InvalidProtocolBufferException>(() => input.ReadRawVarint32()); + Assert.AreEqual(expected.Message, exception.Message); + + input = new CodedInputStream(data); + exception = Assert.Throws<InvalidProtocolBufferException>(() => input.ReadRawVarint64()); + Assert.AreEqual(expected.Message, exception.Message); + + // Make sure we get the same error when reading directly from a Stream. + exception = Assert.Throws<InvalidProtocolBufferException>(() => CodedInputStream.ReadRawVarint32(new MemoryStream(data))); + Assert.AreEqual(expected.Message, exception.Message); + } + + [Test] + public void ReadVarint() + { + AssertReadVarint(Bytes(0x00), 0); + AssertReadVarint(Bytes(0x01), 1); + AssertReadVarint(Bytes(0x7f), 127); + // 14882 + AssertReadVarint(Bytes(0xa2, 0x74), (0x22 << 0) | (0x74 << 7)); + // 2961488830 + AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x0b), + (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | + (0x0bL << 28)); + + // 64-bit + // 7256456126 + AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x1b), + (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | + (0x1bL << 28)); + // 41256202580718336 + AssertReadVarint(Bytes(0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49), + (0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) | + (0x43L << 28) | (0x49L << 35) | (0x24L << 42) | (0x49L << 49)); + // 11964378330978735131 + AssertReadVarint(Bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01), + (0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) | + (0x3bUL << 28) | (0x56UL << 35) | (0x00UL << 42) | + (0x05UL << 49) | (0x26UL << 56) | (0x01UL << 63)); + + // Failures + AssertReadVarintFailure( + InvalidProtocolBufferException.MalformedVarint(), + Bytes(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, + 0x00)); + AssertReadVarintFailure( + InvalidProtocolBufferException.TruncatedMessage(), + Bytes(0x80)); + } + + /// <summary> + /// Parses the given bytes using ReadRawLittleEndian32() and checks + /// that the result matches the given value. + /// </summary> + private static void AssertReadLittleEndian32(byte[] data, uint value) + { + CodedInputStream input = new CodedInputStream(data); + Assert.AreEqual(value, input.ReadRawLittleEndian32()); + Assert.IsTrue(input.IsAtEnd); + + // Try different block sizes. + for (int blockSize = 1; blockSize <= 16; blockSize *= 2) + { + input = new CodedInputStream( + new SmallBlockInputStream(data, blockSize)); + Assert.AreEqual(value, input.ReadRawLittleEndian32()); + Assert.IsTrue(input.IsAtEnd); + } + } + + /// <summary> + /// Parses the given bytes using ReadRawLittleEndian64() and checks + /// that the result matches the given value. + /// </summary> + private static void AssertReadLittleEndian64(byte[] data, ulong value) + { + CodedInputStream input = new CodedInputStream(data); + Assert.AreEqual(value, input.ReadRawLittleEndian64()); + Assert.IsTrue(input.IsAtEnd); + + // Try different block sizes. + for (int blockSize = 1; blockSize <= 16; blockSize *= 2) + { + input = new CodedInputStream( + new SmallBlockInputStream(data, blockSize)); + Assert.AreEqual(value, input.ReadRawLittleEndian64()); + Assert.IsTrue(input.IsAtEnd); + } + } + + [Test] + public void ReadLittleEndian() + { + AssertReadLittleEndian32(Bytes(0x78, 0x56, 0x34, 0x12), 0x12345678); + AssertReadLittleEndian32(Bytes(0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef0); + + AssertReadLittleEndian64(Bytes(0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12), + 0x123456789abcdef0L); + AssertReadLittleEndian64( + Bytes(0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef012345678UL); + } + + [Test] + public void DecodeZigZag32() + { + Assert.AreEqual(0, CodedInputStream.DecodeZigZag32(0)); + Assert.AreEqual(-1, CodedInputStream.DecodeZigZag32(1)); + Assert.AreEqual(1, CodedInputStream.DecodeZigZag32(2)); + Assert.AreEqual(-2, CodedInputStream.DecodeZigZag32(3)); + Assert.AreEqual(0x3FFFFFFF, CodedInputStream.DecodeZigZag32(0x7FFFFFFE)); + Assert.AreEqual(unchecked((int) 0xC0000000), CodedInputStream.DecodeZigZag32(0x7FFFFFFF)); + Assert.AreEqual(0x7FFFFFFF, CodedInputStream.DecodeZigZag32(0xFFFFFFFE)); + Assert.AreEqual(unchecked((int) 0x80000000), CodedInputStream.DecodeZigZag32(0xFFFFFFFF)); + } + + [Test] + public void DecodeZigZag64() + { + Assert.AreEqual(0, CodedInputStream.DecodeZigZag64(0)); + Assert.AreEqual(-1, CodedInputStream.DecodeZigZag64(1)); + Assert.AreEqual(1, CodedInputStream.DecodeZigZag64(2)); + Assert.AreEqual(-2, CodedInputStream.DecodeZigZag64(3)); + Assert.AreEqual(0x000000003FFFFFFFL, CodedInputStream.DecodeZigZag64(0x000000007FFFFFFEL)); + Assert.AreEqual(unchecked((long) 0xFFFFFFFFC0000000L), CodedInputStream.DecodeZigZag64(0x000000007FFFFFFFL)); + Assert.AreEqual(0x000000007FFFFFFFL, CodedInputStream.DecodeZigZag64(0x00000000FFFFFFFEL)); + Assert.AreEqual(unchecked((long) 0xFFFFFFFF80000000L), CodedInputStream.DecodeZigZag64(0x00000000FFFFFFFFL)); + Assert.AreEqual(0x7FFFFFFFFFFFFFFFL, CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFEL)); + Assert.AreEqual(unchecked((long) 0x8000000000000000L), CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFFL)); + } + + [Test] + public void ReadWholeMessage_VaryingBlockSizes() + { + TestAllTypes message = SampleMessages.CreateFullTestAllTypes(); + + byte[] rawBytes = message.ToByteArray(); + Assert.AreEqual(rawBytes.Length, message.CalculateSize()); + TestAllTypes message2 = TestAllTypes.Parser.ParseFrom(rawBytes); + Assert.AreEqual(message, message2); + + // Try different block sizes. + for (int blockSize = 1; blockSize < 256; blockSize *= 2) + { + message2 = TestAllTypes.Parser.ParseFrom(new SmallBlockInputStream(rawBytes, blockSize)); + Assert.AreEqual(message, message2); + } + } + + [Test] + public void ReadHugeBlob() + { + // Allocate and initialize a 1MB blob. + byte[] blob = new byte[1 << 20]; + for (int i = 0; i < blob.Length; i++) + { + blob[i] = (byte) i; + } + + // Make a message containing it. + var message = new TestAllTypes { SingleBytes = ByteString.CopyFrom(blob) }; + + // Serialize and parse it. Make sure to parse from an InputStream, not + // directly from a ByteString, so that CodedInputStream uses buffered + // reading. + TestAllTypes message2 = TestAllTypes.Parser.ParseFrom(message.ToByteString()); + + Assert.AreEqual(message, message2); + } + + [Test] + public void ReadMaliciouslyLargeBlob() + { + MemoryStream ms = new MemoryStream(); + CodedOutputStream output = new CodedOutputStream(ms); + + uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited); + output.WriteRawVarint32(tag); + output.WriteRawVarint32(0x7FFFFFFF); + output.WriteRawBytes(new byte[32]); // Pad with a few random bytes. + output.Flush(); + ms.Position = 0; + + CodedInputStream input = new CodedInputStream(ms); + Assert.AreEqual(tag, input.ReadTag()); + + Assert.Throws<InvalidProtocolBufferException>(() => input.ReadBytes()); + } + + internal static TestRecursiveMessage MakeRecursiveMessage(int depth) + { + if (depth == 0) + { + return new TestRecursiveMessage { I = 5 }; + } + else + { + return new TestRecursiveMessage { A = MakeRecursiveMessage(depth - 1) }; + } + } + + internal static void AssertMessageDepth(TestRecursiveMessage message, int depth) + { + if (depth == 0) + { + Assert.IsNull(message.A); + Assert.AreEqual(5, message.I); + } + else + { + Assert.IsNotNull(message.A); + AssertMessageDepth(message.A, depth - 1); + } + } + + [Test] + public void MaliciousRecursion() + { + ByteString data64 = MakeRecursiveMessage(64).ToByteString(); + ByteString data65 = MakeRecursiveMessage(65).ToByteString(); + + AssertMessageDepth(TestRecursiveMessage.Parser.ParseFrom(data64), 64); + + Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(data65)); + + CodedInputStream input = CodedInputStream.CreateWithLimits(new MemoryStream(data64.ToByteArray()), 1000000, 63); + Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(input)); + } + + [Test] + public void SizeLimit() + { + // Have to use a Stream rather than ByteString.CreateCodedInput as SizeLimit doesn't + // apply to the latter case. + MemoryStream ms = new MemoryStream(SampleMessages.CreateFullTestAllTypes().ToByteArray()); + CodedInputStream input = CodedInputStream.CreateWithLimits(ms, 16, 100); + Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseFrom(input)); + } + + /// <summary> + /// Tests that if we read an string that contains invalid UTF-8, no exception + /// is thrown. Instead, the invalid bytes are replaced with the Unicode + /// "replacement character" U+FFFD. + /// </summary> + [Test] + public void ReadInvalidUtf8() + { + MemoryStream ms = new MemoryStream(); + CodedOutputStream output = new CodedOutputStream(ms); + + uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited); + output.WriteRawVarint32(tag); + output.WriteRawVarint32(1); + output.WriteRawBytes(new byte[] {0x80}); + output.Flush(); + ms.Position = 0; + + CodedInputStream input = new CodedInputStream(ms); + + Assert.AreEqual(tag, input.ReadTag()); + string text = input.ReadString(); + Assert.AreEqual('\ufffd', text[0]); + } + + /// <summary> + /// A stream which limits the number of bytes it reads at a time. + /// We use this to make sure that CodedInputStream doesn't screw up when + /// reading in small blocks. + /// </summary> + private sealed class SmallBlockInputStream : MemoryStream + { + private readonly int blockSize; + + public SmallBlockInputStream(byte[] data, int blockSize) + : base(data) + { + this.blockSize = blockSize; + } + + public override int Read(byte[] buffer, int offset, int count) + { + return base.Read(buffer, offset, Math.Min(count, blockSize)); + } + } + + [Test] + public void TestNegativeEnum() + { + byte[] bytes = { 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01 }; + CodedInputStream input = new CodedInputStream(bytes); + Assert.AreEqual((int)SampleEnum.NegativeValue, input.ReadEnum()); + Assert.IsTrue(input.IsAtEnd); + } + + //Issue 71: CodedInputStream.ReadBytes go to slow path unnecessarily + [Test] + public void TestSlowPathAvoidance() + { + using (var ms = new MemoryStream()) + { + CodedOutputStream output = new CodedOutputStream(ms); + output.WriteTag(1, WireFormat.WireType.LengthDelimited); + output.WriteBytes(ByteString.CopyFrom(new byte[100])); + output.WriteTag(2, WireFormat.WireType.LengthDelimited); + output.WriteBytes(ByteString.CopyFrom(new byte[100])); + output.Flush(); + + ms.Position = 0; + CodedInputStream input = new CodedInputStream(ms, new byte[ms.Length / 2], 0, 0, false); + + uint tag = input.ReadTag(); + Assert.AreEqual(1, WireFormat.GetTagFieldNumber(tag)); + Assert.AreEqual(100, input.ReadBytes().Length); + + tag = input.ReadTag(); + Assert.AreEqual(2, WireFormat.GetTagFieldNumber(tag)); + Assert.AreEqual(100, input.ReadBytes().Length); + } + } + + [Test] + public void Tag0Throws() + { + var input = new CodedInputStream(new byte[] { 0 }); + Assert.Throws<InvalidProtocolBufferException>(() => input.ReadTag()); + } + + [Test] + public void SkipGroup() + { + // Create an output stream with a group in: + // Field 1: string "field 1" + // Field 2: group containing: + // Field 1: fixed int32 value 100 + // Field 2: string "ignore me" + // Field 3: nested group containing + // Field 1: fixed int64 value 1000 + // Field 3: string "field 3" + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + output.WriteTag(1, WireFormat.WireType.LengthDelimited); + output.WriteString("field 1"); + + // The outer group... + output.WriteTag(2, WireFormat.WireType.StartGroup); + output.WriteTag(1, WireFormat.WireType.Fixed32); + output.WriteFixed32(100); + output.WriteTag(2, WireFormat.WireType.LengthDelimited); + output.WriteString("ignore me"); + // The nested group... + output.WriteTag(3, WireFormat.WireType.StartGroup); + output.WriteTag(1, WireFormat.WireType.Fixed64); + output.WriteFixed64(1000); + // Note: Not sure the field number is relevant for end group... + output.WriteTag(3, WireFormat.WireType.EndGroup); + + // End the outer group + output.WriteTag(2, WireFormat.WireType.EndGroup); + + output.WriteTag(3, WireFormat.WireType.LengthDelimited); + output.WriteString("field 3"); + output.Flush(); + stream.Position = 0; + + // Now act like a generated client + var input = new CodedInputStream(stream); + Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited), input.ReadTag()); + Assert.AreEqual("field 1", input.ReadString()); + Assert.AreEqual(WireFormat.MakeTag(2, WireFormat.WireType.StartGroup), input.ReadTag()); + input.SkipLastField(); // Should consume the whole group, including the nested one. + Assert.AreEqual(WireFormat.MakeTag(3, WireFormat.WireType.LengthDelimited), input.ReadTag()); + Assert.AreEqual("field 3", input.ReadString()); + } + + [Test] + public void SkipGroup_WrongEndGroupTag() + { + // Create an output stream with: + // Field 1: string "field 1" + // Start group 2 + // Field 3: fixed int32 + // End group 4 (should give an error) + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + output.WriteTag(1, WireFormat.WireType.LengthDelimited); + output.WriteString("field 1"); + + // The outer group... + output.WriteTag(2, WireFormat.WireType.StartGroup); + output.WriteTag(3, WireFormat.WireType.Fixed32); + output.WriteFixed32(100); + output.WriteTag(4, WireFormat.WireType.EndGroup); + output.Flush(); + stream.Position = 0; + + // Now act like a generated client + var input = new CodedInputStream(stream); + Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited), input.ReadTag()); + Assert.AreEqual("field 1", input.ReadString()); + Assert.AreEqual(WireFormat.MakeTag(2, WireFormat.WireType.StartGroup), input.ReadTag()); + Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField); + } + + [Test] + public void RogueEndGroupTag() + { + // If we have an end-group tag without a leading start-group tag, generated + // code will just call SkipLastField... so that should fail. + + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + output.WriteTag(1, WireFormat.WireType.EndGroup); + output.Flush(); + stream.Position = 0; + + var input = new CodedInputStream(stream); + Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.EndGroup), input.ReadTag()); + Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField); + } + + [Test] + public void EndOfStreamReachedWhileSkippingGroup() + { + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + output.WriteTag(1, WireFormat.WireType.StartGroup); + output.WriteTag(2, WireFormat.WireType.StartGroup); + output.WriteTag(2, WireFormat.WireType.EndGroup); + + output.Flush(); + stream.Position = 0; + + // Now act like a generated client + var input = new CodedInputStream(stream); + input.ReadTag(); + Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField); + } + + [Test] + public void RecursionLimitAppliedWhileSkippingGroup() + { + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + for (int i = 0; i < CodedInputStream.DefaultRecursionLimit + 1; i++) + { + output.WriteTag(1, WireFormat.WireType.StartGroup); + } + for (int i = 0; i < CodedInputStream.DefaultRecursionLimit + 1; i++) + { + output.WriteTag(1, WireFormat.WireType.EndGroup); + } + output.Flush(); + stream.Position = 0; + + // Now act like a generated client + var input = new CodedInputStream(stream); + Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.StartGroup), input.ReadTag()); + Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField); + } + + [Test] + public void Construction_Invalid() + { + Assert.Throws<ArgumentNullException>(() => new CodedInputStream((byte[]) null)); + Assert.Throws<ArgumentNullException>(() => new CodedInputStream(null, 0, 0)); + Assert.Throws<ArgumentNullException>(() => new CodedInputStream((Stream) null)); + Assert.Throws<ArgumentOutOfRangeException>(() => new CodedInputStream(new byte[10], 100, 0)); + Assert.Throws<ArgumentOutOfRangeException>(() => new CodedInputStream(new byte[10], 5, 10)); + } + + [Test] + public void CreateWithLimits_InvalidLimits() + { + var stream = new MemoryStream(); + Assert.Throws<ArgumentOutOfRangeException>(() => CodedInputStream.CreateWithLimits(stream, 0, 1)); + Assert.Throws<ArgumentOutOfRangeException>(() => CodedInputStream.CreateWithLimits(stream, 1, 0)); + } + + [Test] + public void Dispose_DisposesUnderlyingStream() + { + var memoryStream = new MemoryStream(); + Assert.IsTrue(memoryStream.CanRead); + using (var cis = new CodedInputStream(memoryStream)) + { + } + Assert.IsFalse(memoryStream.CanRead); // Disposed + } + + [Test] + public void Dispose_WithLeaveOpen() + { + var memoryStream = new MemoryStream(); + Assert.IsTrue(memoryStream.CanRead); + using (var cis = new CodedInputStream(memoryStream, true)) + { + } + Assert.IsTrue(memoryStream.CanRead); // We left the stream open + } + } }
\ No newline at end of file diff --git a/third_party/protobuf/3.4.0/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/CodedOutputStreamTest.cs b/third_party/protobuf/3.4.0/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/CodedOutputStreamTest.cs index 01bd3218f3..3653d4f337 100644 --- a/third_party/protobuf/3.4.0/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/CodedOutputStreamTest.cs +++ b/third_party/protobuf/3.4.0/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/CodedOutputStreamTest.cs @@ -1,419 +1,419 @@ -#region Copyright notice and license
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-#endregion
-
-using System;
-using System.IO;
-using Google.Protobuf.TestProtos;
-using NUnit.Framework;
-
-namespace Google.Protobuf
-{
- public class CodedOutputStreamTest
- {
- /// <summary>
- /// Writes the given value using WriteRawVarint32() and WriteRawVarint64() and
- /// checks that the result matches the given bytes
- /// </summary>
- private static void AssertWriteVarint(byte[] data, ulong value)
- {
- // Only do 32-bit write if the value fits in 32 bits.
- if ((value >> 32) == 0)
- {
- MemoryStream rawOutput = new MemoryStream();
- CodedOutputStream output = new CodedOutputStream(rawOutput);
- output.WriteRawVarint32((uint) value);
- output.Flush();
- Assert.AreEqual(data, rawOutput.ToArray());
- // Also try computing size.
- Assert.AreEqual(data.Length, CodedOutputStream.ComputeRawVarint32Size((uint) value));
- }
-
- {
- MemoryStream rawOutput = new MemoryStream();
- CodedOutputStream output = new CodedOutputStream(rawOutput);
- output.WriteRawVarint64(value);
- output.Flush();
- Assert.AreEqual(data, rawOutput.ToArray());
-
- // Also try computing size.
- Assert.AreEqual(data.Length, CodedOutputStream.ComputeRawVarint64Size(value));
- }
-
- // Try different buffer sizes.
- for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2)
- {
- // Only do 32-bit write if the value fits in 32 bits.
- if ((value >> 32) == 0)
- {
- MemoryStream rawOutput = new MemoryStream();
- CodedOutputStream output =
- new CodedOutputStream(rawOutput, bufferSize);
- output.WriteRawVarint32((uint) value);
- output.Flush();
- Assert.AreEqual(data, rawOutput.ToArray());
- }
-
- {
- MemoryStream rawOutput = new MemoryStream();
- CodedOutputStream output = new CodedOutputStream(rawOutput, bufferSize);
- output.WriteRawVarint64(value);
- output.Flush();
- Assert.AreEqual(data, rawOutput.ToArray());
- }
- }
- }
-
- /// <summary>
- /// Tests WriteRawVarint32() and WriteRawVarint64()
- /// </summary>
- [Test]
- public void WriteVarint()
- {
- AssertWriteVarint(new byte[] {0x00}, 0);
- AssertWriteVarint(new byte[] {0x01}, 1);
- AssertWriteVarint(new byte[] {0x7f}, 127);
- // 14882
- AssertWriteVarint(new byte[] {0xa2, 0x74}, (0x22 << 0) | (0x74 << 7));
- // 2961488830
- AssertWriteVarint(new byte[] {0xbe, 0xf7, 0x92, 0x84, 0x0b},
- (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
- (0x0bL << 28));
-
- // 64-bit
- // 7256456126
- AssertWriteVarint(new byte[] {0xbe, 0xf7, 0x92, 0x84, 0x1b},
- (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
- (0x1bL << 28));
- // 41256202580718336
- AssertWriteVarint(
- new byte[] {0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49},
- (0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) |
- (0x43UL << 28) | (0x49L << 35) | (0x24UL << 42) | (0x49UL << 49));
- // 11964378330978735131
- AssertWriteVarint(
- new byte[] {0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01},
- unchecked((ulong)
- ((0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) |
- (0x3bL << 28) | (0x56L << 35) | (0x00L << 42) |
- (0x05L << 49) | (0x26L << 56) | (0x01L << 63))));
- }
-
- /// <summary>
- /// Parses the given bytes using WriteRawLittleEndian32() and checks
- /// that the result matches the given value.
- /// </summary>
- private static void AssertWriteLittleEndian32(byte[] data, uint value)
- {
- MemoryStream rawOutput = new MemoryStream();
- CodedOutputStream output = new CodedOutputStream(rawOutput);
- output.WriteRawLittleEndian32(value);
- output.Flush();
- Assert.AreEqual(data, rawOutput.ToArray());
-
- // Try different buffer sizes.
- for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2)
- {
- rawOutput = new MemoryStream();
- output = new CodedOutputStream(rawOutput, bufferSize);
- output.WriteRawLittleEndian32(value);
- output.Flush();
- Assert.AreEqual(data, rawOutput.ToArray());
- }
- }
-
- /// <summary>
- /// Parses the given bytes using WriteRawLittleEndian64() and checks
- /// that the result matches the given value.
- /// </summary>
- private static void AssertWriteLittleEndian64(byte[] data, ulong value)
- {
- MemoryStream rawOutput = new MemoryStream();
- CodedOutputStream output = new CodedOutputStream(rawOutput);
- output.WriteRawLittleEndian64(value);
- output.Flush();
- Assert.AreEqual(data, rawOutput.ToArray());
-
- // Try different block sizes.
- for (int blockSize = 1; blockSize <= 16; blockSize *= 2)
- {
- rawOutput = new MemoryStream();
- output = new CodedOutputStream(rawOutput, blockSize);
- output.WriteRawLittleEndian64(value);
- output.Flush();
- Assert.AreEqual(data, rawOutput.ToArray());
- }
- }
-
- /// <summary>
- /// Tests writeRawLittleEndian32() and writeRawLittleEndian64().
- /// </summary>
- [Test]
- public void WriteLittleEndian()
- {
- AssertWriteLittleEndian32(new byte[] {0x78, 0x56, 0x34, 0x12}, 0x12345678);
- AssertWriteLittleEndian32(new byte[] {0xf0, 0xde, 0xbc, 0x9a}, 0x9abcdef0);
-
- AssertWriteLittleEndian64(
- new byte[] {0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12},
- 0x123456789abcdef0L);
- AssertWriteLittleEndian64(
- new byte[] {0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a},
- 0x9abcdef012345678UL);
- }
-
- [Test]
- public void WriteWholeMessage_VaryingBlockSizes()
- {
- TestAllTypes message = SampleMessages.CreateFullTestAllTypes();
-
- byte[] rawBytes = message.ToByteArray();
-
- // Try different block sizes.
- for (int blockSize = 1; blockSize < 256; blockSize *= 2)
- {
- MemoryStream rawOutput = new MemoryStream();
- CodedOutputStream output = new CodedOutputStream(rawOutput, blockSize);
- message.WriteTo(output);
- output.Flush();
- Assert.AreEqual(rawBytes, rawOutput.ToArray());
- }
- }
-
- [Test]
- public void EncodeZigZag32()
- {
- Assert.AreEqual(0u, CodedOutputStream.EncodeZigZag32(0));
- Assert.AreEqual(1u, CodedOutputStream.EncodeZigZag32(-1));
- Assert.AreEqual(2u, CodedOutputStream.EncodeZigZag32(1));
- Assert.AreEqual(3u, CodedOutputStream.EncodeZigZag32(-2));
- Assert.AreEqual(0x7FFFFFFEu, CodedOutputStream.EncodeZigZag32(0x3FFFFFFF));
- Assert.AreEqual(0x7FFFFFFFu, CodedOutputStream.EncodeZigZag32(unchecked((int) 0xC0000000)));
- Assert.AreEqual(0xFFFFFFFEu, CodedOutputStream.EncodeZigZag32(0x7FFFFFFF));
- Assert.AreEqual(0xFFFFFFFFu, CodedOutputStream.EncodeZigZag32(unchecked((int) 0x80000000)));
- }
-
- [Test]
- public void EncodeZigZag64()
- {
- Assert.AreEqual(0u, CodedOutputStream.EncodeZigZag64(0));
- Assert.AreEqual(1u, CodedOutputStream.EncodeZigZag64(-1));
- Assert.AreEqual(2u, CodedOutputStream.EncodeZigZag64(1));
- Assert.AreEqual(3u, CodedOutputStream.EncodeZigZag64(-2));
- Assert.AreEqual(0x000000007FFFFFFEuL,
- CodedOutputStream.EncodeZigZag64(unchecked((long) 0x000000003FFFFFFFUL)));
- Assert.AreEqual(0x000000007FFFFFFFuL,
- CodedOutputStream.EncodeZigZag64(unchecked((long) 0xFFFFFFFFC0000000UL)));
- Assert.AreEqual(0x00000000FFFFFFFEuL,
- CodedOutputStream.EncodeZigZag64(unchecked((long) 0x000000007FFFFFFFUL)));
- Assert.AreEqual(0x00000000FFFFFFFFuL,
- CodedOutputStream.EncodeZigZag64(unchecked((long) 0xFFFFFFFF80000000UL)));
- Assert.AreEqual(0xFFFFFFFFFFFFFFFEL,
- CodedOutputStream.EncodeZigZag64(unchecked((long) 0x7FFFFFFFFFFFFFFFUL)));
- Assert.AreEqual(0xFFFFFFFFFFFFFFFFL,
- CodedOutputStream.EncodeZigZag64(unchecked((long) 0x8000000000000000UL)));
- }
-
- [Test]
- public void RoundTripZigZag32()
- {
- // Some easier-to-verify round-trip tests. The inputs (other than 0, 1, -1)
- // were chosen semi-randomly via keyboard bashing.
- Assert.AreEqual(0, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(0)));
- Assert.AreEqual(1, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(1)));
- Assert.AreEqual(-1, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(-1)));
- Assert.AreEqual(14927, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(14927)));
- Assert.AreEqual(-3612, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(-3612)));
- }
-
- [Test]
- public void RoundTripZigZag64()
- {
- Assert.AreEqual(0, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(0)));
- Assert.AreEqual(1, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(1)));
- Assert.AreEqual(-1, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(-1)));
- Assert.AreEqual(14927, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(14927)));
- Assert.AreEqual(-3612, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(-3612)));
-
- Assert.AreEqual(856912304801416L,
- CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(856912304801416L)));
- Assert.AreEqual(-75123905439571256L,
- CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(-75123905439571256L)));
- }
-
- [Test]
- public void TestNegativeEnumNoTag()
- {
- Assert.AreEqual(10, CodedOutputStream.ComputeInt32Size(-2));
- Assert.AreEqual(10, CodedOutputStream.ComputeEnumSize((int) SampleEnum.NegativeValue));
-
- byte[] bytes = new byte[10];
- CodedOutputStream output = new CodedOutputStream(bytes);
- output.WriteEnum((int) SampleEnum.NegativeValue);
-
- Assert.AreEqual(0, output.SpaceLeft);
- Assert.AreEqual("FE-FF-FF-FF-FF-FF-FF-FF-FF-01", BitConverter.ToString(bytes));
- }
-
- [Test]
- public void TestCodedInputOutputPosition()
- {
- byte[] content = new byte[110];
- for (int i = 0; i < content.Length; i++)
- content[i] = (byte)i;
-
- byte[] child = new byte[120];
- {
- MemoryStream ms = new MemoryStream(child);
- CodedOutputStream cout = new CodedOutputStream(ms, 20);
- // Field 11: numeric value: 500
- cout.WriteTag(11, WireFormat.WireType.Varint);
- Assert.AreEqual(1, cout.Position);
- cout.WriteInt32(500);
- Assert.AreEqual(3, cout.Position);
- //Field 12: length delimited 120 bytes
- cout.WriteTag(12, WireFormat.WireType.LengthDelimited);
- Assert.AreEqual(4, cout.Position);
- cout.WriteBytes(ByteString.CopyFrom(content));
- Assert.AreEqual(115, cout.Position);
- // Field 13: fixed numeric value: 501
- cout.WriteTag(13, WireFormat.WireType.Fixed32);
- Assert.AreEqual(116, cout.Position);
- cout.WriteSFixed32(501);
- Assert.AreEqual(120, cout.Position);
- cout.Flush();
- }
-
- byte[] bytes = new byte[130];
- {
- CodedOutputStream cout = new CodedOutputStream(bytes);
- // Field 1: numeric value: 500
- cout.WriteTag(1, WireFormat.WireType.Varint);
- Assert.AreEqual(1, cout.Position);
- cout.WriteInt32(500);
- Assert.AreEqual(3, cout.Position);
- //Field 2: length delimited 120 bytes
- cout.WriteTag(2, WireFormat.WireType.LengthDelimited);
- Assert.AreEqual(4, cout.Position);
- cout.WriteBytes(ByteString.CopyFrom(child));
- Assert.AreEqual(125, cout.Position);
- // Field 3: fixed numeric value: 500
- cout.WriteTag(3, WireFormat.WireType.Fixed32);
- Assert.AreEqual(126, cout.Position);
- cout.WriteSFixed32(501);
- Assert.AreEqual(130, cout.Position);
- cout.Flush();
- }
- // Now test Input stream:
- {
- CodedInputStream cin = new CodedInputStream(new MemoryStream(bytes), new byte[50], 0, 0, false);
- Assert.AreEqual(0, cin.Position);
- // Field 1:
- uint tag = cin.ReadTag();
- Assert.AreEqual(1, tag >> 3);
- Assert.AreEqual(1, cin.Position);
- Assert.AreEqual(500, cin.ReadInt32());
- Assert.AreEqual(3, cin.Position);
- //Field 2:
- tag = cin.ReadTag();
- Assert.AreEqual(2, tag >> 3);
- Assert.AreEqual(4, cin.Position);
- int childlen = cin.ReadLength();
- Assert.AreEqual(120, childlen);
- Assert.AreEqual(5, cin.Position);
- int oldlimit = cin.PushLimit((int)childlen);
- Assert.AreEqual(5, cin.Position);
- // Now we are reading child message
- {
- // Field 11: numeric value: 500
- tag = cin.ReadTag();
- Assert.AreEqual(11, tag >> 3);
- Assert.AreEqual(6, cin.Position);
- Assert.AreEqual(500, cin.ReadInt32());
- Assert.AreEqual(8, cin.Position);
- //Field 12: length delimited 120 bytes
- tag = cin.ReadTag();
- Assert.AreEqual(12, tag >> 3);
- Assert.AreEqual(9, cin.Position);
- ByteString bstr = cin.ReadBytes();
- Assert.AreEqual(110, bstr.Length);
- Assert.AreEqual((byte) 109, bstr[109]);
- Assert.AreEqual(120, cin.Position);
- // Field 13: fixed numeric value: 501
- tag = cin.ReadTag();
- Assert.AreEqual(13, tag >> 3);
- // ROK - Previously broken here, this returned 126 failing to account for bufferSizeAfterLimit
- Assert.AreEqual(121, cin.Position);
- Assert.AreEqual(501, cin.ReadSFixed32());
- Assert.AreEqual(125, cin.Position);
- Assert.IsTrue(cin.IsAtEnd);
- }
- cin.PopLimit(oldlimit);
- Assert.AreEqual(125, cin.Position);
- // Field 3: fixed numeric value: 501
- tag = cin.ReadTag();
- Assert.AreEqual(3, tag >> 3);
- Assert.AreEqual(126, cin.Position);
- Assert.AreEqual(501, cin.ReadSFixed32());
- Assert.AreEqual(130, cin.Position);
- Assert.IsTrue(cin.IsAtEnd);
- }
- }
-
- [Test]
- public void Dispose_DisposesUnderlyingStream()
- {
- var memoryStream = new MemoryStream();
- Assert.IsTrue(memoryStream.CanWrite);
- using (var cos = new CodedOutputStream(memoryStream))
- {
- cos.WriteRawByte(0);
- Assert.AreEqual(0, memoryStream.Position); // Not flushed yet
- }
- Assert.AreEqual(1, memoryStream.ToArray().Length); // Flushed data from CodedOutputStream to MemoryStream
- Assert.IsFalse(memoryStream.CanWrite); // Disposed
- }
-
- [Test]
- public void Dispose_WithLeaveOpen()
- {
- var memoryStream = new MemoryStream();
- Assert.IsTrue(memoryStream.CanWrite);
- using (var cos = new CodedOutputStream(memoryStream, true))
- {
- cos.WriteRawByte(0);
- Assert.AreEqual(0, memoryStream.Position); // Not flushed yet
- }
- Assert.AreEqual(1, memoryStream.Position); // Flushed data from CodedOutputStream to MemoryStream
- Assert.IsTrue(memoryStream.CanWrite); // We left the stream open
- }
- }
+#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + +using System; +using System.IO; +using Google.Protobuf.TestProtos; +using NUnit.Framework; + +namespace Google.Protobuf +{ + public class CodedOutputStreamTest + { + /// <summary> + /// Writes the given value using WriteRawVarint32() and WriteRawVarint64() and + /// checks that the result matches the given bytes + /// </summary> + private static void AssertWriteVarint(byte[] data, ulong value) + { + // Only do 32-bit write if the value fits in 32 bits. + if ((value >> 32) == 0) + { + MemoryStream rawOutput = new MemoryStream(); + CodedOutputStream output = new CodedOutputStream(rawOutput); + output.WriteRawVarint32((uint) value); + output.Flush(); + Assert.AreEqual(data, rawOutput.ToArray()); + // Also try computing size. + Assert.AreEqual(data.Length, CodedOutputStream.ComputeRawVarint32Size((uint) value)); + } + + { + MemoryStream rawOutput = new MemoryStream(); + CodedOutputStream output = new CodedOutputStream(rawOutput); + output.WriteRawVarint64(value); + output.Flush(); + Assert.AreEqual(data, rawOutput.ToArray()); + + // Also try computing size. + Assert.AreEqual(data.Length, CodedOutputStream.ComputeRawVarint64Size(value)); + } + + // Try different buffer sizes. + for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2) + { + // Only do 32-bit write if the value fits in 32 bits. + if ((value >> 32) == 0) + { + MemoryStream rawOutput = new MemoryStream(); + CodedOutputStream output = + new CodedOutputStream(rawOutput, bufferSize); + output.WriteRawVarint32((uint) value); + output.Flush(); + Assert.AreEqual(data, rawOutput.ToArray()); + } + + { + MemoryStream rawOutput = new MemoryStream(); + CodedOutputStream output = new CodedOutputStream(rawOutput, bufferSize); + output.WriteRawVarint64(value); + output.Flush(); + Assert.AreEqual(data, rawOutput.ToArray()); + } + } + } + + /// <summary> + /// Tests WriteRawVarint32() and WriteRawVarint64() + /// </summary> + [Test] + public void WriteVarint() + { + AssertWriteVarint(new byte[] {0x00}, 0); + AssertWriteVarint(new byte[] {0x01}, 1); + AssertWriteVarint(new byte[] {0x7f}, 127); + // 14882 + AssertWriteVarint(new byte[] {0xa2, 0x74}, (0x22 << 0) | (0x74 << 7)); + // 2961488830 + AssertWriteVarint(new byte[] {0xbe, 0xf7, 0x92, 0x84, 0x0b}, + (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | + (0x0bL << 28)); + + // 64-bit + // 7256456126 + AssertWriteVarint(new byte[] {0xbe, 0xf7, 0x92, 0x84, 0x1b}, + (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | + (0x1bL << 28)); + // 41256202580718336 + AssertWriteVarint( + new byte[] {0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49}, + (0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) | + (0x43UL << 28) | (0x49L << 35) | (0x24UL << 42) | (0x49UL << 49)); + // 11964378330978735131 + AssertWriteVarint( + new byte[] {0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01}, + unchecked((ulong) + ((0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) | + (0x3bL << 28) | (0x56L << 35) | (0x00L << 42) | + (0x05L << 49) | (0x26L << 56) | (0x01L << 63)))); + } + + /// <summary> + /// Parses the given bytes using WriteRawLittleEndian32() and checks + /// that the result matches the given value. + /// </summary> + private static void AssertWriteLittleEndian32(byte[] data, uint value) + { + MemoryStream rawOutput = new MemoryStream(); + CodedOutputStream output = new CodedOutputStream(rawOutput); + output.WriteRawLittleEndian32(value); + output.Flush(); + Assert.AreEqual(data, rawOutput.ToArray()); + + // Try different buffer sizes. + for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2) + { + rawOutput = new MemoryStream(); + output = new CodedOutputStream(rawOutput, bufferSize); + output.WriteRawLittleEndian32(value); + output.Flush(); + Assert.AreEqual(data, rawOutput.ToArray()); + } + } + + /// <summary> + /// Parses the given bytes using WriteRawLittleEndian64() and checks + /// that the result matches the given value. + /// </summary> + private static void AssertWriteLittleEndian64(byte[] data, ulong value) + { + MemoryStream rawOutput = new MemoryStream(); + CodedOutputStream output = new CodedOutputStream(rawOutput); + output.WriteRawLittleEndian64(value); + output.Flush(); + Assert.AreEqual(data, rawOutput.ToArray()); + + // Try different block sizes. + for (int blockSize = 1; blockSize <= 16; blockSize *= 2) + { + rawOutput = new MemoryStream(); + output = new CodedOutputStream(rawOutput, blockSize); + output.WriteRawLittleEndian64(value); + output.Flush(); + Assert.AreEqual(data, rawOutput.ToArray()); + } + } + + /// <summary> + /// Tests writeRawLittleEndian32() and writeRawLittleEndian64(). + /// </summary> + [Test] + public void WriteLittleEndian() + { + AssertWriteLittleEndian32(new byte[] {0x78, 0x56, 0x34, 0x12}, 0x12345678); + AssertWriteLittleEndian32(new byte[] {0xf0, 0xde, 0xbc, 0x9a}, 0x9abcdef0); + + AssertWriteLittleEndian64( + new byte[] {0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12}, + 0x123456789abcdef0L); + AssertWriteLittleEndian64( + new byte[] {0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a}, + 0x9abcdef012345678UL); + } + + [Test] + public void WriteWholeMessage_VaryingBlockSizes() + { + TestAllTypes message = SampleMessages.CreateFullTestAllTypes(); + + byte[] rawBytes = message.ToByteArray(); + + // Try different block sizes. + for (int blockSize = 1; blockSize < 256; blockSize *= 2) + { + MemoryStream rawOutput = new MemoryStream(); + CodedOutputStream output = new CodedOutputStream(rawOutput, blockSize); + message.WriteTo(output); + output.Flush(); + Assert.AreEqual(rawBytes, rawOutput.ToArray()); + } + } + + [Test] + public void EncodeZigZag32() + { + Assert.AreEqual(0u, CodedOutputStream.EncodeZigZag32(0)); + Assert.AreEqual(1u, CodedOutputStream.EncodeZigZag32(-1)); + Assert.AreEqual(2u, CodedOutputStream.EncodeZigZag32(1)); + Assert.AreEqual(3u, CodedOutputStream.EncodeZigZag32(-2)); + Assert.AreEqual(0x7FFFFFFEu, CodedOutputStream.EncodeZigZag32(0x3FFFFFFF)); + Assert.AreEqual(0x7FFFFFFFu, CodedOutputStream.EncodeZigZag32(unchecked((int) 0xC0000000))); + Assert.AreEqual(0xFFFFFFFEu, CodedOutputStream.EncodeZigZag32(0x7FFFFFFF)); + Assert.AreEqual(0xFFFFFFFFu, CodedOutputStream.EncodeZigZag32(unchecked((int) 0x80000000))); + } + + [Test] + public void EncodeZigZag64() + { + Assert.AreEqual(0u, CodedOutputStream.EncodeZigZag64(0)); + Assert.AreEqual(1u, CodedOutputStream.EncodeZigZag64(-1)); + Assert.AreEqual(2u, CodedOutputStream.EncodeZigZag64(1)); + Assert.AreEqual(3u, CodedOutputStream.EncodeZigZag64(-2)); + Assert.AreEqual(0x000000007FFFFFFEuL, + CodedOutputStream.EncodeZigZag64(unchecked((long) 0x000000003FFFFFFFUL))); + Assert.AreEqual(0x000000007FFFFFFFuL, + CodedOutputStream.EncodeZigZag64(unchecked((long) 0xFFFFFFFFC0000000UL))); + Assert.AreEqual(0x00000000FFFFFFFEuL, + CodedOutputStream.EncodeZigZag64(unchecked((long) 0x000000007FFFFFFFUL))); + Assert.AreEqual(0x00000000FFFFFFFFuL, + CodedOutputStream.EncodeZigZag64(unchecked((long) 0xFFFFFFFF80000000UL))); + Assert.AreEqual(0xFFFFFFFFFFFFFFFEL, + CodedOutputStream.EncodeZigZag64(unchecked((long) 0x7FFFFFFFFFFFFFFFUL))); + Assert.AreEqual(0xFFFFFFFFFFFFFFFFL, + CodedOutputStream.EncodeZigZag64(unchecked((long) 0x8000000000000000UL))); + } + + [Test] + public void RoundTripZigZag32() + { + // Some easier-to-verify round-trip tests. The inputs (other than 0, 1, -1) + // were chosen semi-randomly via keyboard bashing. + Assert.AreEqual(0, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(0))); + Assert.AreEqual(1, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(1))); + Assert.AreEqual(-1, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(-1))); + Assert.AreEqual(14927, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(14927))); + Assert.AreEqual(-3612, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(-3612))); + } + + [Test] + public void RoundTripZigZag64() + { + Assert.AreEqual(0, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(0))); + Assert.AreEqual(1, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(1))); + Assert.AreEqual(-1, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(-1))); + Assert.AreEqual(14927, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(14927))); + Assert.AreEqual(-3612, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(-3612))); + + Assert.AreEqual(856912304801416L, + CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(856912304801416L))); + Assert.AreEqual(-75123905439571256L, + CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(-75123905439571256L))); + } + + [Test] + public void TestNegativeEnumNoTag() + { + Assert.AreEqual(10, CodedOutputStream.ComputeInt32Size(-2)); + Assert.AreEqual(10, CodedOutputStream.ComputeEnumSize((int) SampleEnum.NegativeValue)); + + byte[] bytes = new byte[10]; + CodedOutputStream output = new CodedOutputStream(bytes); + output.WriteEnum((int) SampleEnum.NegativeValue); + + Assert.AreEqual(0, output.SpaceLeft); + Assert.AreEqual("FE-FF-FF-FF-FF-FF-FF-FF-FF-01", BitConverter.ToString(bytes)); + } + + [Test] + public void TestCodedInputOutputPosition() + { + byte[] content = new byte[110]; + for (int i = 0; i < content.Length; i++) + content[i] = (byte)i; + + byte[] child = new byte[120]; + { + MemoryStream ms = new MemoryStream(child); + CodedOutputStream cout = new CodedOutputStream(ms, 20); + // Field 11: numeric value: 500 + cout.WriteTag(11, WireFormat.WireType.Varint); + Assert.AreEqual(1, cout.Position); + cout.WriteInt32(500); + Assert.AreEqual(3, cout.Position); + //Field 12: length delimited 120 bytes + cout.WriteTag(12, WireFormat.WireType.LengthDelimited); + Assert.AreEqual(4, cout.Position); + cout.WriteBytes(ByteString.CopyFrom(content)); + Assert.AreEqual(115, cout.Position); + // Field 13: fixed numeric value: 501 + cout.WriteTag(13, WireFormat.WireType.Fixed32); + Assert.AreEqual(116, cout.Position); + cout.WriteSFixed32(501); + Assert.AreEqual(120, cout.Position); + cout.Flush(); + } + + byte[] bytes = new byte[130]; + { + CodedOutputStream cout = new CodedOutputStream(bytes); + // Field 1: numeric value: 500 + cout.WriteTag(1, WireFormat.WireType.Varint); + Assert.AreEqual(1, cout.Position); + cout.WriteInt32(500); + Assert.AreEqual(3, cout.Position); + //Field 2: length delimited 120 bytes + cout.WriteTag(2, WireFormat.WireType.LengthDelimited); + Assert.AreEqual(4, cout.Position); + cout.WriteBytes(ByteString.CopyFrom(child)); + Assert.AreEqual(125, cout.Position); + // Field 3: fixed numeric value: 500 + cout.WriteTag(3, WireFormat.WireType.Fixed32); + Assert.AreEqual(126, cout.Position); + cout.WriteSFixed32(501); + Assert.AreEqual(130, cout.Position); + cout.Flush(); + } + // Now test Input stream: + { + CodedInputStream cin = new CodedInputStream(new MemoryStream(bytes), new byte[50], 0, 0, false); + Assert.AreEqual(0, cin.Position); + // Field 1: + uint tag = cin.ReadTag(); + Assert.AreEqual(1, tag >> 3); + Assert.AreEqual(1, cin.Position); + Assert.AreEqual(500, cin.ReadInt32()); + Assert.AreEqual(3, cin.Position); + //Field 2: + tag = cin.ReadTag(); + Assert.AreEqual(2, tag >> 3); + Assert.AreEqual(4, cin.Position); + int childlen = cin.ReadLength(); + Assert.AreEqual(120, childlen); + Assert.AreEqual(5, cin.Position); + int oldlimit = cin.PushLimit((int)childlen); + Assert.AreEqual(5, cin.Position); + // Now we are reading child message + { + // Field 11: numeric value: 500 + tag = cin.ReadTag(); + Assert.AreEqual(11, tag >> 3); + Assert.AreEqual(6, cin.Position); + Assert.AreEqual(500, cin.ReadInt32()); + Assert.AreEqual(8, cin.Position); + //Field 12: length delimited 120 bytes + tag = cin.ReadTag(); + Assert.AreEqual(12, tag >> 3); + Assert.AreEqual(9, cin.Position); + ByteString bstr = cin.ReadBytes(); + Assert.AreEqual(110, bstr.Length); + Assert.AreEqual((byte) 109, bstr[109]); + Assert.AreEqual(120, cin.Position); + // Field 13: fixed numeric value: 501 + tag = cin.ReadTag(); + Assert.AreEqual(13, tag >> 3); + // ROK - Previously broken here, this returned 126 failing to account for bufferSizeAfterLimit + Assert.AreEqual(121, cin.Position); + Assert.AreEqual(501, cin.ReadSFixed32()); + Assert.AreEqual(125, cin.Position); + Assert.IsTrue(cin.IsAtEnd); + } + cin.PopLimit(oldlimit); + Assert.AreEqual(125, cin.Position); + // Field 3: fixed numeric value: 501 + tag = cin.ReadTag(); + Assert.AreEqual(3, tag >> 3); + Assert.AreEqual(126, cin.Position); + Assert.AreEqual(501, cin.ReadSFixed32()); + Assert.AreEqual(130, cin.Position); + Assert.IsTrue(cin.IsAtEnd); + } + } + + [Test] + public void Dispose_DisposesUnderlyingStream() + { + var memoryStream = new MemoryStream(); + Assert.IsTrue(memoryStream.CanWrite); + using (var cos = new CodedOutputStream(memoryStream)) + { + cos.WriteRawByte(0); + Assert.AreEqual(0, memoryStream.Position); // Not flushed yet + } + Assert.AreEqual(1, memoryStream.ToArray().Length); // Flushed data from CodedOutputStream to MemoryStream + Assert.IsFalse(memoryStream.CanWrite); // Disposed + } + + [Test] + public void Dispose_WithLeaveOpen() + { + var memoryStream = new MemoryStream(); + Assert.IsTrue(memoryStream.CanWrite); + using (var cos = new CodedOutputStream(memoryStream, true)) + { + cos.WriteRawByte(0); + Assert.AreEqual(0, memoryStream.Position); // Not flushed yet + } + Assert.AreEqual(1, memoryStream.Position); // Flushed data from CodedOutputStream to MemoryStream + Assert.IsTrue(memoryStream.CanWrite); // We left the stream open + } + } }
\ No newline at end of file diff --git a/third_party/protobuf/3.4.0/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/DeprecatedMemberTest.cs b/third_party/protobuf/3.4.0/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/DeprecatedMemberTest.cs index 34d5b9f98c..8dfad8b331 100644 --- a/third_party/protobuf/3.4.0/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/DeprecatedMemberTest.cs +++ b/third_party/protobuf/3.4.0/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/DeprecatedMemberTest.cs @@ -1,55 +1,55 @@ -#region Copyright notice and license
-// Protocol Buffers - Google's data interchange format
-// Copyright 2015 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-#endregion
-
-using System;
-using System.Reflection;
-using Google.Protobuf.TestProtos;
-using NUnit.Framework;
-
-namespace Google.Protobuf
-{
- public class DeprecatedMemberTest
- {
- private static void AssertIsDeprecated(MemberInfo member)
- {
- Assert.NotNull(member);
- Assert.IsTrue(member.IsDefined(typeof(ObsoleteAttribute), false), "Member not obsolete: " + member);
- }
-
- [Test]
- public void TestDepreatedPrimitiveValue()
- {
- AssertIsDeprecated(typeof(TestDeprecatedFields).GetProperty("DeprecatedInt32"));
- }
-
- }
-}
+#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + +using System; +using System.Reflection; +using Google.Protobuf.TestProtos; +using NUnit.Framework; + +namespace Google.Protobuf +{ + public class DeprecatedMemberTest + { + private static void AssertIsDeprecated(MemberInfo member) + { + Assert.NotNull(member); + Assert.IsTrue(member.IsDefined(typeof(ObsoleteAttribute), false), "Member not obsolete: " + member); + } + + [Test] + public void TestDepreatedPrimitiveValue() + { + AssertIsDeprecated(typeof(TestDeprecatedFields).GetProperty("DeprecatedInt32")); + } + + } +} diff --git a/third_party/protobuf/3.4.0/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/GeneratedMessageTest.cs b/third_party/protobuf/3.4.0/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/GeneratedMessageTest.cs index 8b153d691f..b029551c0b 100644 --- a/third_party/protobuf/3.4.0/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/GeneratedMessageTest.cs +++ b/third_party/protobuf/3.4.0/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/GeneratedMessageTest.cs @@ -1,723 +1,723 @@ -#region Copyright notice and license
-// Protocol Buffers - Google's data interchange format
-// Copyright 2015 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-#endregion
-
-using System;
-using System.IO;
-using Google.Protobuf.TestProtos;
-using NUnit.Framework;
-using System.Collections;
-using System.Collections.Generic;
-using System.Linq;
-using Google.Protobuf.WellKnownTypes;
-
-namespace Google.Protobuf
-{
- /// <summary>
- /// Tests around the generated TestAllTypes message.
- /// </summary>
- public class GeneratedMessageTest
- {
- [Test]
- public void EmptyMessageFieldDistinctFromMissingMessageField()
- {
- // This demonstrates what we're really interested in...
- var message1 = new TestAllTypes { SingleForeignMessage = new ForeignMessage() };
- var message2 = new TestAllTypes(); // SingleForeignMessage is null
- EqualityTester.AssertInequality(message1, message2);
- }
-
- [Test]
- public void DefaultValues()
- {
- // Single fields
- var message = new TestAllTypes();
- Assert.AreEqual(false, message.SingleBool);
- Assert.AreEqual(ByteString.Empty, message.SingleBytes);
- Assert.AreEqual(0.0, message.SingleDouble);
- Assert.AreEqual(0, message.SingleFixed32);
- Assert.AreEqual(0L, message.SingleFixed64);
- Assert.AreEqual(0.0f, message.SingleFloat);
- Assert.AreEqual(ForeignEnum.ForeignUnspecified, message.SingleForeignEnum);
- Assert.IsNull(message.SingleForeignMessage);
- Assert.AreEqual(ImportEnum.Unspecified, message.SingleImportEnum);
- Assert.IsNull(message.SingleImportMessage);
- Assert.AreEqual(0, message.SingleInt32);
- Assert.AreEqual(0L, message.SingleInt64);
- Assert.AreEqual(TestAllTypes.Types.NestedEnum.Unspecified, message.SingleNestedEnum);
- Assert.IsNull(message.SingleNestedMessage);
- Assert.IsNull(message.SinglePublicImportMessage);
- Assert.AreEqual(0, message.SingleSfixed32);
- Assert.AreEqual(0L, message.SingleSfixed64);
- Assert.AreEqual(0, message.SingleSint32);
- Assert.AreEqual(0L, message.SingleSint64);
- Assert.AreEqual("", message.SingleString);
- Assert.AreEqual(0U, message.SingleUint32);
- Assert.AreEqual(0UL, message.SingleUint64);
-
- // Repeated fields
- Assert.AreEqual(0, message.RepeatedBool.Count);
- Assert.AreEqual(0, message.RepeatedBytes.Count);
- Assert.AreEqual(0, message.RepeatedDouble.Count);
- Assert.AreEqual(0, message.RepeatedFixed32.Count);
- Assert.AreEqual(0, message.RepeatedFixed64.Count);
- Assert.AreEqual(0, message.RepeatedFloat.Count);
- Assert.AreEqual(0, message.RepeatedForeignEnum.Count);
- Assert.AreEqual(0, message.RepeatedForeignMessage.Count);
- Assert.AreEqual(0, message.RepeatedImportEnum.Count);
- Assert.AreEqual(0, message.RepeatedImportMessage.Count);
- Assert.AreEqual(0, message.RepeatedNestedEnum.Count);
- Assert.AreEqual(0, message.RepeatedNestedMessage.Count);
- Assert.AreEqual(0, message.RepeatedPublicImportMessage.Count);
- Assert.AreEqual(0, message.RepeatedSfixed32.Count);
- Assert.AreEqual(0, message.RepeatedSfixed64.Count);
- Assert.AreEqual(0, message.RepeatedSint32.Count);
- Assert.AreEqual(0, message.RepeatedSint64.Count);
- Assert.AreEqual(0, message.RepeatedString.Count);
- Assert.AreEqual(0, message.RepeatedUint32.Count);
- Assert.AreEqual(0, message.RepeatedUint64.Count);
-
- // Oneof fields
- Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.None, message.OneofFieldCase);
- Assert.AreEqual(0, message.OneofUint32);
- Assert.AreEqual("", message.OneofString);
- Assert.AreEqual(ByteString.Empty, message.OneofBytes);
- Assert.IsNull(message.OneofNestedMessage);
- }
-
- [Test]
- public void NullStringAndBytesRejected()
- {
- var message = new TestAllTypes();
- Assert.Throws<ArgumentNullException>(() => message.SingleString = null);
- Assert.Throws<ArgumentNullException>(() => message.OneofString = null);
- Assert.Throws<ArgumentNullException>(() => message.SingleBytes = null);
- Assert.Throws<ArgumentNullException>(() => message.OneofBytes = null);
- }
-
- [Test]
- public void RoundTrip_Empty()
- {
- var message = new TestAllTypes();
- // Without setting any values, there's nothing to write.
- byte[] bytes = message.ToByteArray();
- Assert.AreEqual(0, bytes.Length);
- TestAllTypes parsed = TestAllTypes.Parser.ParseFrom(bytes);
- Assert.AreEqual(message, parsed);
- }
-
- [Test]
- public void RoundTrip_SingleValues()
- {
- var message = new TestAllTypes
- {
- SingleBool = true,
- SingleBytes = ByteString.CopyFrom(1, 2, 3, 4),
- SingleDouble = 23.5,
- SingleFixed32 = 23,
- SingleFixed64 = 1234567890123,
- SingleFloat = 12.25f,
- SingleForeignEnum = ForeignEnum.ForeignBar,
- SingleForeignMessage = new ForeignMessage { C = 10 },
- SingleImportEnum = ImportEnum.ImportBaz,
- SingleImportMessage = new ImportMessage { D = 20 },
- SingleInt32 = 100,
- SingleInt64 = 3210987654321,
- SingleNestedEnum = TestAllTypes.Types.NestedEnum.Foo,
- SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 35 },
- SinglePublicImportMessage = new PublicImportMessage { E = 54 },
- SingleSfixed32 = -123,
- SingleSfixed64 = -12345678901234,
- SingleSint32 = -456,
- SingleSint64 = -12345678901235,
- SingleString = "test",
- SingleUint32 = uint.MaxValue,
- SingleUint64 = ulong.MaxValue
- };
-
- byte[] bytes = message.ToByteArray();
- TestAllTypes parsed = TestAllTypes.Parser.ParseFrom(bytes);
- Assert.AreEqual(message, parsed);
- }
-
- [Test]
- public void RoundTrip_RepeatedValues()
- {
- var message = new TestAllTypes
- {
- RepeatedBool = { true, false },
- RepeatedBytes = { ByteString.CopyFrom(1, 2, 3, 4), ByteString.CopyFrom(5, 6) },
- RepeatedDouble = { -12.25, 23.5 },
- RepeatedFixed32 = { uint.MaxValue, 23 },
- RepeatedFixed64 = { ulong.MaxValue, 1234567890123 },
- RepeatedFloat = { 100f, 12.25f },
- RepeatedForeignEnum = { ForeignEnum.ForeignFoo, ForeignEnum.ForeignBar },
- RepeatedForeignMessage = { new ForeignMessage(), new ForeignMessage { C = 10 } },
- RepeatedImportEnum = { ImportEnum.ImportBaz, ImportEnum.Unspecified },
- RepeatedImportMessage = { new ImportMessage { D = 20 }, new ImportMessage { D = 25 } },
- RepeatedInt32 = { 100, 200 },
- RepeatedInt64 = { 3210987654321, long.MaxValue },
- RepeatedNestedEnum = { TestAllTypes.Types.NestedEnum.Foo, TestAllTypes.Types.NestedEnum.Neg },
- RepeatedNestedMessage = { new TestAllTypes.Types.NestedMessage { Bb = 35 }, new TestAllTypes.Types.NestedMessage { Bb = 10 } },
- RepeatedPublicImportMessage = { new PublicImportMessage { E = 54 }, new PublicImportMessage { E = -1 } },
- RepeatedSfixed32 = { -123, 123 },
- RepeatedSfixed64 = { -12345678901234, 12345678901234 },
- RepeatedSint32 = { -456, 100 },
- RepeatedSint64 = { -12345678901235, 123 },
- RepeatedString = { "foo", "bar" },
- RepeatedUint32 = { uint.MaxValue, uint.MinValue },
- RepeatedUint64 = { ulong.MaxValue, uint.MinValue }
- };
-
- byte[] bytes = message.ToByteArray();
- TestAllTypes parsed = TestAllTypes.Parser.ParseFrom(bytes);
- Assert.AreEqual(message, parsed);
- }
-
- // Note that not every map within map_unittest_proto3 is used. They all go through very
- // similar code paths. The fact that all maps are present is validation that we have codecs
- // for every type.
- [Test]
- public void RoundTrip_Maps()
- {
- var message = new TestMap
- {
- MapBoolBool = {
- { false, true },
- { true, false }
- },
- MapInt32Bytes = {
- { 5, ByteString.CopyFrom(6, 7, 8) },
- { 25, ByteString.CopyFrom(1, 2, 3, 4, 5) },
- { 10, ByteString.Empty }
- },
- MapInt32ForeignMessage = {
- { 0, new ForeignMessage { C = 10 } },
- { 5, new ForeignMessage() },
- },
- MapInt32Enum = {
- { 1, MapEnum.Bar },
- { 2000, MapEnum.Foo }
- }
- };
-
- byte[] bytes = message.ToByteArray();
- TestMap parsed = TestMap.Parser.ParseFrom(bytes);
- Assert.AreEqual(message, parsed);
- }
-
- [Test]
- public void MapWithEmptyEntry()
- {
- var message = new TestMap
- {
- MapInt32Bytes = { { 0, ByteString.Empty } }
- };
-
- byte[] bytes = message.ToByteArray();
- Assert.AreEqual(2, bytes.Length); // Tag for field entry (1 byte), length of entry (0; 1 byte)
-
- var parsed = TestMap.Parser.ParseFrom(bytes);
- Assert.AreEqual(1, parsed.MapInt32Bytes.Count);
- Assert.AreEqual(ByteString.Empty, parsed.MapInt32Bytes[0]);
- }
-
- [Test]
- public void MapWithOnlyValue()
- {
- // Hand-craft the stream to contain a single entry with just a value.
- var memoryStream = new MemoryStream();
- var output = new CodedOutputStream(memoryStream);
- output.WriteTag(TestMap.MapInt32ForeignMessageFieldNumber, WireFormat.WireType.LengthDelimited);
- var nestedMessage = new ForeignMessage { C = 20 };
- // Size of the entry (tag, size written by WriteMessage, data written by WriteMessage)
- output.WriteLength(2 + nestedMessage.CalculateSize());
- output.WriteTag(2, WireFormat.WireType.LengthDelimited);
- output.WriteMessage(nestedMessage);
- output.Flush();
-
- var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray());
- Assert.AreEqual(nestedMessage, parsed.MapInt32ForeignMessage[0]);
- }
-
- [Test]
- public void MapWithOnlyKey_PrimitiveValue()
- {
- // Hand-craft the stream to contain a single entry with just a key.
- var memoryStream = new MemoryStream();
- var output = new CodedOutputStream(memoryStream);
- output.WriteTag(TestMap.MapInt32DoubleFieldNumber, WireFormat.WireType.LengthDelimited);
- int key = 10;
- output.WriteLength(1 + CodedOutputStream.ComputeInt32Size(key));
- output.WriteTag(1, WireFormat.WireType.Varint);
- output.WriteInt32(key);
- output.Flush();
-
- var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray());
- Assert.AreEqual(0.0, parsed.MapInt32Double[key]);
- }
-
- [Test]
- public void MapWithOnlyKey_MessageValue()
- {
- // Hand-craft the stream to contain a single entry with just a key.
- var memoryStream = new MemoryStream();
- var output = new CodedOutputStream(memoryStream);
- output.WriteTag(TestMap.MapInt32ForeignMessageFieldNumber, WireFormat.WireType.LengthDelimited);
- int key = 10;
- output.WriteLength(1 + CodedOutputStream.ComputeInt32Size(key));
- output.WriteTag(1, WireFormat.WireType.Varint);
- output.WriteInt32(key);
- output.Flush();
-
- var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray());
- Assert.AreEqual(new ForeignMessage(), parsed.MapInt32ForeignMessage[key]);
- }
-
- [Test]
- public void MapIgnoresExtraFieldsWithinEntryMessages()
- {
- // Hand-craft the stream to contain a single entry with three fields
- var memoryStream = new MemoryStream();
- var output = new CodedOutputStream(memoryStream);
-
- output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited);
-
- var key = 10; // Field 1
- var value = 20; // Field 2
- var extra = 30; // Field 3
-
- // Each field can be represented in a single byte, with a single byte tag.
- // Total message size: 6 bytes.
- output.WriteLength(6);
- output.WriteTag(1, WireFormat.WireType.Varint);
- output.WriteInt32(key);
- output.WriteTag(2, WireFormat.WireType.Varint);
- output.WriteInt32(value);
- output.WriteTag(3, WireFormat.WireType.Varint);
- output.WriteInt32(extra);
- output.Flush();
-
- var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray());
- Assert.AreEqual(value, parsed.MapInt32Int32[key]);
- }
-
- [Test]
- public void MapFieldOrderIsIrrelevant()
- {
- var memoryStream = new MemoryStream();
- var output = new CodedOutputStream(memoryStream);
-
- output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited);
-
- var key = 10;
- var value = 20;
-
- // Each field can be represented in a single byte, with a single byte tag.
- // Total message size: 4 bytes.
- output.WriteLength(4);
- output.WriteTag(2, WireFormat.WireType.Varint);
- output.WriteInt32(value);
- output.WriteTag(1, WireFormat.WireType.Varint);
- output.WriteInt32(key);
- output.Flush();
-
- var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray());
- Assert.AreEqual(value, parsed.MapInt32Int32[key]);
- }
-
- [Test]
- public void MapNonContiguousEntries()
- {
- var memoryStream = new MemoryStream();
- var output = new CodedOutputStream(memoryStream);
-
- // Message structure:
- // Entry for MapInt32Int32
- // Entry for MapStringString
- // Entry for MapInt32Int32
-
- // First entry
- var key1 = 10;
- var value1 = 20;
- output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited);
- output.WriteLength(4);
- output.WriteTag(1, WireFormat.WireType.Varint);
- output.WriteInt32(key1);
- output.WriteTag(2, WireFormat.WireType.Varint);
- output.WriteInt32(value1);
-
- // Second entry
- var key2 = "a";
- var value2 = "b";
- output.WriteTag(TestMap.MapStringStringFieldNumber, WireFormat.WireType.LengthDelimited);
- output.WriteLength(6); // 3 bytes per entry: tag, size, character
- output.WriteTag(1, WireFormat.WireType.LengthDelimited);
- output.WriteString(key2);
- output.WriteTag(2, WireFormat.WireType.LengthDelimited);
- output.WriteString(value2);
-
- // Third entry
- var key3 = 15;
- var value3 = 25;
- output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited);
- output.WriteLength(4);
- output.WriteTag(1, WireFormat.WireType.Varint);
- output.WriteInt32(key3);
- output.WriteTag(2, WireFormat.WireType.Varint);
- output.WriteInt32(value3);
-
- output.Flush();
- var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray());
- var expected = new TestMap
- {
- MapInt32Int32 = { { key1, value1 }, { key3, value3 } },
- MapStringString = { { key2, value2 } }
- };
- Assert.AreEqual(expected, parsed);
- }
-
- [Test]
- public void DuplicateKeys_LastEntryWins()
- {
- var memoryStream = new MemoryStream();
- var output = new CodedOutputStream(memoryStream);
-
- var key = 10;
- var value1 = 20;
- var value2 = 30;
-
- // First entry
- output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited);
- output.WriteLength(4);
- output.WriteTag(1, WireFormat.WireType.Varint);
- output.WriteInt32(key);
- output.WriteTag(2, WireFormat.WireType.Varint);
- output.WriteInt32(value1);
-
- // Second entry - same key, different value
- output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited);
- output.WriteLength(4);
- output.WriteTag(1, WireFormat.WireType.Varint);
- output.WriteInt32(key);
- output.WriteTag(2, WireFormat.WireType.Varint);
- output.WriteInt32(value2);
- output.Flush();
-
- var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray());
- Assert.AreEqual(value2, parsed.MapInt32Int32[key]);
- }
-
- [Test]
- public void CloneSingleNonMessageValues()
- {
- var original = new TestAllTypes
- {
- SingleBool = true,
- SingleBytes = ByteString.CopyFrom(1, 2, 3, 4),
- SingleDouble = 23.5,
- SingleFixed32 = 23,
- SingleFixed64 = 1234567890123,
- SingleFloat = 12.25f,
- SingleInt32 = 100,
- SingleInt64 = 3210987654321,
- SingleNestedEnum = TestAllTypes.Types.NestedEnum.Foo,
- SingleSfixed32 = -123,
- SingleSfixed64 = -12345678901234,
- SingleSint32 = -456,
- SingleSint64 = -12345678901235,
- SingleString = "test",
- SingleUint32 = uint.MaxValue,
- SingleUint64 = ulong.MaxValue
- };
- var clone = original.Clone();
- Assert.AreNotSame(original, clone);
- Assert.AreEqual(original, clone);
- // Just as a single example
- clone.SingleInt32 = 150;
- Assert.AreNotEqual(original, clone);
- }
-
- [Test]
- public void CloneRepeatedNonMessageValues()
- {
- var original = new TestAllTypes
- {
- RepeatedBool = { true, false },
- RepeatedBytes = { ByteString.CopyFrom(1, 2, 3, 4), ByteString.CopyFrom(5, 6) },
- RepeatedDouble = { -12.25, 23.5 },
- RepeatedFixed32 = { uint.MaxValue, 23 },
- RepeatedFixed64 = { ulong.MaxValue, 1234567890123 },
- RepeatedFloat = { 100f, 12.25f },
- RepeatedInt32 = { 100, 200 },
- RepeatedInt64 = { 3210987654321, long.MaxValue },
- RepeatedNestedEnum = { TestAllTypes.Types.NestedEnum.Foo, TestAllTypes.Types.NestedEnum.Neg },
- RepeatedSfixed32 = { -123, 123 },
- RepeatedSfixed64 = { -12345678901234, 12345678901234 },
- RepeatedSint32 = { -456, 100 },
- RepeatedSint64 = { -12345678901235, 123 },
- RepeatedString = { "foo", "bar" },
- RepeatedUint32 = { uint.MaxValue, uint.MinValue },
- RepeatedUint64 = { ulong.MaxValue, uint.MinValue }
- };
-
- var clone = original.Clone();
- Assert.AreNotSame(original, clone);
- Assert.AreEqual(original, clone);
- // Just as a single example
- clone.RepeatedDouble.Add(25.5);
- Assert.AreNotEqual(original, clone);
- }
-
- [Test]
- public void CloneSingleMessageField()
- {
- var original = new TestAllTypes
- {
- SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 20 }
- };
-
- var clone = original.Clone();
- Assert.AreNotSame(original, clone);
- Assert.AreNotSame(original.SingleNestedMessage, clone.SingleNestedMessage);
- Assert.AreEqual(original, clone);
-
- clone.SingleNestedMessage.Bb = 30;
- Assert.AreNotEqual(original, clone);
- }
-
- [Test]
- public void CloneRepeatedMessageField()
- {
- var original = new TestAllTypes
- {
- RepeatedNestedMessage = { new TestAllTypes.Types.NestedMessage { Bb = 20 } }
- };
-
- var clone = original.Clone();
- Assert.AreNotSame(original, clone);
- Assert.AreNotSame(original.RepeatedNestedMessage, clone.RepeatedNestedMessage);
- Assert.AreNotSame(original.RepeatedNestedMessage[0], clone.RepeatedNestedMessage[0]);
- Assert.AreEqual(original, clone);
-
- clone.RepeatedNestedMessage[0].Bb = 30;
- Assert.AreNotEqual(original, clone);
- }
-
- [Test]
- public void CloneOneofField()
- {
- var original = new TestAllTypes
- {
- OneofNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 20 }
- };
-
- var clone = original.Clone();
- Assert.AreNotSame(original, clone);
- Assert.AreEqual(original, clone);
-
- // We should have cloned the message
- original.OneofNestedMessage.Bb = 30;
- Assert.AreNotEqual(original, clone);
- }
-
- [Test]
- public void OneofProperties()
- {
- // Switch the oneof case between each of the different options, and check everything behaves
- // as expected in each case.
- var message = new TestAllTypes();
- Assert.AreEqual("", message.OneofString);
- Assert.AreEqual(0, message.OneofUint32);
- Assert.AreEqual(ByteString.Empty, message.OneofBytes);
- Assert.IsNull(message.OneofNestedMessage);
- Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.None, message.OneofFieldCase);
-
- message.OneofString = "sample";
- Assert.AreEqual("sample", message.OneofString);
- Assert.AreEqual(0, message.OneofUint32);
- Assert.AreEqual(ByteString.Empty, message.OneofBytes);
- Assert.IsNull(message.OneofNestedMessage);
- Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofString, message.OneofFieldCase);
-
- var bytes = ByteString.CopyFrom(1, 2, 3);
- message.OneofBytes = bytes;
- Assert.AreEqual("", message.OneofString);
- Assert.AreEqual(0, message.OneofUint32);
- Assert.AreEqual(bytes, message.OneofBytes);
- Assert.IsNull(message.OneofNestedMessage);
- Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofBytes, message.OneofFieldCase);
-
- message.OneofUint32 = 20;
- Assert.AreEqual("", message.OneofString);
- Assert.AreEqual(20, message.OneofUint32);
- Assert.AreEqual(ByteString.Empty, message.OneofBytes);
- Assert.IsNull(message.OneofNestedMessage);
- Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofUint32, message.OneofFieldCase);
-
- var nestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 25 };
- message.OneofNestedMessage = nestedMessage;
- Assert.AreEqual("", message.OneofString);
- Assert.AreEqual(0, message.OneofUint32);
- Assert.AreEqual(ByteString.Empty, message.OneofBytes);
- Assert.AreEqual(nestedMessage, message.OneofNestedMessage);
- Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofNestedMessage, message.OneofFieldCase);
-
- message.ClearOneofField();
- Assert.AreEqual("", message.OneofString);
- Assert.AreEqual(0, message.OneofUint32);
- Assert.AreEqual(ByteString.Empty, message.OneofBytes);
- Assert.IsNull(message.OneofNestedMessage);
- Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.None, message.OneofFieldCase);
- }
-
- [Test]
- public void Oneof_DefaultValuesNotEqual()
- {
- var message1 = new TestAllTypes { OneofString = "" };
- var message2 = new TestAllTypes { OneofUint32 = 0 };
- Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofString, message1.OneofFieldCase);
- Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofUint32, message2.OneofFieldCase);
- Assert.AreNotEqual(message1, message2);
- }
-
- [Test]
- public void OneofSerialization_NonDefaultValue()
- {
- var message = new TestAllTypes();
- message.OneofString = "this would take a bit of space";
- message.OneofUint32 = 10;
- var bytes = message.ToByteArray();
- Assert.AreEqual(3, bytes.Length); // 2 bytes for the tag + 1 for the value - no string!
-
- var message2 = TestAllTypes.Parser.ParseFrom(bytes);
- Assert.AreEqual(message, message2);
- Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofUint32, message2.OneofFieldCase);
- }
-
- [Test]
- public void OneofSerialization_DefaultValue()
- {
- var message = new TestAllTypes();
- message.OneofString = "this would take a bit of space";
- message.OneofUint32 = 0; // This is the default value for UInt32; normally wouldn't be serialized
- var bytes = message.ToByteArray();
- Assert.AreEqual(3, bytes.Length); // 2 bytes for the tag + 1 for the value - it's still serialized
-
- var message2 = TestAllTypes.Parser.ParseFrom(bytes);
- Assert.AreEqual(message, message2);
- Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofUint32, message2.OneofFieldCase);
- }
-
- [Test]
- public void IgnoreUnknownFields_RealDataStillRead()
- {
- var message = SampleMessages.CreateFullTestAllTypes();
- var stream = new MemoryStream();
- var output = new CodedOutputStream(stream);
- var unusedFieldNumber = 23456;
- Assert.IsFalse(TestAllTypes.Descriptor.Fields.InDeclarationOrder().Select(x => x.FieldNumber).Contains(unusedFieldNumber));
- output.WriteTag(unusedFieldNumber, WireFormat.WireType.LengthDelimited);
- output.WriteString("ignore me");
- message.WriteTo(output);
- output.Flush();
-
- stream.Position = 0;
- var parsed = TestAllTypes.Parser.ParseFrom(stream);
- Assert.AreEqual(message, parsed);
- }
-
- [Test]
- public void IgnoreUnknownFields_AllTypes()
- {
- // Simple way of ensuring we can skip all kinds of fields.
- var data = SampleMessages.CreateFullTestAllTypes().ToByteArray();
- var empty = Empty.Parser.ParseFrom(data);
- Assert.AreEqual(new Empty(), empty);
- }
-
- // This was originally seen as a conformance test failure.
- [Test]
- public void TruncatedMessageFieldThrows()
- {
- // 130, 3 is the message tag
- // 1 is the data length - but there's no data.
- var data = new byte[] { 130, 3, 1 };
- Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseFrom(data));
- }
-
- /// <summary>
- /// Demonstrates current behaviour with an extraneous end group tag - see issue 688
- /// for details; we may want to change this.
- /// </summary>
- [Test]
- public void ExtraEndGroupThrows()
- {
- var message = SampleMessages.CreateFullTestAllTypes();
- var stream = new MemoryStream();
- var output = new CodedOutputStream(stream);
-
- output.WriteTag(TestAllTypes.SingleFixed32FieldNumber, WireFormat.WireType.Fixed32);
- output.WriteFixed32(123);
- output.WriteTag(100, WireFormat.WireType.EndGroup);
-
- output.Flush();
-
- stream.Position = 0;
- Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseFrom(stream));
- }
-
- [Test]
- public void CustomDiagnosticMessage_DirectToStringCall()
- {
- var message = new ForeignMessage { C = 31 };
- Assert.AreEqual("{ \"c\": 31, \"@cInHex\": \"1f\" }", message.ToString());
- Assert.AreEqual("{ \"c\": 31 }", JsonFormatter.Default.Format(message));
- }
-
- [Test]
- public void CustomDiagnosticMessage_Nested()
- {
- var message = new TestAllTypes { SingleForeignMessage = new ForeignMessage { C = 16 } };
- Assert.AreEqual("{ \"singleForeignMessage\": { \"c\": 16, \"@cInHex\": \"10\" } }", message.ToString());
- Assert.AreEqual("{ \"singleForeignMessage\": { \"c\": 16 } }", JsonFormatter.Default.Format(message));
- }
-
- [Test]
- public void CustomDiagnosticMessage_DirectToTextWriterCall()
- {
- var message = new ForeignMessage { C = 31 };
- var writer = new StringWriter();
- JsonFormatter.Default.Format(message, writer);
- Assert.AreEqual("{ \"c\": 31 }", writer.ToString());
- }
- }
+#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + +using System; +using System.IO; +using Google.Protobuf.TestProtos; +using NUnit.Framework; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using Google.Protobuf.WellKnownTypes; + +namespace Google.Protobuf +{ + /// <summary> + /// Tests around the generated TestAllTypes message. + /// </summary> + public class GeneratedMessageTest + { + [Test] + public void EmptyMessageFieldDistinctFromMissingMessageField() + { + // This demonstrates what we're really interested in... + var message1 = new TestAllTypes { SingleForeignMessage = new ForeignMessage() }; + var message2 = new TestAllTypes(); // SingleForeignMessage is null + EqualityTester.AssertInequality(message1, message2); + } + + [Test] + public void DefaultValues() + { + // Single fields + var message = new TestAllTypes(); + Assert.AreEqual(false, message.SingleBool); + Assert.AreEqual(ByteString.Empty, message.SingleBytes); + Assert.AreEqual(0.0, message.SingleDouble); + Assert.AreEqual(0, message.SingleFixed32); + Assert.AreEqual(0L, message.SingleFixed64); + Assert.AreEqual(0.0f, message.SingleFloat); + Assert.AreEqual(ForeignEnum.ForeignUnspecified, message.SingleForeignEnum); + Assert.IsNull(message.SingleForeignMessage); + Assert.AreEqual(ImportEnum.Unspecified, message.SingleImportEnum); + Assert.IsNull(message.SingleImportMessage); + Assert.AreEqual(0, message.SingleInt32); + Assert.AreEqual(0L, message.SingleInt64); + Assert.AreEqual(TestAllTypes.Types.NestedEnum.Unspecified, message.SingleNestedEnum); + Assert.IsNull(message.SingleNestedMessage); + Assert.IsNull(message.SinglePublicImportMessage); + Assert.AreEqual(0, message.SingleSfixed32); + Assert.AreEqual(0L, message.SingleSfixed64); + Assert.AreEqual(0, message.SingleSint32); + Assert.AreEqual(0L, message.SingleSint64); + Assert.AreEqual("", message.SingleString); + Assert.AreEqual(0U, message.SingleUint32); + Assert.AreEqual(0UL, message.SingleUint64); + + // Repeated fields + Assert.AreEqual(0, message.RepeatedBool.Count); + Assert.AreEqual(0, message.RepeatedBytes.Count); + Assert.AreEqual(0, message.RepeatedDouble.Count); + Assert.AreEqual(0, message.RepeatedFixed32.Count); + Assert.AreEqual(0, message.RepeatedFixed64.Count); + Assert.AreEqual(0, message.RepeatedFloat.Count); + Assert.AreEqual(0, message.RepeatedForeignEnum.Count); + Assert.AreEqual(0, message.RepeatedForeignMessage.Count); + Assert.AreEqual(0, message.RepeatedImportEnum.Count); + Assert.AreEqual(0, message.RepeatedImportMessage.Count); + Assert.AreEqual(0, message.RepeatedNestedEnum.Count); + Assert.AreEqual(0, message.RepeatedNestedMessage.Count); + Assert.AreEqual(0, message.RepeatedPublicImportMessage.Count); + Assert.AreEqual(0, message.RepeatedSfixed32.Count); + Assert.AreEqual(0, message.RepeatedSfixed64.Count); + Assert.AreEqual(0, message.RepeatedSint32.Count); + Assert.AreEqual(0, message.RepeatedSint64.Count); + Assert.AreEqual(0, message.RepeatedString.Count); + Assert.AreEqual(0, message.RepeatedUint32.Count); + Assert.AreEqual(0, message.RepeatedUint64.Count); + + // Oneof fields + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.None, message.OneofFieldCase); + Assert.AreEqual(0, message.OneofUint32); + Assert.AreEqual("", message.OneofString); + Assert.AreEqual(ByteString.Empty, message.OneofBytes); + Assert.IsNull(message.OneofNestedMessage); + } + + [Test] + public void NullStringAndBytesRejected() + { + var message = new TestAllTypes(); + Assert.Throws<ArgumentNullException>(() => message.SingleString = null); + Assert.Throws<ArgumentNullException>(() => message.OneofString = null); + Assert.Throws<ArgumentNullException>(() => message.SingleBytes = null); + Assert.Throws<ArgumentNullException>(() => message.OneofBytes = null); + } + + [Test] + public void RoundTrip_Empty() + { + var message = new TestAllTypes(); + // Without setting any values, there's nothing to write. + byte[] bytes = message.ToByteArray(); + Assert.AreEqual(0, bytes.Length); + TestAllTypes parsed = TestAllTypes.Parser.ParseFrom(bytes); + Assert.AreEqual(message, parsed); + } + + [Test] + public void RoundTrip_SingleValues() + { + var message = new TestAllTypes + { + SingleBool = true, + SingleBytes = ByteString.CopyFrom(1, 2, 3, 4), + SingleDouble = 23.5, + SingleFixed32 = 23, + SingleFixed64 = 1234567890123, + SingleFloat = 12.25f, + SingleForeignEnum = ForeignEnum.ForeignBar, + SingleForeignMessage = new ForeignMessage { C = 10 }, + SingleImportEnum = ImportEnum.ImportBaz, + SingleImportMessage = new ImportMessage { D = 20 }, + SingleInt32 = 100, + SingleInt64 = 3210987654321, + SingleNestedEnum = TestAllTypes.Types.NestedEnum.Foo, + SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 35 }, + SinglePublicImportMessage = new PublicImportMessage { E = 54 }, + SingleSfixed32 = -123, + SingleSfixed64 = -12345678901234, + SingleSint32 = -456, + SingleSint64 = -12345678901235, + SingleString = "test", + SingleUint32 = uint.MaxValue, + SingleUint64 = ulong.MaxValue + }; + + byte[] bytes = message.ToByteArray(); + TestAllTypes parsed = TestAllTypes.Parser.ParseFrom(bytes); + Assert.AreEqual(message, parsed); + } + + [Test] + public void RoundTrip_RepeatedValues() + { + var message = new TestAllTypes + { + RepeatedBool = { true, false }, + RepeatedBytes = { ByteString.CopyFrom(1, 2, 3, 4), ByteString.CopyFrom(5, 6) }, + RepeatedDouble = { -12.25, 23.5 }, + RepeatedFixed32 = { uint.MaxValue, 23 }, + RepeatedFixed64 = { ulong.MaxValue, 1234567890123 }, + RepeatedFloat = { 100f, 12.25f }, + RepeatedForeignEnum = { ForeignEnum.ForeignFoo, ForeignEnum.ForeignBar }, + RepeatedForeignMessage = { new ForeignMessage(), new ForeignMessage { C = 10 } }, + RepeatedImportEnum = { ImportEnum.ImportBaz, ImportEnum.Unspecified }, + RepeatedImportMessage = { new ImportMessage { D = 20 }, new ImportMessage { D = 25 } }, + RepeatedInt32 = { 100, 200 }, + RepeatedInt64 = { 3210987654321, long.MaxValue }, + RepeatedNestedEnum = { TestAllTypes.Types.NestedEnum.Foo, TestAllTypes.Types.NestedEnum.Neg }, + RepeatedNestedMessage = { new TestAllTypes.Types.NestedMessage { Bb = 35 }, new TestAllTypes.Types.NestedMessage { Bb = 10 } }, + RepeatedPublicImportMessage = { new PublicImportMessage { E = 54 }, new PublicImportMessage { E = -1 } }, + RepeatedSfixed32 = { -123, 123 }, + RepeatedSfixed64 = { -12345678901234, 12345678901234 }, + RepeatedSint32 = { -456, 100 }, + RepeatedSint64 = { -12345678901235, 123 }, + RepeatedString = { "foo", "bar" }, + RepeatedUint32 = { uint.MaxValue, uint.MinValue }, + RepeatedUint64 = { ulong.MaxValue, uint.MinValue } + }; + + byte[] bytes = message.ToByteArray(); + TestAllTypes parsed = TestAllTypes.Parser.ParseFrom(bytes); + Assert.AreEqual(message, parsed); + } + + // Note that not every map within map_unittest_proto3 is used. They all go through very + // similar code paths. The fact that all maps are present is validation that we have codecs + // for every type. + [Test] + public void RoundTrip_Maps() + { + var message = new TestMap + { + MapBoolBool = { + { false, true }, + { true, false } + }, + MapInt32Bytes = { + { 5, ByteString.CopyFrom(6, 7, 8) }, + { 25, ByteString.CopyFrom(1, 2, 3, 4, 5) }, + { 10, ByteString.Empty } + }, + MapInt32ForeignMessage = { + { 0, new ForeignMessage { C = 10 } }, + { 5, new ForeignMessage() }, + }, + MapInt32Enum = { + { 1, MapEnum.Bar }, + { 2000, MapEnum.Foo } + } + }; + + byte[] bytes = message.ToByteArray(); + TestMap parsed = TestMap.Parser.ParseFrom(bytes); + Assert.AreEqual(message, parsed); + } + + [Test] + public void MapWithEmptyEntry() + { + var message = new TestMap + { + MapInt32Bytes = { { 0, ByteString.Empty } } + }; + + byte[] bytes = message.ToByteArray(); + Assert.AreEqual(2, bytes.Length); // Tag for field entry (1 byte), length of entry (0; 1 byte) + + var parsed = TestMap.Parser.ParseFrom(bytes); + Assert.AreEqual(1, parsed.MapInt32Bytes.Count); + Assert.AreEqual(ByteString.Empty, parsed.MapInt32Bytes[0]); + } + + [Test] + public void MapWithOnlyValue() + { + // Hand-craft the stream to contain a single entry with just a value. + var memoryStream = new MemoryStream(); + var output = new CodedOutputStream(memoryStream); + output.WriteTag(TestMap.MapInt32ForeignMessageFieldNumber, WireFormat.WireType.LengthDelimited); + var nestedMessage = new ForeignMessage { C = 20 }; + // Size of the entry (tag, size written by WriteMessage, data written by WriteMessage) + output.WriteLength(2 + nestedMessage.CalculateSize()); + output.WriteTag(2, WireFormat.WireType.LengthDelimited); + output.WriteMessage(nestedMessage); + output.Flush(); + + var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray()); + Assert.AreEqual(nestedMessage, parsed.MapInt32ForeignMessage[0]); + } + + [Test] + public void MapWithOnlyKey_PrimitiveValue() + { + // Hand-craft the stream to contain a single entry with just a key. + var memoryStream = new MemoryStream(); + var output = new CodedOutputStream(memoryStream); + output.WriteTag(TestMap.MapInt32DoubleFieldNumber, WireFormat.WireType.LengthDelimited); + int key = 10; + output.WriteLength(1 + CodedOutputStream.ComputeInt32Size(key)); + output.WriteTag(1, WireFormat.WireType.Varint); + output.WriteInt32(key); + output.Flush(); + + var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray()); + Assert.AreEqual(0.0, parsed.MapInt32Double[key]); + } + + [Test] + public void MapWithOnlyKey_MessageValue() + { + // Hand-craft the stream to contain a single entry with just a key. + var memoryStream = new MemoryStream(); + var output = new CodedOutputStream(memoryStream); + output.WriteTag(TestMap.MapInt32ForeignMessageFieldNumber, WireFormat.WireType.LengthDelimited); + int key = 10; + output.WriteLength(1 + CodedOutputStream.ComputeInt32Size(key)); + output.WriteTag(1, WireFormat.WireType.Varint); + output.WriteInt32(key); + output.Flush(); + + var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray()); + Assert.AreEqual(new ForeignMessage(), parsed.MapInt32ForeignMessage[key]); + } + + [Test] + public void MapIgnoresExtraFieldsWithinEntryMessages() + { + // Hand-craft the stream to contain a single entry with three fields + var memoryStream = new MemoryStream(); + var output = new CodedOutputStream(memoryStream); + + output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited); + + var key = 10; // Field 1 + var value = 20; // Field 2 + var extra = 30; // Field 3 + + // Each field can be represented in a single byte, with a single byte tag. + // Total message size: 6 bytes. + output.WriteLength(6); + output.WriteTag(1, WireFormat.WireType.Varint); + output.WriteInt32(key); + output.WriteTag(2, WireFormat.WireType.Varint); + output.WriteInt32(value); + output.WriteTag(3, WireFormat.WireType.Varint); + output.WriteInt32(extra); + output.Flush(); + + var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray()); + Assert.AreEqual(value, parsed.MapInt32Int32[key]); + } + + [Test] + public void MapFieldOrderIsIrrelevant() + { + var memoryStream = new MemoryStream(); + var output = new CodedOutputStream(memoryStream); + + output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited); + + var key = 10; + var value = 20; + + // Each field can be represented in a single byte, with a single byte tag. + // Total message size: 4 bytes. + output.WriteLength(4); + output.WriteTag(2, WireFormat.WireType.Varint); + output.WriteInt32(value); + output.WriteTag(1, WireFormat.WireType.Varint); + output.WriteInt32(key); + output.Flush(); + + var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray()); + Assert.AreEqual(value, parsed.MapInt32Int32[key]); + } + + [Test] + public void MapNonContiguousEntries() + { + var memoryStream = new MemoryStream(); + var output = new CodedOutputStream(memoryStream); + + // Message structure: + // Entry for MapInt32Int32 + // Entry for MapStringString + // Entry for MapInt32Int32 + + // First entry + var key1 = 10; + var value1 = 20; + output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited); + output.WriteLength(4); + output.WriteTag(1, WireFormat.WireType.Varint); + output.WriteInt32(key1); + output.WriteTag(2, WireFormat.WireType.Varint); + output.WriteInt32(value1); + + // Second entry + var key2 = "a"; + var value2 = "b"; + output.WriteTag(TestMap.MapStringStringFieldNumber, WireFormat.WireType.LengthDelimited); + output.WriteLength(6); // 3 bytes per entry: tag, size, character + output.WriteTag(1, WireFormat.WireType.LengthDelimited); + output.WriteString(key2); + output.WriteTag(2, WireFormat.WireType.LengthDelimited); + output.WriteString(value2); + + // Third entry + var key3 = 15; + var value3 = 25; + output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited); + output.WriteLength(4); + output.WriteTag(1, WireFormat.WireType.Varint); + output.WriteInt32(key3); + output.WriteTag(2, WireFormat.WireType.Varint); + output.WriteInt32(value3); + + output.Flush(); + var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray()); + var expected = new TestMap + { + MapInt32Int32 = { { key1, value1 }, { key3, value3 } }, + MapStringString = { { key2, value2 } } + }; + Assert.AreEqual(expected, parsed); + } + + [Test] + public void DuplicateKeys_LastEntryWins() + { + var memoryStream = new MemoryStream(); + var output = new CodedOutputStream(memoryStream); + + var key = 10; + var value1 = 20; + var value2 = 30; + + // First entry + output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited); + output.WriteLength(4); + output.WriteTag(1, WireFormat.WireType.Varint); + output.WriteInt32(key); + output.WriteTag(2, WireFormat.WireType.Varint); + output.WriteInt32(value1); + + // Second entry - same key, different value + output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited); + output.WriteLength(4); + output.WriteTag(1, WireFormat.WireType.Varint); + output.WriteInt32(key); + output.WriteTag(2, WireFormat.WireType.Varint); + output.WriteInt32(value2); + output.Flush(); + + var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray()); + Assert.AreEqual(value2, parsed.MapInt32Int32[key]); + } + + [Test] + public void CloneSingleNonMessageValues() + { + var original = new TestAllTypes + { + SingleBool = true, + SingleBytes = ByteString.CopyFrom(1, 2, 3, 4), + SingleDouble = 23.5, + SingleFixed32 = 23, + SingleFixed64 = 1234567890123, + SingleFloat = 12.25f, + SingleInt32 = 100, + SingleInt64 = 3210987654321, + SingleNestedEnum = TestAllTypes.Types.NestedEnum.Foo, + SingleSfixed32 = -123, + SingleSfixed64 = -12345678901234, + SingleSint32 = -456, + SingleSint64 = -12345678901235, + SingleString = "test", + SingleUint32 = uint.MaxValue, + SingleUint64 = ulong.MaxValue + }; + var clone = original.Clone(); + Assert.AreNotSame(original, clone); + Assert.AreEqual(original, clone); + // Just as a single example + clone.SingleInt32 = 150; + Assert.AreNotEqual(original, clone); + } + + [Test] + public void CloneRepeatedNonMessageValues() + { + var original = new TestAllTypes + { + RepeatedBool = { true, false }, + RepeatedBytes = { ByteString.CopyFrom(1, 2, 3, 4), ByteString.CopyFrom(5, 6) }, + RepeatedDouble = { -12.25, 23.5 }, + RepeatedFixed32 = { uint.MaxValue, 23 }, + RepeatedFixed64 = { ulong.MaxValue, 1234567890123 }, + RepeatedFloat = { 100f, 12.25f }, + RepeatedInt32 = { 100, 200 }, + RepeatedInt64 = { 3210987654321, long.MaxValue }, + RepeatedNestedEnum = { TestAllTypes.Types.NestedEnum.Foo, TestAllTypes.Types.NestedEnum.Neg }, + RepeatedSfixed32 = { -123, 123 }, + RepeatedSfixed64 = { -12345678901234, 12345678901234 }, + RepeatedSint32 = { -456, 100 }, + RepeatedSint64 = { -12345678901235, 123 }, + RepeatedString = { "foo", "bar" }, + RepeatedUint32 = { uint.MaxValue, uint.MinValue }, + RepeatedUint64 = { ulong.MaxValue, uint.MinValue } + }; + + var clone = original.Clone(); + Assert.AreNotSame(original, clone); + Assert.AreEqual(original, clone); + // Just as a single example + clone.RepeatedDouble.Add(25.5); + Assert.AreNotEqual(original, clone); + } + + [Test] + public void CloneSingleMessageField() + { + var original = new TestAllTypes + { + SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 20 } + }; + + var clone = original.Clone(); + Assert.AreNotSame(original, clone); + Assert.AreNotSame(original.SingleNestedMessage, clone.SingleNestedMessage); + Assert.AreEqual(original, clone); + + clone.SingleNestedMessage.Bb = 30; + Assert.AreNotEqual(original, clone); + } + + [Test] + public void CloneRepeatedMessageField() + { + var original = new TestAllTypes + { + RepeatedNestedMessage = { new TestAllTypes.Types.NestedMessage { Bb = 20 } } + }; + + var clone = original.Clone(); + Assert.AreNotSame(original, clone); + Assert.AreNotSame(original.RepeatedNestedMessage, clone.RepeatedNestedMessage); + Assert.AreNotSame(original.RepeatedNestedMessage[0], clone.RepeatedNestedMessage[0]); + Assert.AreEqual(original, clone); + + clone.RepeatedNestedMessage[0].Bb = 30; + Assert.AreNotEqual(original, clone); + } + + [Test] + public void CloneOneofField() + { + var original = new TestAllTypes + { + OneofNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 20 } + }; + + var clone = original.Clone(); + Assert.AreNotSame(original, clone); + Assert.AreEqual(original, clone); + + // We should have cloned the message + original.OneofNestedMessage.Bb = 30; + Assert.AreNotEqual(original, clone); + } + + [Test] + public void OneofProperties() + { + // Switch the oneof case between each of the different options, and check everything behaves + // as expected in each case. + var message = new TestAllTypes(); + Assert.AreEqual("", message.OneofString); + Assert.AreEqual(0, message.OneofUint32); + Assert.AreEqual(ByteString.Empty, message.OneofBytes); + Assert.IsNull(message.OneofNestedMessage); + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.None, message.OneofFieldCase); + + message.OneofString = "sample"; + Assert.AreEqual("sample", message.OneofString); + Assert.AreEqual(0, message.OneofUint32); + Assert.AreEqual(ByteString.Empty, message.OneofBytes); + Assert.IsNull(message.OneofNestedMessage); + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofString, message.OneofFieldCase); + + var bytes = ByteString.CopyFrom(1, 2, 3); + message.OneofBytes = bytes; + Assert.AreEqual("", message.OneofString); + Assert.AreEqual(0, message.OneofUint32); + Assert.AreEqual(bytes, message.OneofBytes); + Assert.IsNull(message.OneofNestedMessage); + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofBytes, message.OneofFieldCase); + + message.OneofUint32 = 20; + Assert.AreEqual("", message.OneofString); + Assert.AreEqual(20, message.OneofUint32); + Assert.AreEqual(ByteString.Empty, message.OneofBytes); + Assert.IsNull(message.OneofNestedMessage); + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofUint32, message.OneofFieldCase); + + var nestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 25 }; + message.OneofNestedMessage = nestedMessage; + Assert.AreEqual("", message.OneofString); + Assert.AreEqual(0, message.OneofUint32); + Assert.AreEqual(ByteString.Empty, message.OneofBytes); + Assert.AreEqual(nestedMessage, message.OneofNestedMessage); + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofNestedMessage, message.OneofFieldCase); + + message.ClearOneofField(); + Assert.AreEqual("", message.OneofString); + Assert.AreEqual(0, message.OneofUint32); + Assert.AreEqual(ByteString.Empty, message.OneofBytes); + Assert.IsNull(message.OneofNestedMessage); + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.None, message.OneofFieldCase); + } + + [Test] + public void Oneof_DefaultValuesNotEqual() + { + var message1 = new TestAllTypes { OneofString = "" }; + var message2 = new TestAllTypes { OneofUint32 = 0 }; + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofString, message1.OneofFieldCase); + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofUint32, message2.OneofFieldCase); + Assert.AreNotEqual(message1, message2); + } + + [Test] + public void OneofSerialization_NonDefaultValue() + { + var message = new TestAllTypes(); + message.OneofString = "this would take a bit of space"; + message.OneofUint32 = 10; + var bytes = message.ToByteArray(); + Assert.AreEqual(3, bytes.Length); // 2 bytes for the tag + 1 for the value - no string! + + var message2 = TestAllTypes.Parser.ParseFrom(bytes); + Assert.AreEqual(message, message2); + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofUint32, message2.OneofFieldCase); + } + + [Test] + public void OneofSerialization_DefaultValue() + { + var message = new TestAllTypes(); + message.OneofString = "this would take a bit of space"; + message.OneofUint32 = 0; // This is the default value for UInt32; normally wouldn't be serialized + var bytes = message.ToByteArray(); + Assert.AreEqual(3, bytes.Length); // 2 bytes for the tag + 1 for the value - it's still serialized + + var message2 = TestAllTypes.Parser.ParseFrom(bytes); + Assert.AreEqual(message, message2); + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofUint32, message2.OneofFieldCase); + } + + [Test] + public void IgnoreUnknownFields_RealDataStillRead() + { + var message = SampleMessages.CreateFullTestAllTypes(); + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + var unusedFieldNumber = 23456; + Assert.IsFalse(TestAllTypes.Descriptor.Fields.InDeclarationOrder().Select(x => x.FieldNumber).Contains(unusedFieldNumber)); + output.WriteTag(unusedFieldNumber, WireFormat.WireType.LengthDelimited); + output.WriteString("ignore me"); + message.WriteTo(output); + output.Flush(); + + stream.Position = 0; + var parsed = TestAllTypes.Parser.ParseFrom(stream); + Assert.AreEqual(message, parsed); + } + + [Test] + public void IgnoreUnknownFields_AllTypes() + { + // Simple way of ensuring we can skip all kinds of fields. + var data = SampleMessages.CreateFullTestAllTypes().ToByteArray(); + var empty = Empty.Parser.ParseFrom(data); + Assert.AreEqual(new Empty(), empty); + } + + // This was originally seen as a conformance test failure. + [Test] + public void TruncatedMessageFieldThrows() + { + // 130, 3 is the message tag + // 1 is the data length - but there's no data. + var data = new byte[] { 130, 3, 1 }; + Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseFrom(data)); + } + + /// <summary> + /// Demonstrates current behaviour with an extraneous end group tag - see issue 688 + /// for details; we may want to change this. + /// </summary> + [Test] + public void ExtraEndGroupThrows() + { + var message = SampleMessages.CreateFullTestAllTypes(); + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + + output.WriteTag(TestAllTypes.SingleFixed32FieldNumber, WireFormat.WireType.Fixed32); + output.WriteFixed32(123); + output.WriteTag(100, WireFormat.WireType.EndGroup); + + output.Flush(); + + stream.Position = 0; + Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseFrom(stream)); + } + + [Test] + public void CustomDiagnosticMessage_DirectToStringCall() + { + var message = new ForeignMessage { C = 31 }; + Assert.AreEqual("{ \"c\": 31, \"@cInHex\": \"1f\" }", message.ToString()); + Assert.AreEqual("{ \"c\": 31 }", JsonFormatter.Default.Format(message)); + } + + [Test] + public void CustomDiagnosticMessage_Nested() + { + var message = new TestAllTypes { SingleForeignMessage = new ForeignMessage { C = 16 } }; + Assert.AreEqual("{ \"singleForeignMessage\": { \"c\": 16, \"@cInHex\": \"10\" } }", message.ToString()); + Assert.AreEqual("{ \"singleForeignMessage\": { \"c\": 16 } }", JsonFormatter.Default.Format(message)); + } + + [Test] + public void CustomDiagnosticMessage_DirectToTextWriterCall() + { + var message = new ForeignMessage { C = 31 }; + var writer = new StringWriter(); + JsonFormatter.Default.Format(message, writer); + Assert.AreEqual("{ \"c\": 31 }", writer.ToString()); + } + } }
\ No newline at end of file diff --git a/third_party/protobuf/3.4.0/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/IssuesTest.cs b/third_party/protobuf/3.4.0/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/IssuesTest.cs index a38d6b08b5..ddb23aa685 100644 --- a/third_party/protobuf/3.4.0/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/IssuesTest.cs +++ b/third_party/protobuf/3.4.0/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/IssuesTest.cs @@ -1,82 +1,82 @@ -#region Copyright notice and license
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-#endregion
-
-using Google.Protobuf.Reflection;
-using UnitTest.Issues.TestProtos;
-using NUnit.Framework;
-
-
-namespace Google.Protobuf
-{
- /// <summary>
- /// Tests for issues which aren't easily compartmentalized into other unit tests.
- /// </summary>
- public class IssuesTest
- {
- // Issue 45
- [Test]
- public void FieldCalledItem()
- {
- ItemField message = new ItemField { Item = 3 };
- FieldDescriptor field = ItemField.Descriptor.FindFieldByName("item");
- Assert.NotNull(field);
- Assert.AreEqual(3, (int)field.Accessor.GetValue(message));
- }
-
- [Test]
- public void ReservedNames()
- {
- var message = new ReservedNames { Types_ = 10, Descriptor_ = 20 };
- // Underscores aren't reflected in the JSON.
- Assert.AreEqual("{ \"types\": 10, \"descriptor\": 20 }", message.ToString());
- }
-
- [Test]
- public void JsonNameParseTest()
- {
- var settings = new JsonParser.Settings(10, TypeRegistry.FromFiles(UnittestIssuesReflection.Descriptor));
- var parser = new JsonParser(settings);
-
- // It is safe to use either original field name or explicitly specified json_name
- Assert.AreEqual(new TestJsonName { Name = "test", Description = "test2", Guid = "test3" },
- parser.Parse<TestJsonName>("{ \"name\": \"test\", \"desc\": \"test2\", \"guid\": \"test3\" }"));
- }
-
- [Test]
- public void JsonNameFormatTest()
- {
- var message = new TestJsonName { Name = "test", Description = "test2", Guid = "test3" };
- Assert.AreEqual("{ \"name\": \"test\", \"desc\": \"test2\", \"exid\": \"test3\" }",
- JsonFormatter.Default.Format(message));
- }
- }
-}
+#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + +using Google.Protobuf.Reflection; +using UnitTest.Issues.TestProtos; +using NUnit.Framework; + + +namespace Google.Protobuf +{ + /// <summary> + /// Tests for issues which aren't easily compartmentalized into other unit tests. + /// </summary> + public class IssuesTest + { + // Issue 45 + [Test] + public void FieldCalledItem() + { + ItemField message = new ItemField { Item = 3 }; + FieldDescriptor field = ItemField.Descriptor.FindFieldByName("item"); + Assert.NotNull(field); + Assert.AreEqual(3, (int)field.Accessor.GetValue(message)); + } + + [Test] + public void ReservedNames() + { + var message = new ReservedNames { Types_ = 10, Descriptor_ = 20 }; + // Underscores aren't reflected in the JSON. + Assert.AreEqual("{ \"types\": 10, \"descriptor\": 20 }", message.ToString()); + } + + [Test] + public void JsonNameParseTest() + { + var settings = new JsonParser.Settings(10, TypeRegistry.FromFiles(UnittestIssuesReflection.Descriptor)); + var parser = new JsonParser(settings); + + // It is safe to use either original field name or explicitly specified json_name + Assert.AreEqual(new TestJsonName { Name = "test", Description = "test2", Guid = "test3" }, + parser.Parse<TestJsonName>("{ \"name\": \"test\", \"desc\": \"test2\", \"guid\": \"test3\" }")); + } + + [Test] + public void JsonNameFormatTest() + { + var message = new TestJsonName { Name = "test", Description = "test2", Guid = "test3" }; + Assert.AreEqual("{ \"name\": \"test\", \"desc\": \"test2\", \"exid\": \"test3\" }", + JsonFormatter.Default.Format(message)); + } + } +} diff --git a/third_party/protobuf/3.4.0/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/TestCornerCases.cs b/third_party/protobuf/3.4.0/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/TestCornerCases.cs index 248f5fa913..fd75b19f42 100644 --- a/third_party/protobuf/3.4.0/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/TestCornerCases.cs +++ b/third_party/protobuf/3.4.0/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/TestCornerCases.cs @@ -1,62 +1,62 @@ -#region Copyright notice and license
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-#endregion
-
-using UnitTest.Issues.TestProtos;
-using NUnit.Framework;
-
-namespace Google.Protobuf
-{
- public class TestCornerCases
- {
- [Test]
- public void TestRoundTripNegativeEnums()
- {
- NegativeEnumMessage msg = new NegativeEnumMessage
- {
- Value = NegativeEnum.MinusOne,
- Values = { NegativeEnum.Zero, NegativeEnum.MinusOne, NegativeEnum.FiveBelow },
- PackedValues = { NegativeEnum.Zero, NegativeEnum.MinusOne, NegativeEnum.FiveBelow }
- };
-
- Assert.AreEqual(58, msg.CalculateSize());
-
- byte[] bytes = new byte[58];
- CodedOutputStream output = new CodedOutputStream(bytes);
-
- msg.WriteTo(output);
- Assert.AreEqual(0, output.SpaceLeft);
-
- NegativeEnumMessage copy = NegativeEnumMessage.Parser.ParseFrom(bytes);
- Assert.AreEqual(msg, copy);
- }
- }
-}
+#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + +using UnitTest.Issues.TestProtos; +using NUnit.Framework; + +namespace Google.Protobuf +{ + public class TestCornerCases + { + [Test] + public void TestRoundTripNegativeEnums() + { + NegativeEnumMessage msg = new NegativeEnumMessage + { + Value = NegativeEnum.MinusOne, + Values = { NegativeEnum.Zero, NegativeEnum.MinusOne, NegativeEnum.FiveBelow }, + PackedValues = { NegativeEnum.Zero, NegativeEnum.MinusOne, NegativeEnum.FiveBelow } + }; + + Assert.AreEqual(58, msg.CalculateSize()); + + byte[] bytes = new byte[58]; + CodedOutputStream output = new CodedOutputStream(bytes); + + msg.WriteTo(output); + Assert.AreEqual(0, output.SpaceLeft); + + NegativeEnumMessage copy = NegativeEnumMessage.Parser.ParseFrom(bytes); + Assert.AreEqual(msg, copy); + } + } +} |