Readings and decodes protocol message fields.

This class is generally used by generated code to read appropriate primitives from the stream. It effectively encapsulates the lowest levels of protocol buffer format.

Repeated fields and map fields are not handled by this class; use RepeatedField{T} and MapField{TKey, TValue} to serialize such fields.

コード例 #1
0
        /// <summary>
        /// Pick up 16 bytes IV from the front of cipher text, use it together with <paramref name="key"> to AES parse the protobuf stream.
        /// </summary>
        /// <typeparam name="P">Your protobuf type here.</typeparam>
        public static P ProtoFromStream <P>(Stream stream, byte[] key)
            where P : IMessage <P>, new()
        {
            //iOS used to complain about Protobuf doing JIT without this, not sure about now.
            Environment.SetEnvironmentVariable("MONO_REFLECTION_SERIALIZER", "yes");

            //This scheme we paste initialization vector as a header of the save file, so we just yank it back for use...
            byte[] ivRead = new byte[16];
            stream.Read(ivRead, 0, 16);

            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();

            aes.Key = key;
            aes.IV  = ivRead;

            //Debug.Log($"Using {string.Join(",", des.Key.Select(x => x))} {string.Join(",", des.IV.Select(x => x))}");

            P loadedData = new P();

            using (var cryptoStream = new CryptoStream(stream, aes.CreateDecryptor(), CryptoStreamMode.Read))
            {
                using (Google.Protobuf.CodedInputStream cis = new Google.Protobuf.CodedInputStream(cryptoStream))
                {
                    loadedData = new MessageParser <P>(() => new P()).ParseFrom(cis);
                    return(loadedData);
                }
            }
        }
コード例 #2
0
        /// <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);
        }
コード例 #3
0
ファイル: MessageExtensions.cs プロジェクト: 2php/protobuf
 /// <summary>
 /// Merges data from the given byte array into an existing message.
 /// </summary>
 /// <param name="message">The message to merge the data into.</param>
 /// <param name="data">The data to merge, which must be protobuf-encoded binary data.</param>
 public static void MergeFrom(this IMessage message, byte[] data)
 {
     ProtoPreconditions.CheckNotNull(message, "message");
     ProtoPreconditions.CheckNotNull(data, "data");
     CodedInputStream input = new CodedInputStream(data);
     message.MergeFrom(input);
     input.CheckReadEndOfStreamTag();
 }
コード例 #4
0
ファイル: MessageExtensions.cs プロジェクト: 2php/protobuf
 /// <summary>
 /// Merges data from the given stream into an existing message.
 /// </summary>
 /// <param name="message">The message to merge the data into.</param>
 /// <param name="input">Stream containing the data to merge, which must be protobuf-encoded binary data.</param>
 public static void MergeFrom(this IMessage message, Stream input)
 {
     ProtoPreconditions.CheckNotNull(message, "message");
     ProtoPreconditions.CheckNotNull(input, "input");
     CodedInputStream codedInput = new CodedInputStream(input);
     message.MergeFrom(codedInput);
     codedInput.CheckReadEndOfStreamTag();
 }
コード例 #5
0
 /// <summary>
 /// Merges data from the given stream into an existing message.
 /// </summary>
 /// <param name="message">The message to merge the data into.</param>
 /// <param name="input">Stream containing the data to merge, which must be protobuf-encoded binary data.</param>
 public static void MergeFrom(this IMessage message, Stream input)
 {
     Preconditions.CheckNotNull(message, "message");
     Preconditions.CheckNotNull(input, "input");
     CodedInputStream codedInput = new CodedInputStream(input);
     message.MergeFrom(codedInput);
     codedInput.CheckLastTagWas(0);
 }
