CreateInstance() public static method

Creates a new CodedInputStream reading data from the given stream.
public static CreateInstance ( Stream input ) : CodedInputStream
input Stream
return CodedInputStream
Beispiel #1
0
        public void ReadMaliciouslyLargeBlob()
        {
            MemoryStream      ms     = new MemoryStream();
            CodedOutputStream output = CodedOutputStream.CreateInstance(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 = CodedInputStream.CreateInstance(ms);
            uint             testtag;
            string           ignore;

            Assert.IsTrue(input.ReadTag(out testtag, out ignore));
            Assert.AreEqual(tag, testtag);

            ByteString bytes = null;

            // TODO(jonskeet): Should this be ArgumentNullException instead?
            Assert.Throws <InvalidProtocolBufferException>(() => input.ReadBytes(ref bytes));
        }
        public void TestNegativeEnumArray()
        {
            int arraySize = 1 + 1 + (11 * 5);
            int msgSize   = arraySize;

            byte[]            bytes  = new byte[msgSize];
            CodedOutputStream output = CodedOutputStream.CreateInstance(bytes);

            output.WriteEnumArray(8, "", new int[] { 0, -1, -2, -3, -4, -5 });

            Assert.AreEqual(0, output.SpaceLeft);

            CodedInputStream input = CodedInputStream.CreateInstance(bytes);
            uint             tag;
            string           name;

            Assert.IsTrue(input.ReadTag(out tag, out name));

            List <int> values = new List <int>();

            input.ReadInt32Array(tag, name, values);

            Assert.AreEqual(6, values.Count);
            for (int i = 0; i > -6; i--)
            {
                Assert.AreEqual(i, values[Math.Abs(i)]);
            }
        }
Beispiel #3
0
        public void TestSlowPathAvoidance()
        {
            using (var ms = new MemoryStream())
            {
                CodedOutputStream output = CodedOutputStream.CreateInstance(ms);
                output.WriteField(FieldType.Bytes, 1, "bytes", ByteString.CopyFrom(new byte[100]));
                output.WriteField(FieldType.Bytes, 2, "bytes", ByteString.CopyFrom(new byte[100]));
                output.Flush();

                ms.Position = 0;
                CodedInputStream input = CodedInputStream.CreateInstance(ms, new byte[ms.Length / 2]);

                uint       tag;
                string     ignore;
                ByteString value;

                Assert.IsTrue(input.ReadTag(out tag, out ignore));
                Assert.AreEqual(1, WireFormat.GetTagFieldNumber(tag));
                value = ByteString.Empty;
                Assert.IsTrue(input.ReadBytes(ref value) && value.Length == 100);

                Assert.IsTrue(input.ReadTag(out tag, out ignore));
                Assert.AreEqual(2, WireFormat.GetTagFieldNumber(tag));
                value = ByteString.Empty;
                Assert.IsTrue(input.ReadBytes(ref value) && value.Length == 100);
            }
        }
Beispiel #4
0
        public void ReadInvalidUtf8()
        {
            MemoryStream      ms     = new MemoryStream();
            CodedOutputStream output = CodedOutputStream.CreateInstance(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 = CodedInputStream.CreateInstance(ms);

            uint   testtag;
            string ignored;

            Assert.IsTrue(input.ReadTag(out testtag, out ignored));
            Assert.AreEqual(tag, testtag);
            string text = null;

            input.ReadString(ref text);
            Assert.AreEqual('\ufffd', text[0]);
        }
Beispiel #5
0
        /// <summary>
        /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() and
        /// </summary>
        private static void AssertReadVarint(byte[] data, ulong value)
        {
            CodedInputStream input = CodedInputStream.CreateInstance(data);

            Assert.AreEqual((uint)value, input.ReadRawVarint32());

            input = CodedInputStream.CreateInstance(data);
            Assert.AreEqual(value, input.ReadRawVarint64());
            Assert.IsTrue(input.IsAtEnd);

            // Try different block sizes.
            for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2)
            {
                input = CodedInputStream.CreateInstance(new SmallBlockInputStream(data, bufferSize));
                Assert.AreEqual((uint)value, input.ReadRawVarint32());

                input = CodedInputStream.CreateInstance(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);
        }
Beispiel #6
0
        public void SkipWholeMessage()
        {
            TestAllTypes message = TestUtil.GetAllSet();

            byte[] rawBytes = message.ToByteArray();

            // Create two parallel inputs.  Parse one as unknown fields while using
            // skipField() to skip each field on the other.  Expect the same tags.
            CodedInputStream input1 = CodedInputStream.CreateInstance(rawBytes);
            CodedInputStream input2 = CodedInputStream.CreateInstance(rawBytes);

            UnknownFieldSet.Builder unknownFields = UnknownFieldSet.CreateBuilder();

            uint   tag;
            string name;

            while (input1.ReadTag(out tag, out name))
            {
                uint tag2;
                Assert.IsTrue(input2.ReadTag(out tag2, out name));
                Assert.AreEqual(tag, tag2);

                unknownFields.MergeFieldFrom(tag, input1);
                input2.SkipField();
            }
        }
        /// <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 = CodedInputStream.CreateInstance(data);

            try {
                input.ReadRawVarint32();
                Assert.Fail("Should have thrown an exception.");
            } catch (InvalidProtocolBufferException e) {
                Assert.AreEqual(expected.Message, e.Message);
            }

            input = CodedInputStream.CreateInstance(data);
            try {
                input.ReadRawVarint64();
                Assert.Fail("Should have thrown an exception.");
            } catch (InvalidProtocolBufferException e) {
                Assert.AreEqual(expected.Message, e.Message);
            }

            // Make sure we get the same error when reading directly from a Stream.
            try {
                CodedInputStream.ReadRawVarint32(new MemoryStream(data));
                Assert.Fail("Should have thrown an exception.");
            } catch (InvalidProtocolBufferException e) {
                Assert.AreEqual(expected.Message, e.Message);
            }
        }
Beispiel #8
0
        public void TestBufferRefillIssue()
        {
            var ms = new MemoryStream();

            BucketOfBytes.CreateBuilder()
            .SetValue(ByteString.CopyFrom(new byte[3000]))
            .Build().WriteDelimitedTo(ms);
            BucketOfBytesEx.CreateBuilder()
            .SetValue(ByteString.CopyFrom(new byte[1000]))
            .SetValue2(ByteString.CopyFrom(new byte[1100]))
            .Build().WriteDelimitedTo(ms);
            BucketOfBytes.CreateBuilder()
            .SetValue(ByteString.CopyFrom(new byte[100]))
            .Build().WriteDelimitedTo(ms);

            ms.Position = 0;
            var input   = CodedInputStream.CreateInstance(ms);
            var builder = BucketOfBytes.CreateBuilder();

            input.ReadMessage(builder, ExtensionRegistry.Empty);
            Assert.AreEqual(3005L, input.Position);
            Assert.AreEqual(3000, builder.Value.Length);
            input.ReadMessage(builder, ExtensionRegistry.Empty);
            Assert.AreEqual(5114, input.Position);
            Assert.AreEqual(1000, builder.Value.Length);
            input.ReadMessage(builder, ExtensionRegistry.Empty);
            Assert.AreEqual(5217L, input.Position);
            Assert.AreEqual(input.Position, ms.Length);
            Assert.AreEqual(100, builder.Value.Length);
        }
Beispiel #9
0
        public void TestNegativeEnumArray()
        {
            int arraySize = 1 + 1 + (11 * 5);
            int msgSize   = arraySize;

            byte[]            bytes  = new byte[msgSize];
            CodedOutputStream output = CodedOutputStream.CreateInstance(bytes);

            output.WriteInt32Array(8, "", new int[] { 0, -1, -2, -3, -4, -5 });

            Assert.AreEqual(0, output.SpaceLeft);

            CodedInputStream input = CodedInputStream.CreateInstance(bytes);
            uint             tag;
            string           name;

            Assert.IsTrue(input.ReadTag(out tag, out name));

            List <TestNegEnum>   values = new List <TestNegEnum>();
            ICollection <object> unk;

            input.ReadEnumArray(tag, name, values, out unk);

            Assert.AreEqual(2, values.Count);
            Assert.AreEqual(TestNegEnum.None, values[0]);
            Assert.AreEqual(TestNegEnum.Value, values[1]);

            Assert.IsNotNull(unk);
            Assert.AreEqual(4, unk.Count);
        }
        public IEnumerator <TMessage> GetEnumerator()
        {
            using (Stream stream = streamProvider())
            {
                CodedInputStream input = CodedInputStream.CreateInstance(stream);
                input.SetSizeLimit(sizeLimit);
                uint   tag;
                string name;
                while (input.ReadTag(out tag, out name))
                {
                    if ((tag == 0 && name == "item") || (tag == ExpectedTag))
                    {
                        IBuilder builder = defaultMessageInstance.WeakCreateBuilderForType();
                        input.ReadMessage(builder, extensionRegistry);
                        yield return((TMessage)builder.WeakBuild());
                    }
                    else
                    {
                        throw InvalidProtocolBufferException.InvalidMessageStreamTag();
                    }

                    input.ResetSizeCounter();
                }
            }
        }
Beispiel #11
0
        public void ResetSizeCounter()
        {
            CodedInputStream input = CodedInputStream.CreateInstance(
                new SmallBlockInputStream(new byte[256], 8));

            input.SetSizeLimit(16);
            input.ReadRawBytes(16);

            try
            {
                input.ReadRawByte();
                Assert.Fail("Should have thrown an exception!");
            }
            catch (InvalidProtocolBufferException)
            {
                // Success.
            }

            input.ResetSizeCounter();
            input.ReadRawByte(); // No exception thrown.

            try
            {
                input.ReadRawBytes(16); // Hits limit again.
                Assert.Fail("Should have thrown an exception!");
            }
            catch (InvalidProtocolBufferException)
            {
                // Success.
            }
        }
Beispiel #12
0
        public void ReadMaliciouslyLargeBlob()
        {
            MemoryStream      ms     = new MemoryStream();
            CodedOutputStream output = CodedOutputStream.CreateInstance(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 = CodedInputStream.CreateInstance(ms);
            uint             testtag;
            string           ignore;

            Assert.IsTrue(input.ReadTag(out testtag, out ignore));
            Assert.AreEqual(tag, testtag);

            try
            {
                ByteString bytes = null;
                input.ReadBytes(ref bytes);
                Assert.Fail("Should have thrown an exception!");
            }
            catch (InvalidProtocolBufferException)
            {
                // success.
            }
        }
Beispiel #13
0
        public TBuilder MergeFrom(Stream input, ExtensionRegistry extensionRegistry)
        {
            CodedInputStream codedInput = CodedInputStream.CreateInstance(input);

            MergeFrom(codedInput, extensionRegistry);
            codedInput.CheckLastTagWas(0);
            return(ThisBuilder);
        }
Beispiel #14
0
            /// <summary>
            /// Parses <paramref name="data"/> as an UnknownFieldSet and merge it
            /// with the set being built. This is just a small wrapper around
            /// MergeFrom(ICodedInputStream).
            /// </summary>
            public Builder MergeFrom(byte[] data)
            {
                CodedInputStream input = CodedInputStream.CreateInstance(data);

                MergeFrom(input);
                input.CheckLastTagWas(0);
                return(this);
            }
        public TBuilder MergeFrom(byte[] data, ExtensionRegistry extensionRegistry)
        {
            CodedInputStream codedInputStream = CodedInputStream.CreateInstance(data);

            this.MergeFrom(codedInputStream, extensionRegistry);
            codedInputStream.CheckLastTagWas(0u);
            return(this.ThisBuilder);
        }
Beispiel #16
0
            /// <summary>
            /// Parses <paramref name="input"/> as an UnknownFieldSet and merge it
            /// with the set being built. This is just a small wrapper around
            /// MergeFrom(ICodedInputStream).
            /// </summary>
            public Builder MergeFrom(Stream input)
            {
                CodedInputStream codedInput = CodedInputStream.CreateInstance(input);

                MergeFrom(codedInput);
                codedInput.CheckLastTagWas(0);
                return(this);
            }
        public TBuilder MergeFrom(Stream input)
        {
            CodedInputStream codedInputStream = CodedInputStream.CreateInstance(input);

            this.MergeFrom(codedInputStream);
            codedInputStream.CheckLastTagWas(0u);
            return(this.ThisBuilder);
        }
Beispiel #18
0
        public TBuilder MergeFrom(byte[] data, ExtensionRegistry extensionRegistry)
        {
            CodedInputStream input = CodedInputStream.CreateInstance(data);

            MergeFrom(input, extensionRegistry);
            input.CheckLastTagWas(0);
            return(ThisBuilder);
        }
            byte[] IWireTransfer.Execute(string method, byte[] message)
            {
                //now when we recieve a wire transmission to invoke a method by name with a byte[] or stream payload
                //we just simply call the sub:
                IMessageLite response = _stub.CallMethod(method, CodedInputStream.CreateInstance(message),
                                                         ExtensionRegistry.Empty);

                //now we return the expected response message:
                return(response.ToByteArray());
            }
Beispiel #20
0
        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(TestUtil.GetAllSet().ToByteString().ToByteArray());
            CodedInputStream input = CodedInputStream.CreateInstance(ms);

            input.SetSizeLimit(16);

            Assert.Throws <InvalidProtocolBufferException>(() => TestAllTypes.ParseFrom(input));
        }
Beispiel #21
0
        public void SkipRawBytesBug()
        {
            byte[]           rawBytes = new byte[] { 1, 2 };
            CodedInputStream input    = CodedInputStream.CreateInstance(rawBytes);

            int limit = input.PushLimit(1);

            input.SkipRawBytes(1);
            input.PopLimit(limit);
            Assert.AreEqual(2, input.ReadRawByte());
        }
        public void TestBuilderLiteMergeFromCodedInputStream()
        {
            TestAllTypesLite copy, msg = TestAllTypesLite.CreateBuilder()
                                         .SetOptionalString("Should be merged.").Build();

            copy = TestAllTypesLite.DefaultInstance;
            Assert.AreNotEqual(msg.ToByteArray(), copy.ToByteArray());

            copy = copy.ToBuilder().MergeFrom(CodedInputStream.CreateInstance(new MemoryStream(msg.ToByteArray()))).Build();
            Assert.AreEqual(msg.ToByteArray(), copy.ToByteArray());
        }
Beispiel #23
0
        public void TestNegativeEnum()
        {
            byte[] bytes = new byte[10] {
                0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01
            };
            CodedInputStream input = CodedInputStream.CreateInstance(bytes);
            object           unk;
            TestNegEnum      val = TestNegEnum.None;

            Assert.IsTrue(input.ReadEnum(ref val, out unk));
            Assert.IsTrue(input.IsAtEnd);
            Assert.AreEqual(TestNegEnum.Value, val);
        }
        /// <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 = CodedInputStream.CreateInstance(data);

            Assert.AreEqual(value, input.ReadRawLittleEndian64());

            // Try different block sizes.
            for (int blockSize = 1; blockSize <= 16; blockSize *= 2)
            {
                input = CodedInputStream.CreateInstance(
                    new SmallBlockInputStream(data, blockSize));
                Assert.AreEqual(value, input.ReadRawLittleEndian64());
            }
        }
 public IEnumerator <TMessage> GetEnumerator()
 {
     using (Stream stream = streamProvider()) {
         CodedInputStream input = CodedInputStream.CreateInstance(stream);
         uint             tag;
         while ((tag = input.ReadTag()) != 0)
         {
             if (tag != ExpectedTag)
             {
                 throw InvalidProtocolBufferException.InvalidMessageStreamTag();
             }
             yield return(messageReader(input, extensionRegistry));
         }
     }
 }
        public void TestMergeFromCodedInputStream()
        {
            TestAllTypesLite copy, msg = TestAllTypesLite.CreateBuilder()
                                         .SetOptionalUint32(uint.MaxValue).Build();

            copy = TestAllTypesLite.DefaultInstance;
            Assert.AreNotEqual(msg.ToByteArray(), copy.ToByteArray());

            using (MemoryStream ms = new MemoryStream(msg.ToByteArray())) {
                CodedInputStream ci = CodedInputStream.CreateInstance(ms);
                copy = copy.ToBuilder().MergeFrom(ci).Build();
            }

            Assert.AreEqual(msg.ToByteArray(), copy.ToByteArray());
        }