コード例 #6
0
ファイル: SchemaTest.cs プロジェクト: paperclip/krpc
 public void ByteStringToValueType ()
 {
     // From Google's protobuf documentation, varint encoding example:
     // 300 = 1010 1100 0000 0010 = 0xAC 0x02
     byte[] bytes = { 0xAC, 0x02 };
     var codedStream = new CodedInputStream (bytes);
     uint value = codedStream.ReadUInt32 ();
     Assert.AreEqual (300, value);
 }
コード例 #7
0
        public void MergeFrom(pb.CodedInputStream input)
        {
    #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
            input.ReadRawMessage(this);
    #else
            uint tag;
            while ((tag = input.ReadTag()) != 0)
            {
                switch (tag)
                {
                default:
                    _unknownFields = pb.UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
                    break;

                case 10: {
                    ClientId = input.ReadString();
                    break;
                }

                case 18: {
                    MessageId = input.ReadString();
                    break;
                }

                case 24: {
                    Type = (MessageType)input.ReadEnum();
                    break;
                }

                case 34: {
                    if (time_ == null)
                    {
                        Time = new global.Google.Protobuf.WellKnownTypes.Timestamp();
                    }
                    input.ReadMessage(Time);
                    break;
                }

                case 40: {
                    Status = (MessageStatus)input.ReadEnum();
                    break;
                }

                case 50: {
                    Payload = input.ReadBytes();
                    break;
                }

                case 56: {
                    Response = (ResponseType)input.ReadEnum();
                    break;
                }
                }
            }
    #endif
        }
コード例 #8
0
ファイル: MainWindow.xaml.cs プロジェクト: shuetam/Proto
        private void MergeAllFrom(List <Type> protoClasses, string pathToProtos1, string pathToProtos2)
        {
            if (pathToProtos1 == "" || pathToProtos2 == "")
            {
                MessageBox.Show("Please select data protos files first");
            }


            this.protoInstances1 = new List <object>();
            this.protoInstances2 = new List <object>();

            foreach (Type protoClass in protoClasses)
            {
                ConstructorInfo[] constructors = protoClass.GetConstructors();

                if (constructors.Count <ConstructorInfo>() > 0)
                {
                    try
                    {
                        var protoInstance1 = constructors[0].Invoke(null);
                        var protoInstance2 = constructors[0].Invoke(null);

                        IEnumerable <MethodInfo> protoMethods1 = (IEnumerable <MethodInfo>)protoInstance1.GetType().GetMethods();
                        IEnumerable <MethodInfo> protoMethods2 = (IEnumerable <MethodInfo>)protoInstance1.GetType().GetMethods();

                        var mergeFromList1 = protoMethods1.Where(m => m.Name == "MergeFrom").ToList();
                        var mergeFromList2 = protoMethods1.Where(m => m.Name == "MergeFrom").ToList();

                        var mergeFrom1 = mergeFromList1[1];
                        var mergeFrom2 = mergeFromList2[1];

                        byte[] protosBytes1 = File.ReadAllBytes(pathToProtos1);
                        var    googleCode1  = new Google.Protobuf.CodedInputStream(protosBytes1);

                        byte[] protosBytes2 = File.ReadAllBytes(pathToProtos2);
                        var    googleCode2  = new Google.Protobuf.CodedInputStream(protosBytes2);

                        mergeFrom1.Invoke(protoInstance1, new object[] { googleCode1 });
                        mergeFrom2.Invoke(protoInstance2, new object[] { googleCode2 });

                        protoInstances1.Add(protoInstance1);
                        protoInstances2.Add(protoInstance2);
                    }

                    catch (System.Reflection.TargetInvocationException i)
                    {
                    }
                }
            }
        }
コード例 #9
0
ファイル: Encoder.cs プロジェクト: artwhaley/krpc
 /// <summary>
 /// Decode a value of the given type.
 /// Should not be called directly. This interface is used by service client stubs.
 /// </summary>
 public static object Decode(ByteString value, Type type, Connection client)
 {
     var stream = new CodedInputStream (value.ToByteArray ());
     if (type == typeof(double))
         return stream.ReadDouble ();
     else if (type == typeof(float))
         return stream.ReadFloat ();
     else if (type == typeof(int))
         return stream.ReadInt32 ();
     else if (type == typeof(long))
         return stream.ReadInt64 ();
     else if (type == typeof(uint))
         return stream.ReadUInt32 ();
     else if (type == typeof(ulong))
         return stream.ReadUInt64 ();
     else if (type == typeof(bool))
         return stream.ReadBool ();
     else if (type == typeof(string))
         return stream.ReadString ();
     else if (type == typeof(byte[]))
         return stream.ReadBytes ().ToByteArray ();
     else if (type.IsEnum)
         return stream.ReadInt32 ();
     else if (typeof(RemoteObject).IsAssignableFrom (type)) {
         if (client == null)
             throw new ArgumentException ("Client not passed when decoding remote object");
         var id = stream.ReadUInt64 ();
         if (id == 0)
             return null;
         return (RemoteObject)Activator.CreateInstance (type, client, id);
     } else if (typeof(IMessage).IsAssignableFrom (type)) {
         IMessage message = (IMessage)Activator.CreateInstance (type);
         message.MergeFrom (stream);
         return message;
     } else if (type.IsGenericType && type.GetGenericTypeDefinition () == typeof(IList<>))
         return DecodeList (value, type, client);
     else if (type.IsGenericType && type.GetGenericTypeDefinition () == typeof(IDictionary<,>))
         return DecodeDictionary (value, type, client);
     else if (type.IsGenericType && type.GetGenericTypeDefinition () == typeof(ISet<>))
         return DecodeSet (value, type, client);
     else if (type.IsGenericType &&
              (type.GetGenericTypeDefinition () == typeof(Tuple<>) ||
              type.GetGenericTypeDefinition () == typeof(Tuple<,>) ||
              type.GetGenericTypeDefinition () == typeof(Tuple<,,>) ||
              type.GetGenericTypeDefinition () == typeof(Tuple<,,,>) ||
              type.GetGenericTypeDefinition () == typeof(Tuple<,,,,>) ||
              type.GetGenericTypeDefinition () == typeof(Tuple<,,,,,>)))
         return DecodeTuple (value, type, client); // TODO: ugly handing of tuple types
     throw new ArgumentException (type + " is not a serializable type");
 }
コード例 #10
0
ファイル: MainWindow.xaml.cs プロジェクト: shuetam/Proto
        private bool MergeFrom(Type protoClass, string pathToProtos1, string pathToProtos2)
        {
            if (pathToProtos1 == "" || pathToProtos2 == "")
            {
                return(false);
            }

            ConstructorInfo[] constructors = protoClass.GetConstructors();

            if (constructors.Count <ConstructorInfo>() > 0)
            {
                try
                {
                    var protoInstance1 = constructors[0].Invoke(null);
                    var protoInstance2 = constructors[0].Invoke(null);

                    IEnumerable <MethodInfo> protoMethods1 = (IEnumerable <MethodInfo>)protoInstance1.GetType().GetMethods();
                    IEnumerable <MethodInfo> protoMethods2 = (IEnumerable <MethodInfo>)protoInstance1.GetType().GetMethods();

                    var mergeFromList1 = protoMethods1.Where(m => m.Name == "MergeFrom").ToList();
                    var mergeFromList2 = protoMethods1.Where(m => m.Name == "MergeFrom").ToList();

                    var mergeFrom1 = mergeFromList1[1];
                    var mergeFrom2 = mergeFromList2[1];

                    byte[] protosBytes1 = File.ReadAllBytes(pathToProtos1);
                    var    googleCode1  = new Google.Protobuf.CodedInputStream(protosBytes1);

                    byte[] protosBytes2 = File.ReadAllBytes(pathToProtos2);
                    var    googleCode2  = new Google.Protobuf.CodedInputStream(protosBytes2);

                    mergeFrom1.Invoke(protoInstance1, new object[] { googleCode1 });
                    mergeFrom2.Invoke(protoInstance2, new object[] { googleCode2 });

                    this.proto1 = protoInstance1;
                    this.proto2 = protoInstance2;
                    return(true);
                }

                catch (System.Reflection.TargetInvocationException i)
                {
                    return(false);
                }
            }

            return(false);
        }