Beispiel #27
0
        public void ResetSizeCounter()
        {
            CodedInputStream input = CodedInputStream.CreateInstance(
                new SmallBlockInputStream(new byte[256], 8));

            input.SetSizeLimit(16);
            input.ReadRawBytes(16);

            Assert.Throws <InvalidProtocolBufferException>(() => input.ReadRawByte());

            input.ResetSizeCounter();
            input.ReadRawByte(); // No exception thrown.

            Assert.Throws <InvalidProtocolBufferException>(() => input.ReadRawBytes(16));
        }
Beispiel #28
0
        /// <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 = CodedInputStream.CreateInstance(data);
            var exception          = Assert.Throws <InvalidProtocolBufferException>(() => input.ReadRawVarint32());

            Assert.AreEqual(expected.Message, exception.Message);

            input     = CodedInputStream.CreateInstance(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);
        }
        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(TestUtil.GetAllSet().ToByteString().ToByteArray());
            CodedInputStream input = CodedInputStream.CreateInstance(ms);

            input.SetSizeLimit(16);

            try {
                TestAllTypes.ParseFrom(input);
                Assert.Fail("Should have thrown an exception!");
            } catch (InvalidProtocolBufferException) {
                // success.
            }
        }
        /// <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 void AssertReadVarintFailure(InvalidProtocolBufferException expected, byte[] data)
        {
            CodedInputStream input = CodedInputStream.CreateInstance(data);

            try {
                input.ReadRawVarint32();
                Assert.Fail("Should have thrown an exception.");
            } catch (InvalidProtocolBufferException e) {
                Assert.AreEqual(expected.Message, e.Message);
            }

            input = CodedInputStream.CreateInstance(data);
            try {
                input.ReadRawVarint64();
                Assert.Fail("Should have thrown an exception.");
            } catch (InvalidProtocolBufferException e) {
                Assert.AreEqual(expected.Message, e.Message);
            }
        }