コード例 #11
0
ファイル: RPCStream.cs プロジェクト: paperclip/krpc
 protected override int Read (ref Request request, byte[] data, int offset, int length)
 {
     try {
         var codedStream = new CodedInputStream (data, offset, length);
         // Get the protobuf message size
         int size = (int)codedStream.ReadUInt32 ();
         int totalSize = (int)codedStream.Position + size;
         // Check if enough data is available, if not then delay the decoding
         if (length < totalSize)
             return 0;
         // Decode the request
         request = Schema.KRPC.Request.Parser.ParseFrom (codedStream).ToMessage ();
         return totalSize;
     } catch (InvalidProtocolBufferException e) {
         throw new MalformedRequestException (e.Message);
     }
 }
コード例 #12
0
    private static PlayerData PlayerDataFromStream(Stream stream)
    {
        Environment.SetEnvironmentVariable("MONO_REFLECTION_SERIALIZER", "yes");         //So that iOS don't complain about protobuf's JITing

        //Try to get the IV..
        byte[] ivRead = new byte[8];
        stream.Read(ivRead, 0, 8);

        DESCryptoServiceProvider des = new DESCryptoServiceProvider();

        des.Key = Key;
        des.IV  = ivRead;

        PlayerData loadedData = new PlayerData();

        using (var cryptoStream = new CryptoStream(stream, des.CreateDecryptor(), CryptoStreamMode.Read))
        {
            using (Google.Protobuf.CodedInputStream cis = new Google.Protobuf.CodedInputStream(cryptoStream))
            {
                loadedData = PlayerData.Parser.ParseFrom(cis);
                return(loadedData);
            }
        }
    }
コード例 #13
0
ファイル: FieldCodec.cs プロジェクト: drolean/Arctium-RE
 internal uint <ForUInt32> b__7_0(CodedInputStream input)
 {
     return(input.ReadUInt32());
 }
コード例 #14
0
        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);
                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);
            }
        }
コード例 #15
0
 public override void ReadValue(CodedInputStream stream)
 {
 }
コード例 #16
0
ファイル: FieldCodec.cs プロジェクト: drolean/Arctium-RE
 internal float <ForFloat> b__13_0(CodedInputStream input)
 {
     return(input.ReadFloat());
 }
コード例 #17
0
ファイル: Encoder.cs プロジェクト: paperclip/krpc
 static object DecodeSet (CodedInputStream stream, Type type, IConnection client)
 {
     var encodedSet = KRPC.Schema.KRPC.Set.Parser.ParseFrom (stream);
     var set = (IEnumerable)(typeof(HashSet<>)
         .MakeGenericType (type.GetGenericArguments ().Single ())
         .GetConstructor (Type.EmptyTypes)
         .Invoke (null));
     MethodInfo methodInfo = type.GetMethod ("Add");
     foreach (var item in encodedSet.Items) {
         var decodedItem = Decode (item, type.GetGenericArguments ().Single (), client);
         methodInfo.Invoke (set, new [] { decodedItem });
     }
     return set;
 }
コード例 #18
0
ファイル: FieldCodec.cs プロジェクト: drolean/Arctium-RE
 internal int <ForSInt32> b__4_0(CodedInputStream input)
 {
     return(input.ReadSInt32());
 }
コード例 #19
0
ファイル: Encoder.cs プロジェクト: paperclip/krpc
 static object DecodeMessage (CodedInputStream stream, Type type)
 {
     if (type == typeof(Request)) {
         var message = new Schema.KRPC.Request ();
         message.MergeFrom (stream);
         return message.ToMessage ();
     }
     throw new ArgumentException ("Cannot decode protocol buffer messages of type " + type);
 }
コード例 #20
0
ファイル: FieldCodec.cs プロジェクト: drolean/Arctium-RE
 internal uint <ForFixed32> b__5_0(CodedInputStream input)
 {
     return(input.ReadFixed32());
 }
コード例 #21
0
ファイル: FieldCodec.cs プロジェクト: drolean/Arctium-RE
 internal long <ForSFixed64> b__11_0(CodedInputStream input)
 {
     return(input.ReadSFixed64());
 }
コード例 #22
0
ファイル: Adapt_IMessage.cs プロジェクト: stylehuan/ET
 public void MergeFrom(CodedInputStream input)
 {
     Invoke(0, input);
 }
コード例 #23
0
        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);
            }
        }
コード例 #24
0
 internal bool ContainsInputField(CodedInputStream stream, Type target, out Extension extension)
 {
     return(extensions.TryGetValue(new ObjectIntPair <Type>(target, WireFormat.GetTagFieldNumber(stream.LastTag)), out extension));
 }
コード例 #25
0
ファイル: FieldCodec.cs プロジェクト: drolean/Arctium-RE
            internal static T Read <T>(CodedInputStream input, FieldCodec <T> codec)
            {
                int byteLimit = input.ReadLength();
                T   result;

                while (true)
                {
IL_FA:
                    uint arg_C8_0 = 1476935752u;
                    while (true)
                    {
                        uint num;
                        switch ((num = (arg_C8_0 ^ 2018772964u)) % 9u)
                        {
                        case 0u:
                            input.SkipLastField();
                            arg_C8_0 = 1768391466u;
                            continue;

                        case 1u:
                        {
                            uint num2;
                            arg_C8_0 = (((num2 = input.ReadTag()) == 0u) ? 789788880u : 1000495088u);
                            continue;
                        }

                        case 3u:
                            arg_C8_0 = (num * 422428889u ^ 15908708u);
                            continue;

                        case 4u:
                            result   = codec.Read(input);
                            arg_C8_0 = (num * 2015424451u ^ 1456283564u);
                            continue;

                        case 5u:
                        {
                            uint num2;
                            arg_C8_0 = ((num2 == codec.Tag) ? 627669222u : 345821031u);
                            continue;
                        }

                        case 6u:
                        {
                            input.CheckReadEndOfStreamTag();
                            int oldLimit;
                            input.PopLimit(oldLimit);
                            arg_C8_0 = (num * 1368242210u ^ 1133084529u);
                            continue;
                        }

                        case 7u:
                        {
                            int oldLimit = input.PushLimit(byteLimit);
                            result   = codec.DefaultValue;
                            arg_C8_0 = (num * 2466023856u ^ 3651674u);
                            continue;
                        }

                        case 8u:
                            goto IL_FA;
                        }
                        return(result);
                    }
                }
                return(result);
            }
コード例 #26
0
ファイル: FieldCodec.cs プロジェクト: drolean/Arctium-RE
 internal double <ForDouble> b__14_0(CodedInputStream input)
 {
     return(input.ReadDouble());
 }
コード例 #27
0
        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);

                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);
            }
        }
コード例 #28
0
ファイル: FieldCodec.cs プロジェクト: drolean/Arctium-RE
 internal bool <ForBool> b__2_0(CodedInputStream input)
 {
     return(input.ReadBool());
 }
コード例 #29
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 = 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);
        }
コード例 #30
0
ファイル: FieldCodec.cs プロジェクト: drolean/Arctium-RE
 internal ulong <ForFixed64> b__10_0(CodedInputStream input)
 {
     return(input.ReadFixed64());
 }
コード例 #31
0
        public void ResetSizeCounter()
        {
            CodedInputStream input = new CodedInputStream(
                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));
        }
コード例 #32
0
ファイル: Encoder.cs プロジェクト: paperclip/krpc
 static object DecodeList (CodedInputStream stream, Type type, IConnection client)
 {
     var encodedList = KRPC.Schema.KRPC.List.Parser.ParseFrom (stream);
     var list = (IList)(typeof(List<>)
         .MakeGenericType (type.GetGenericArguments ().Single ())
         .GetConstructor (Type.EmptyTypes)
         .Invoke (null));
     foreach (var item in encodedList.Items)
         list.Add (Decode (item, type.GetGenericArguments ().Single (), client));
     return list;
 }
コード例 #33
0
 public void MergeFrom(pb.CodedInputStream input)
 {
     throw new System.NotImplementedException();
 }
コード例 #34
0
ファイル: FieldCodec.cs プロジェクト: drolean/Arctium-RE
 internal ulong <ForUInt64> b__12_0(CodedInputStream input)
 {
     return(input.ReadUInt64());
 }
コード例 #35
0
ファイル: FieldCodec.cs プロジェクト: drolean/Arctium-RE
 internal ByteString <ForBytes> b__1_0(CodedInputStream input)
 {
     return(input.ReadBytes());
 }
コード例 #36
0
ファイル: FieldCodec.cs プロジェクト: drolean/Arctium-RE
 internal long <ForSInt64> b__9_0(CodedInputStream input)
 {
     return(input.ReadSInt64());
 }
コード例 #37
0
ファイル: FieldCodec.cs プロジェクト: drolean/Arctium-RE
 internal string <ForString> b__0_0(CodedInputStream input)
 {
     return(input.ReadString());
 }
コード例 #38
0
ファイル: CodedInputStreamTest.cs プロジェクト: 2php/protobuf
 public void Dispose_DisposesUnderlyingStream()
 {
     var memoryStream = new MemoryStream();
     Assert.IsTrue(memoryStream.CanRead);
     using (var cis = new CodedInputStream(memoryStream))
     {
     }
     Assert.IsFalse(memoryStream.CanRead); // Disposed
 }
コード例 #39
0
ファイル: CodedInputStreamTest.cs プロジェクト: 2php/protobuf
 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
 }
コード例 #40
0
        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]);
        }
コード例 #41
0
ファイル: Encoder.cs プロジェクト: paperclip/krpc
 static object DecodeDictionary (CodedInputStream stream, Type type, IConnection client)
 {
     var encodedDictionary = KRPC.Schema.KRPC.Dictionary.Parser.ParseFrom (stream);
     var dictionary = (IDictionary)(typeof(Dictionary<,>)
         .MakeGenericType (type.GetGenericArguments () [0], type.GetGenericArguments () [1])
         .GetConstructor (Type.EmptyTypes)
         .Invoke (null));
     foreach (var entry in encodedDictionary.Entries) {
         var key = Decode (entry.Key, type.GetGenericArguments () [0], client);
         var value = Decode (entry.Value, type.GetGenericArguments () [1], client);
         dictionary [key] = value;
     }
     return dictionary;
 }
コード例 #42
0
        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);
        }
コード例 #43
0
ファイル: Encoder.cs プロジェクト: paperclip/krpc
 static object DecodeTuple (CodedInputStream stream, Type type, IConnection client)
 {
     var encodedTuple = KRPC.Schema.KRPC.Tuple.Parser.ParseFrom (stream);
     var valueTypes = type.GetGenericArguments ().ToArray ();
     var genericType = Type.GetType ("System.Tuple`" + valueTypes.Length.ToString ());
     var values = new object[valueTypes.Length];
     for (int i = 0; i < valueTypes.Length; i++) {
         var item = encodedTuple.Items [i];
         values [i] = Decode (item, valueTypes [i], client);
     }
     var tuple = genericType
         .MakeGenericType (valueTypes)
         .GetConstructor (valueTypes)
         .Invoke (values);
     return tuple;
 }
コード例 #44
0
        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());
        }
コード例 #45
0
ファイル: StreamManager.cs プロジェクト: artwhaley/krpc
            internal void Main()
            {
                client = new TcpClient ();
                client.Connect (address, port);
                stream = client.GetStream ();
                stream.Write (Encoder.streamHelloMessage, 0, Encoder.streamHelloMessage.Length);
                stream.Write (clientIdentifier, 0, clientIdentifier.Length);
                var recvOkMessage = new byte [Encoder.okMessage.Length];
                stream.Read (recvOkMessage, 0, Encoder.okMessage.Length);
                if (recvOkMessage.Equals (Encoder.okMessage))
                    throw new Exception ("Invalid hello message received from stream server. " +
                    "Got " + Encoder.ToHexString (recvOkMessage));
                this.codedStream = new CodedInputStream (stream);

                try {
                    while (true) {
                        var message = new StreamMessage ();
                        codedStream.ReadMessage (message);
                        foreach (var response in message.Responses)
                            manager.Update (response.Id, response.Response);
                    }
                } catch (IOException) {
                    // Exit when the connection closes
                }
            }
コード例 #46
0
 public void Tag0Throws()
 {
     var input = new CodedInputStream(new byte[] { 0 });
     Assert.Throws<InvalidProtocolBufferException>(() => input.ReadTag());
 }
コード例 #47
0
ファイル: ExtensionSet.cs プロジェクト: romanrogozin/Plugin
 /// <summary>
 /// Tries to merge a field from the coded input, returning true if the field was merged.
 /// If the set is null or the field was not otherwise merged, this returns false.
 /// </summary>
 public static bool TryMergeFieldFrom <TTarget>(ref ExtensionSet <TTarget> set, CodedInputStream stream) where TTarget : IExtendableMessage <TTarget>
 {
     ParseContext.Initialize(stream, out ParseContext ctx);
     try
     {
         return(TryMergeFieldFrom <TTarget>(ref set, ref ctx));
     }
     finally
     {
         ctx.CopyStateTo(stream);
     }
 }
コード例 #48
0
ファイル: FieldCodec.cs プロジェクト: drolean/Arctium-RE
 internal int <ForSFixed32> b__6_0(CodedInputStream input)
 {
     return(input.ReadSFixed32());
 }
コード例 #49
0
        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());
        }
コード例 #50
0
ファイル: ExtensionValue.cs プロジェクト: NikkittaP/osg_pack
 public void MergeFrom(CodedInputStream input)
 {
     hasValue = true;
     codec.ValueMerger(input, ref field);
 }
コード例 #51
0
        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);
        }
コード例 #52
0
ファイル: ExtensionValue.cs プロジェクト: NikkittaP/osg_pack
 public void MergeFrom(CodedInputStream input)
 {
     field.AddEntriesFrom(input, codec);
 }
コード例 #53
0
        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);
        }
コード例 #54
0
        public void ReadTag_ZeroFieldRejected(byte tag)
        {
            CodedInputStream cis = new CodedInputStream(new byte[] { tag });

            Assert.Throws <InvalidProtocolBufferException>(() => cis.ReadTag());
        }
コード例 #55
0
 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);
 }
コード例 #56
0
        public void Dispose_FromByteArray()
        {
            var stream = new CodedInputStream(new byte[10]);

            stream.Dispose();
        }
コード例 #57
0
        /// <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);
            }
        }
コード例 #58
0
 public static void Initialize(CodedInputStream codedInputStream, out SegmentedBufferHelper instance)
 {
     instance.totalLength = codedInputStream.InternalInputStream == null ? (int?)codedInputStream.InternalBuffer.Length : null;
     instance.readOnlySequenceEnumerator = default;
     instance.codedInputStream           = codedInputStream;
 }
コード例 #59
0
        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);
        }
コード例 #60
0
        public void Tag0Throws()
        {
            var input = new CodedInputStream(new byte[] { 0 });

            Assert.Throws <InvalidProtocolBufferException>(() => input.ReadTag());
        }