Readings and decodes protocol message fields.
This class contains two kinds of methods: methods that read specific protocol message constructs and field types (e.g. ReadTag and ReadInt32) and methods that read low-level values (e.g. ReadRawVarint32 and ReadRawBytes). If you are reading encoded protocol messages, you should use the former methods, but if you are reading some other format of your own design, use the latter. The names of the former methods are taken from the protocol buffer type names, not .NET types. (Hence ReadFloat instead of ReadSingle, and ReadBool instead of ReadBoolean.) TODO(jonskeet): Consider whether recursion and size limits shouldn't be readonly, set at construction time.
Beispiel #1
0
        public static void Identify(IClient client, CodedInputStream stream)
        {
            var header = new Header(stream);
            var payload = new byte[header.PayloadLength];
            payload = stream.ReadRawBytes((int)header.PayloadLength);

            var packet = new Packet(header, payload);
            var service = Service.GetByID(header.ServiceID);

            if (service == null)
            {
                Logger.Error("No service exists with id: 0x{0}", header.ServiceID.ToString("X2"));
                return;
            }

            var method = service.DescriptorForType.Methods[(int)header.MethodID - 1];
            var proto = service.GetRequestPrototype(method);
            var builder = proto.WeakCreateBuilderForType();

            try
            {
                var message = builder.WeakMergeFrom(CodedInputStream.CreateInstance(packet.Payload.ToArray())).WeakBuild();

                ((IServerService) service).Client = client;
                service.CallMethod(method, null, message, (msg => SendResponse(client, header.RequestID, msg)));
            }
            catch (NotImplementedException)
            {
                Logger.Debug(string.Format("Unimplemented service method: {0} {1}", service.GetType().Name, method.Name));
            }
            catch(Exception e)
            {
                Logger.DebugException(e,string.Empty);
            }
        }
Beispiel #2
0
        public static void Identify(CodedInputStream stream)
        {
            try
            {
                var header = new BNetHeader(stream);
                var payload = new byte[header.PayloadLength];

                payload = stream.ReadRawBytes((int) header.PayloadLength);

                var packet = new BNetPacket(header, payload);
                if (header.ServiceID == 0xfe) return;

                var service = Service.GetByID(header.ServiceID);
                if (service == null) return;

                var method =
                    service.DescriptorForType.Methods.Single(
                        m => (uint) m.Options[bnet.protocol.Rpc.MethodId.Descriptor] == header.MethodID);

                var proto = service.GetRequestPrototype(method);
                var builder = proto.WeakCreateBuilderForType();

                var message =
                    builder.WeakMergeFrom(CodedInputStream.CreateInstance(packet.Payload.ToArray())).WeakBuild();
                service.CallMethod(method, null, message, (msg => { }));
            }
            catch (UninitializedMessageException e)
            {
                Console.WriteLine("Failed to parse message: {0}", e.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Beispiel #3
0
        public PacketIn(MooNetClient client, CodedInputStream stream)
        {
            this.Client = client;
            this.Stream = stream;

            this.Read();
        }
Beispiel #4
0
        public static void Identify(IConnection connection, CodedInputStream stream)
        {
            var client = (MooNetClient) connection.Client;
            var packet = new PacketIn(client, stream);

            if (packet.Header.ServiceId == ServiceReply)
                ProcessReply(client, packet);
            else
                ProcessMessage(client, stream, packet);           
        }
Beispiel #5
0
        public Header(CodedInputStream stream)
        {
            var serviceId = stream.ReadRawByte();
            var methodId = stream.ReadRawVarint32();
            var requestId = stream.ReadRawByte() | (stream.ReadRawByte() << 8);
            if (serviceId != 0xfe) this.Unknown = stream.ReadRawVarint64();
            var payloadLength = stream.ReadRawVarint32();

            this.SetData(serviceId, methodId, requestId, payloadLength);
        }
Beispiel #6
0
        public PacketIn(CodedInputStream stream)
        {
            this._stream = stream;

            this.ServiceId = stream.ReadRawByte();
            this.MethodId = stream.ReadRawVarint32();
            this.RequestId = stream.ReadRawByte() | (stream.ReadRawByte() << 8);

            this.ObjectId = 0UL;
            if (this.ServiceId != 0xfe) this.ObjectId = stream.ReadRawVarint64();
        }
Beispiel #7
0
        public BNetHeader(CodedInputStream stream)
        {
            var serviceId = stream.ReadRawByte();
            var methodId = stream.ReadRawVarint32();
            var requestId = stream.ReadRawByte() | (stream.ReadRawByte() << 8);

            var objectId = 0UL;
            if (serviceId != 0xfe) objectId = stream.ReadRawVarint64();
            var payloadLength = stream.ReadRawVarint32();

            this.SetData(serviceId, methodId, requestId, payloadLength, objectId);
        }
Beispiel #8
0
        public ClientPacket(CodedInputStream stream)
        {
            m_stream = stream;

            // Read header
            m_service = m_stream.ReadRawByte();
            m_method = m_stream.ReadInt32();
            m_requestId = m_stream.ReadInt16();
            m_listenerId = 0;

            Console.WriteLine("IN: service {0}, method {1:X}, requestId {2}, listenerId {3}", m_service, m_method, m_requestId, m_listenerId);

            if (m_service != 0xFE)
                m_listenerId = m_stream.ReadRawVarint64();
        }
Beispiel #9
0
        private void Handle(CodedInputStream stream)
        {
            if (first)
            {
                first = false;
                new HardcodedGsPackets(this.stream);
            }

            var size = stream.ReadInt32Reversed(); // includes size of size

            var payLoad = stream.ReadRawBytes(size - 4);
            payLoad.PrintHex();

            var opcode = payLoad[0]; // assume that opcode is 1 byte for now

            Console.WriteLine("GS: Opcode {0:X2}, payload size {1}", opcode, size - 4);
        }
Beispiel #10
0
        public static int Identify(IClient client, CodedInputStream stream)
        {
            var header = new Header(stream);
            var payload = new byte[header.PayloadLength];
            payload = stream.ReadRawBytes((int)header.PayloadLength);
            
            var packet = new Packet(header, payload);
            var service = ServiceManager.GetServerServiceByID(header.ServiceID);

            if(service!=null)
            {
                service.CallMethod(header.MethodID, client, packet);
                return packet.Length;
            }

            Console.WriteLine("\n===========[Unknown Crap]===========\nHeader\t: {0}Payload\t: {1}", header.Data.Dump(), payload.Dump());
            return 0;
        }
Beispiel #11
0
        public static void Identify(IConnection connection, CodedInputStream stream)
        {
            var header = new BNetHeader(stream);
            var payload = new byte[header.PayloadLength];
            payload = stream.ReadRawBytes((int)header.PayloadLength);

            var packet = new BNetPacket(header, payload);
            var service = Service.GetByID(header.ServiceID);

            if (service == null)
            {
                Logger.Error("No service exists with id: 0x{0}", header.ServiceID.ToString("X2"));
                return;
            }

            //var method = service.DescriptorForType.Methods[(int)header.MethodID - 1];
            //Logger.Warn("METHODID: {0}, from header: {1}", (uint)method.Options[bnet.protocol.Rpc.MethodId.Descriptor], header.MethodID);
            var method = service.DescriptorForType.Methods.Single(m => (uint)m.Options[bnet.protocol.Rpc.MethodId.Descriptor] == header.MethodID);
            var proto = service.GetRequestPrototype(method);
            var builder = proto.WeakCreateBuilderForType();

            try
            {
                var message = builder.WeakMergeFrom(CodedInputStream.CreateInstance(packet.Payload.ToArray())).WeakBuild();
                lock (service) // lock the service so that it's in-context client does not get changed..
                {
                    //Logger.Debug("service-call data:{0}", message.ToString());
                    ((IServerService) service).Client = (IBNetClient)connection.Client;
                    service.CallMethod(method, null, message, (msg => SendResponse(connection, header.RequestID, msg)));
                }
            }
            catch (NotImplementedException)
            {
                Logger.Debug("Unimplemented service method: {0} {1}", service.GetType().Name, method.Name);
            }
            catch (UninitializedMessageException e)
            {
                Logger.Debug("Failed to parse message: {0}", e.Message);
            }
            catch (Exception e)
            {
                Logger.DebugException(e, string.Empty);
            }
        }
Beispiel #12
0
        private void Handle(CodedInputStream stream)
        {
            var packet = new ClientPacket(stream);

            if (packet.Service == Program.PrevService)
            {
                //packet.Method should be 0, if there is no errors
                Callback callback = callbacks.Dequeue();
                if (callback.RequestId != packet.RequestId)
                    throw new InvalidOperationException("Callback does not match!");
                callback.Action(packet.ReadMessage(callback.Builder));
                return;
            }

            IService service = importedServices[packet.Service];

            MethodDescriptor method = service.DescriptorForType.Methods.Single(m => GetMethodId(m) == packet.Method);

            Action<IMessage> done =
                response =>
                {
                    ServerPacket data = new ServerPacket(Program.PrevService, (int)ErrorCode, packet.RequestId, 0).WriteMessage(response);
                    Send(data);
                    if (ErrorCode != AuthError.None)
                    {
                        DisconnectNotification dcNotify = DisconnectNotification.CreateBuilder().SetErrorCode((uint)ErrorCode).Build();
                        ConnectionService.CreateStub(this).ForceDisconnect(null, dcNotify, r => { });
                    }
                };

            IMessage requestProto = service.GetRequestPrototype(method);

            IMessage message = packet.ReadMessage(requestProto.WeakToBuilder());

            // Logging
            Console.WriteLine(requestProto.GetType());
            Console.WriteLine("Text View:");
            Console.WriteLine(message.ToString());

            service.CallMethod(method, null, message, done);
        }
Beispiel #13
0
        public MooNetCallNode(PacketIn packet, CodedInputStream stream)
        {
            var service = Service.GetByID(packet.Header.ServiceId);
            var method = service.DescriptorForType.Methods.Single(m => MooNetRouter.GetMethodId(m) == packet.Header.MethodId);
            var proto = service.GetRequestPrototype(method);
            reply = service.GetResponsePrototype(method);
            var builder = proto.WeakCreateBuilderForType();

            try
            {
                message = builder.WeakMergeFrom(CodedInputStream.CreateInstance(packet.GetPayload(stream))).WeakBuild();
                Text = message.DescriptorForType.Name;
            }
            catch (Exception e)
            {
                message = builder.WeakBuildPartial();
                Text = "Error parsing message {0}";
            }


        }
Beispiel #14
0
        private static void ProcessMessage(MooNetClient client, CodedInputStream stream, PacketIn packet)
        {
            var service = Service.GetByID(packet.Header.ServiceId);

            if (service == null)
            {
                Logger.Error("No service exists with id: 0x{0}", packet.Header.ServiceId.ToString("X2"));
                return;
            }

            var method = service.DescriptorForType.Methods.Single(m => GetMethodId(m) == packet.Header.MethodId);
            var proto = service.GetRequestPrototype(method);
            var builder = proto.WeakCreateBuilderForType();
            var message = builder.WeakMergeFrom(CodedInputStream.CreateInstance(packet.GetPayload(stream))).WeakBuild(); //var message = packet.ReadMessage(proto.WeakToBuilder()); // this method doesn't seem to work with 7728. /raist.
            Logger.LogIncoming(message, packet.Header);

            try
            {
                lock (service) // lock the service so that its in-context client does not get changed..
                {
                    ((IServerService)service).Client = client;
                    ((IServerService)service).LastCallHeader = packet.Header;
                    service.CallMethod(method, null, message, (msg => SendRPCResponse(client.Connection, packet.Header.Token, msg)));
                }
            }
            catch (NotImplementedException)
            {
                Logger.Warn("Unimplemented service method: {0}.{1}", service.GetType().Name, method.Name);
            }
            catch (UninitializedMessageException e)
            {
                Logger.Debug("Failed to parse message: {0}", e.Message);
            }
            catch (Exception e)
            {
                Logger.DebugException(e, string.Empty);
            }
        }
Beispiel #15
0
 public byte[] GetPayload(CodedInputStream stream)
 {
     var data = Client.IncomingMooNetStream.GetPacketData((int)this.Header.Size);
     return data;
 }
 IBuilderLite IBuilderLite.WeakMergeFrom(CodedInputStream input, ExtensionRegistry registry) {
   return MergeFrom(input);
 }
 IBuilderLite IBuilderLite.WeakMergeFrom(CodedInputStream input) {
   return MergeFrom(input);
 }
    static int ParseFrom(IntPtr L)
    {
        try
        {
            int count = LuaDLL.lua_gettop(L);

            if (count == 1 && TypeChecker.CheckTypes <Google.ProtocolBuffers.ByteString>(L, 1))
            {
                Google.ProtocolBuffers.ByteString arg0 = (Google.ProtocolBuffers.ByteString)ToLua.ToObject(L, 1);
                MyLib.CGPlayerCmd o = MyLib.CGPlayerCmd.ParseFrom(arg0);
                ToLua.PushSealed(L, o);
                return(1);
            }
            else if (count == 1 && TypeChecker.CheckTypes <byte[]>(L, 1))
            {
                byte[]            arg0 = ToLua.CheckByteBuffer(L, 1);
                MyLib.CGPlayerCmd o    = MyLib.CGPlayerCmd.ParseFrom(arg0);
                ToLua.PushSealed(L, o);
                return(1);
            }
            else if (count == 1 && TypeChecker.CheckTypes <System.IO.Stream>(L, 1))
            {
                System.IO.Stream  arg0 = (System.IO.Stream)ToLua.ToObject(L, 1);
                MyLib.CGPlayerCmd o    = MyLib.CGPlayerCmd.ParseFrom(arg0);
                ToLua.PushSealed(L, o);
                return(1);
            }
            else if (count == 1 && TypeChecker.CheckTypes <Google.ProtocolBuffers.CodedInputStream>(L, 1))
            {
                Google.ProtocolBuffers.CodedInputStream arg0 = (Google.ProtocolBuffers.CodedInputStream)ToLua.ToObject(L, 1);
                MyLib.CGPlayerCmd o = MyLib.CGPlayerCmd.ParseFrom(arg0);
                ToLua.PushSealed(L, o);
                return(1);
            }
            else if (count == 2 && TypeChecker.CheckTypes <Google.ProtocolBuffers.ByteString, Google.ProtocolBuffers.ExtensionRegistry>(L, 1))
            {
                Google.ProtocolBuffers.ByteString        arg0 = (Google.ProtocolBuffers.ByteString)ToLua.ToObject(L, 1);
                Google.ProtocolBuffers.ExtensionRegistry arg1 = (Google.ProtocolBuffers.ExtensionRegistry)ToLua.ToObject(L, 2);
                MyLib.CGPlayerCmd o = MyLib.CGPlayerCmd.ParseFrom(arg0, arg1);
                ToLua.PushSealed(L, o);
                return(1);
            }
            else if (count == 2 && TypeChecker.CheckTypes <byte[], Google.ProtocolBuffers.ExtensionRegistry>(L, 1))
            {
                byte[] arg0 = ToLua.CheckByteBuffer(L, 1);
                Google.ProtocolBuffers.ExtensionRegistry arg1 = (Google.ProtocolBuffers.ExtensionRegistry)ToLua.ToObject(L, 2);
                MyLib.CGPlayerCmd o = MyLib.CGPlayerCmd.ParseFrom(arg0, arg1);
                ToLua.PushSealed(L, o);
                return(1);
            }
            else if (count == 2 && TypeChecker.CheckTypes <System.IO.Stream, Google.ProtocolBuffers.ExtensionRegistry>(L, 1))
            {
                System.IO.Stream arg0 = (System.IO.Stream)ToLua.ToObject(L, 1);
                Google.ProtocolBuffers.ExtensionRegistry arg1 = (Google.ProtocolBuffers.ExtensionRegistry)ToLua.ToObject(L, 2);
                MyLib.CGPlayerCmd o = MyLib.CGPlayerCmd.ParseFrom(arg0, arg1);
                ToLua.PushSealed(L, o);
                return(1);
            }
            else if (count == 2 && TypeChecker.CheckTypes <Google.ProtocolBuffers.CodedInputStream, Google.ProtocolBuffers.ExtensionRegistry>(L, 1))
            {
                Google.ProtocolBuffers.CodedInputStream  arg0 = (Google.ProtocolBuffers.CodedInputStream)ToLua.ToObject(L, 1);
                Google.ProtocolBuffers.ExtensionRegistry arg1 = (Google.ProtocolBuffers.ExtensionRegistry)ToLua.ToObject(L, 2);
                MyLib.CGPlayerCmd o = MyLib.CGPlayerCmd.ParseFrom(arg0, arg1);
                ToLua.PushSealed(L, o);
                return(1);
            }
            else
            {
                return(LuaDLL.luaL_throw(L, "invalid arguments to method: MyLib.CGPlayerCmd.ParseFrom"));
            }
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e));
        }
    }
Beispiel #19
0
 /// <summary>
 /// Parses an UnknownFieldSet from the given input.
 /// </summary>
 public static UnknownFieldSet ParseFrom(CodedInputStream input)
 {
     return(CreateBuilder().MergeFrom(input).Build());
 }
        private bool connect()
        {
            try
            {
                client = new TcpClient();
                client.Connect(host, port);

                clientStream = client.GetStream();
                codedStream = CodedInputStream.CreateInstance(clientStream);

                Trace.WriteLine("Connected to AnntoPen server. ");
            }
            catch (SocketException)
            {
                Trace.WriteLine("Cannot connect to AnntoPen server. ");
                return false;
            }

            clientThread = new Thread(clientThreadWorker);
            clientThread.Start();
            return true;
        }
 internal void MergeFrom(CodedInputStream input, ExtensionRegistry extensionRegistry, IBuilder builder)
 {
     while (true) {
       uint tag = input.ReadTag();
       if (tag == 0) {
     break;
       }
       if (!MergeFieldFrom(input, extensionRegistry, builder, tag)) {
     // end group tag
     break;
       }
     }
 }
 /// <summary>
 /// Parse an entire message from <paramref name="input"/> and merge
 /// its fields into this set.
 /// </summary>
 public Builder MergeFrom(CodedInputStream input)
 {
     while (true) {
       uint tag = input.ReadTag();
       if (tag == 0 || !MergeFieldFrom(tag, input)) {
     break;
       }
     }
     return this;
 }
 /// <summary>
 /// Parses an UnknownFieldSet from the given input.
 /// </summary>
 public static UnknownFieldSet ParseFrom(CodedInputStream input)
 {
     return CreateBuilder().MergeFrom(input).Build();
 }
        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 = CodedOutputStream.CreateInstance(ms, 20);
                // Field 11: numeric value: 500
                cout.WriteTag(11, WireFormat.WireType.Varint);
                Assert.AreEqual(1, cout.Position);
                cout.WriteInt32NoTag(500);
                Assert.AreEqual(3, cout.Position);
                //Field 12: length delimited 120 bytes
                cout.WriteTag(12, WireFormat.WireType.LengthDelimited);
                Assert.AreEqual(4, cout.Position);
                cout.WriteBytesNoTag(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.WriteSFixed32NoTag(501);
                Assert.AreEqual(120, cout.Position);
                cout.Flush();
            }

            byte[] bytes = new byte[130];
            {
                CodedOutputStream cout = CodedOutputStream.CreateInstance(bytes);
                // Field 1: numeric value: 500
                cout.WriteTag(1, WireFormat.WireType.Varint);
                Assert.AreEqual(1, cout.Position);
                cout.WriteInt32NoTag(500);
                Assert.AreEqual(3, cout.Position);
                //Field 2: length delimited 120 bytes
                cout.WriteTag(2, WireFormat.WireType.LengthDelimited);
                Assert.AreEqual(4, cout.Position);
                cout.WriteBytesNoTag(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.WriteSFixed32NoTag(501);
                Assert.AreEqual(130, cout.Position);
                cout.Flush();
            }
            //Now test Input stream:
            {
                CodedInputStream cin = CodedInputStream.CreateInstance(new MemoryStream(bytes), new byte[50]);
                uint             tag;
                int    intValue = 0;
                string ignore;
                Assert.AreEqual(0, cin.Position);
                // Field 1:
                Assert.IsTrue(cin.ReadTag(out tag, out ignore) && tag >> 3 == 1);
                Assert.AreEqual(1, cin.Position);
                Assert.IsTrue(cin.ReadInt32(ref intValue) && intValue == 500);
                Assert.AreEqual(3, cin.Position);
                //Field 2:
                Assert.IsTrue(cin.ReadTag(out tag, out ignore) && tag >> 3 == 2);
                Assert.AreEqual(4, cin.Position);
                uint childlen = cin.ReadRawVarint32();
                Assert.AreEqual(120u, 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
                    Assert.IsTrue(cin.ReadTag(out tag, out ignore) && tag >> 3 == 11);
                    Assert.AreEqual(6, cin.Position);
                    Assert.IsTrue(cin.ReadInt32(ref intValue) && intValue == 500);
                    Assert.AreEqual(8, cin.Position);
                    //Field 12: length delimited 120 bytes
                    Assert.IsTrue(cin.ReadTag(out tag, out ignore) && tag >> 3 == 12);
                    Assert.AreEqual(9, cin.Position);
                    ByteString bstr = null;
                    Assert.IsTrue(cin.ReadBytes(ref bstr) && bstr.Length == 110 && bstr.ToByteArray()[109] == 109);
                    Assert.AreEqual(120, cin.Position);
                    // Field 13: fixed numeric value: 501
                    Assert.IsTrue(cin.ReadTag(out tag, out ignore) && tag >> 3 == 13);
                    // ROK - Previously broken here, this returned 126 failing to account for bufferSizeAfterLimit
                    Assert.AreEqual(121, cin.Position);
                    Assert.IsTrue(cin.ReadSFixed32(ref intValue) && intValue == 501);
                    Assert.AreEqual(125, cin.Position);
                    Assert.IsTrue(cin.IsAtEnd);
                }
                cin.PopLimit(oldlimit);
                Assert.AreEqual(125, cin.Position);
                // Field 3: fixed numeric value: 501
                Assert.IsTrue(cin.ReadTag(out tag, out ignore) && tag >> 3 == 3);
                Assert.AreEqual(126, cin.Position);
                Assert.IsTrue(cin.ReadSFixed32(ref intValue) && intValue == 501);
                Assert.AreEqual(130, cin.Position);
                Assert.IsTrue(cin.IsAtEnd);
            }
        }
Beispiel #25
0
            /// <summary>
            /// Called by MergeFieldFrom to parse a MessageSet extension.
            /// </summary>
            private void MergeMessageSetExtensionFromCodedStream(CodedInputStream input,
                                                                 ExtensionRegistry extensionRegistry, IBuilder builder)
            {
                MessageDescriptor type = builder.DescriptorForType;

                // The wire format for MessageSet is:
                //   message MessageSet {
                //     repeated group Item = 1 {
                //       required int32 typeId = 2;
                //       required bytes message = 3;
                //     }
                //   }
                // "typeId" is the extension's field number.  The extension can only be
                // a message type, where "message" contains the encoded bytes of that
                // message.
                //
                // In practice, we will probably never see a MessageSet item in which
                // the message appears before the type ID, or where either field does not
                // appear exactly once.  However, in theory such cases are valid, so we
                // should be prepared to accept them.

                int             typeId     = 0;
                ByteString      rawBytes   = null; // If we encounter "message" before "typeId"
                IBuilderLite    subBuilder = null;
                FieldDescriptor field      = null;

                while (true)
                {
                    uint tag = input.ReadTag();
                    if (tag == 0)
                    {
                        break;
                    }

                    if (tag == WireFormat.MessageSetTag.TypeID)
                    {
                        typeId = input.ReadInt32();
                        // Zero is not a valid type ID.
                        if (typeId != 0)
                        {
                            ExtensionInfo extension = extensionRegistry[type, typeId];
                            if (extension != null)
                            {
                                field      = extension.Descriptor;
                                subBuilder = extension.DefaultInstance.WeakCreateBuilderForType();
                                IMessageLite originalMessage = (IMessageLite)builder[field];
                                if (originalMessage != null)
                                {
                                    subBuilder.WeakMergeFrom(originalMessage);
                                }
                                if (rawBytes != null)
                                {
                                    // We already encountered the message.  Parse it now.
                                    // TODO(jonskeet): Check this is okay. It's subtly different from the Java, as it doesn't create an input stream from rawBytes.
                                    // In fact, why don't we just call MergeFrom(rawBytes)? And what about the extension registry?
                                    subBuilder.WeakMergeFrom(rawBytes.CreateCodedInput());
                                    rawBytes = null;
                                }
                            }
                            else
                            {
                                // Unknown extension number.  If we already saw data, put it
                                // in rawBytes.
                                if (rawBytes != null)
                                {
                                    MergeField(typeId, UnknownField.CreateBuilder().AddLengthDelimited(rawBytes).Build());
                                    rawBytes = null;
                                }
                            }
                        }
                    }
                    else if (tag == WireFormat.MessageSetTag.Message)
                    {
                        if (typeId == 0)
                        {
                            // We haven't seen a type ID yet, so we have to store the raw bytes for now.
                            rawBytes = input.ReadBytes();
                        }
                        else if (subBuilder == null)
                        {
                            // We don't know how to parse this.  Ignore it.
                            MergeField(typeId, UnknownField.CreateBuilder().AddLengthDelimited(input.ReadBytes()).Build());
                        }
                        else
                        {
                            // We already know the type, so we can parse directly from the input
                            // with no copying.  Hooray!
                            input.ReadMessage(subBuilder, extensionRegistry);
                        }
                    }
                    else
                    {
                        // Unknown tag.  Skip it.
                        if (!input.SkipField(tag))
                        {
                            break; // end of group
                        }
                    }
                }

                input.CheckLastTagWas(WireFormat.MessageSetTag.ItemEnd);

                if (subBuilder != null)
                {
                    builder[field] = subBuilder.WeakBuild();
                }
            }
Beispiel #26
0
            /// <summary>
            /// Like <see cref="MergeFrom(CodedInputStream, ExtensionRegistry, IBuilder)" />
            /// but parses a single field.
            /// </summary>
            /// <param name="input">The input to read the field from</param>
            /// <param name="extensionRegistry">Registry to use when an extension field is encountered</param>
            /// <param name="builder">Builder to merge field into, if it's a known field</param>
            /// <param name="tag">The tag, which should already have been read from the input</param>
            /// <returns>true unless the tag is an end-group tag</returns>
            internal bool MergeFieldFrom(CodedInputStream input,
                                         ExtensionRegistry extensionRegistry, IBuilder builder, uint tag)
            {
                MessageDescriptor type = builder.DescriptorForType;

                if (type.Options.MessageSetWireFormat && tag == WireFormat.MessageSetTag.ItemStart)
                {
                    MergeMessageSetExtensionFromCodedStream(input, extensionRegistry, builder);
                    return(true);
                }

                WireFormat.WireType wireType = WireFormat.GetTagWireType(tag);
                int fieldNumber = WireFormat.GetTagFieldNumber(tag);

                FieldDescriptor field;
                IMessageLite    defaultFieldInstance = null;

                if (type.IsExtensionNumber(fieldNumber))
                {
                    ExtensionInfo extension = extensionRegistry[type, fieldNumber];
                    if (extension == null)
                    {
                        field = null;
                    }
                    else
                    {
                        field = extension.Descriptor;
                        defaultFieldInstance = extension.DefaultInstance;
                    }
                }
                else
                {
                    field = type.FindFieldByNumber(fieldNumber);
                }

                // Unknown field or wrong wire type. Skip.
                if (field == null || wireType != WireFormat.GetWireType(field))
                {
                    return(MergeFieldFrom(tag, input));
                }

                if (field.IsPacked)
                {
                    int length = (int)input.ReadRawVarint32();
                    int limit  = input.PushLimit(length);
                    if (field.FieldType == FieldType.Enum)
                    {
                        while (!input.ReachedLimit)
                        {
                            int    rawValue = input.ReadEnum();
                            object value    = field.EnumType.FindValueByNumber(rawValue);
                            if (value == null)
                            {
                                // If the number isn't recognized as a valid value for this
                                // enum, drop it (don't even add it to unknownFields).
                                return(true);
                            }
                            builder.WeakAddRepeatedField(field, value);
                        }
                    }
                    else
                    {
                        while (!input.ReachedLimit)
                        {
                            Object value = input.ReadPrimitiveField(field.FieldType);
                            builder.WeakAddRepeatedField(field, value);
                        }
                    }
                    input.PopLimit(limit);
                }
                else
                {
                    object value;
                    switch (field.FieldType)
                    {
                    case FieldType.Group:
                    case FieldType.Message: {
                        IBuilderLite subBuilder;
                        if (defaultFieldInstance != null)
                        {
                            subBuilder = defaultFieldInstance.WeakCreateBuilderForType();
                        }
                        else
                        {
                            subBuilder = builder.CreateBuilderForField(field);
                        }
                        if (!field.IsRepeated)
                        {
                            subBuilder.WeakMergeFrom((IMessageLite)builder[field]);
                        }
                        if (field.FieldType == FieldType.Group)
                        {
                            input.ReadGroup(field.FieldNumber, subBuilder, extensionRegistry);
                        }
                        else
                        {
                            input.ReadMessage(subBuilder, extensionRegistry);
                        }
                        value = subBuilder.WeakBuild();
                        break;
                    }

                    case FieldType.Enum: {
                        int rawValue = input.ReadEnum();
                        value = field.EnumType.FindValueByNumber(rawValue);
                        // If the number isn't recognized as a valid value for this enum,
                        // drop it.
                        if (value == null)
                        {
                            MergeVarintField(fieldNumber, (ulong)rawValue);
                            return(true);
                        }
                        break;
                    }

                    default:
                        value = input.ReadPrimitiveField(field.FieldType);
                        break;
                    }
                    if (field.IsRepeated)
                    {
                        builder.WeakAddRepeatedField(field, value);
                    }
                    else
                    {
                        builder[field] = value;
                    }
                }
                return(true);
            }
Beispiel #27
0
 public byte[] GetPayload(CodedInputStream stream)
 {
     return stream.ReadRawBytes((int)this.Header.Size);
 }
        protected override bool ParseUnknownField(CodedInputStream input,
                                                  ExtensionRegistry extensionRegistry, uint tag)
        {
            FieldSet extensions = MessageBeingBuilt.Extensions;

            WireFormat.WireType wireType = WireFormat.GetTagWireType(tag);
            int fieldNumber = WireFormat.GetTagFieldNumber(tag);
            IGeneratedExtensionLite extension = extensionRegistry[DefaultInstanceForType, fieldNumber];

            bool unknown = false;
            bool packed  = false;

            if (extension == null)
            {
                unknown = true; // Unknown field.
            }
            else if (wireType == FieldMappingAttribute.WireTypeFromFieldType(extension.Descriptor.FieldType, false /* isPacked */))
            {
                packed = false; // Normal, unpacked value.
            }
            else if (extension.Descriptor.IsRepeated &&
                     //?? just returns true ?? extension.Descriptor.type.isPackable() &&
                     wireType == FieldMappingAttribute.WireTypeFromFieldType(extension.Descriptor.FieldType, true /* isPacked */))
            {
                packed = true; // Packed value.
            }
            else
            {
                unknown = true; // Wrong wire type.
            }

            if (unknown) // Unknown field or wrong wire type.  Skip.
            {
                return(input.SkipField(tag));
            }

            if (packed)
            {
                int length = (int)Math.Min(int.MaxValue, input.ReadRawVarint32());
                int limit  = input.PushLimit(length);
                if (extension.Descriptor.FieldType == FieldType.Enum)
                {
                    while (!input.ReachedLimit)
                    {
                        int    rawValue = input.ReadEnum();
                        Object value    =
                            extension.Descriptor.EnumType.FindValueByNumber(rawValue);
                        if (value == null)
                        {
                            // If the number isn't recognized as a valid value for this
                            // enum, drop it (don't even add it to unknownFields).
                            return(true);
                        }
                        extensions.AddRepeatedField(extension.Descriptor, value);
                    }
                }
                else
                {
                    while (!input.ReachedLimit)
                    {
                        Object value = input.ReadPrimitiveField(extension.Descriptor.FieldType);
                        extensions.AddRepeatedField(extension.Descriptor, value);
                    }
                }
                input.PopLimit(limit);
            }
            else
            {
                Object value;
                switch (extension.Descriptor.MappedType)
                {
                case MappedType.Message: {
                    IBuilderLite subBuilder = null;
                    if (!extension.Descriptor.IsRepeated)
                    {
                        IMessageLite existingValue = extensions[extension.Descriptor] as IMessageLite;
                        if (existingValue != null)
                        {
                            subBuilder = existingValue.WeakToBuilder();
                        }
                    }
                    if (subBuilder == null)
                    {
                        subBuilder = extension.MessageDefaultInstance.WeakCreateBuilderForType();
                    }
                    if (extension.Descriptor.FieldType == FieldType.Group)
                    {
                        input.ReadGroup(extension.Number, subBuilder, extensionRegistry);
                    }
                    else
                    {
                        input.ReadMessage(subBuilder, extensionRegistry);
                    }
                    value = subBuilder.WeakBuild();
                    break;
                }

                case MappedType.Enum:
                    int rawValue = input.ReadEnum();
                    value = extension.Descriptor.EnumType.FindValueByNumber(rawValue);
                    // If the number isn't recognized as a valid value for this enum,
                    // drop it.
                    if (value == null)
                    {
                        return(true);
                    }
                    break;

                default:
                    value = input.ReadPrimitiveField(extension.Descriptor.FieldType);
                    break;
                }

                if (extension.Descriptor.IsRepeated)
                {
                    extensions.AddRepeatedField(extension.Descriptor, value);
                }
                else
                {
                    extensions[extension.Descriptor] = value;
                }
            }

            return(true);
        }
    static int MergeFrom(IntPtr L)
    {
        try
        {
            int count = LuaDLL.lua_gettop(L);

            if (count == 2 && TypeChecker.CheckTypes <Google.ProtocolBuffers.IMessageLite>(L, 2))
            {
                Google.ProtocolBuffers.AbstractBuilderLite <MyLib.GCPlayerCmd, MyLib.GCPlayerCmd.Builder> obj = (Google.ProtocolBuffers.AbstractBuilderLite <MyLib.GCPlayerCmd, MyLib.GCPlayerCmd.Builder>)ToLua.CheckObject <Google.ProtocolBuffers.AbstractBuilderLite <MyLib.GCPlayerCmd, MyLib.GCPlayerCmd.Builder> >(L, 1);
                Google.ProtocolBuffers.IMessageLite arg0 = (Google.ProtocolBuffers.IMessageLite)ToLua.ToObject(L, 2);
                MyLib.GCPlayerCmd.Builder           o    = obj.MergeFrom(arg0);
                ToLua.PushSealed(L, o);
                return(1);
            }
            else if (count == 2 && TypeChecker.CheckTypes <Google.ProtocolBuffers.CodedInputStream>(L, 2))
            {
                Google.ProtocolBuffers.AbstractBuilderLite <MyLib.GCPlayerCmd, MyLib.GCPlayerCmd.Builder> obj = (Google.ProtocolBuffers.AbstractBuilderLite <MyLib.GCPlayerCmd, MyLib.GCPlayerCmd.Builder>)ToLua.CheckObject <Google.ProtocolBuffers.AbstractBuilderLite <MyLib.GCPlayerCmd, MyLib.GCPlayerCmd.Builder> >(L, 1);
                Google.ProtocolBuffers.CodedInputStream arg0 = (Google.ProtocolBuffers.CodedInputStream)ToLua.ToObject(L, 2);
                MyLib.GCPlayerCmd.Builder o = obj.MergeFrom(arg0);
                ToLua.PushSealed(L, o);
                return(1);
            }
            else if (count == 2 && TypeChecker.CheckTypes <Google.ProtocolBuffers.ByteString>(L, 2))
            {
                Google.ProtocolBuffers.AbstractBuilderLite <MyLib.GCPlayerCmd, MyLib.GCPlayerCmd.Builder> obj = (Google.ProtocolBuffers.AbstractBuilderLite <MyLib.GCPlayerCmd, MyLib.GCPlayerCmd.Builder>)ToLua.CheckObject <Google.ProtocolBuffers.AbstractBuilderLite <MyLib.GCPlayerCmd, MyLib.GCPlayerCmd.Builder> >(L, 1);
                Google.ProtocolBuffers.ByteString arg0 = (Google.ProtocolBuffers.ByteString)ToLua.ToObject(L, 2);
                MyLib.GCPlayerCmd.Builder         o    = obj.MergeFrom(arg0);
                ToLua.PushSealed(L, o);
                return(1);
            }
            else if (count == 2 && TypeChecker.CheckTypes <byte[]>(L, 2))
            {
                Google.ProtocolBuffers.AbstractBuilderLite <MyLib.GCPlayerCmd, MyLib.GCPlayerCmd.Builder> obj = (Google.ProtocolBuffers.AbstractBuilderLite <MyLib.GCPlayerCmd, MyLib.GCPlayerCmd.Builder>)ToLua.CheckObject <Google.ProtocolBuffers.AbstractBuilderLite <MyLib.GCPlayerCmd, MyLib.GCPlayerCmd.Builder> >(L, 1);
                byte[] arg0 = ToLua.CheckByteBuffer(L, 2);
                MyLib.GCPlayerCmd.Builder o = obj.MergeFrom(arg0);
                ToLua.PushSealed(L, o);
                return(1);
            }
            else if (count == 2 && TypeChecker.CheckTypes <System.IO.Stream>(L, 2))
            {
                Google.ProtocolBuffers.AbstractBuilderLite <MyLib.GCPlayerCmd, MyLib.GCPlayerCmd.Builder> obj = (Google.ProtocolBuffers.AbstractBuilderLite <MyLib.GCPlayerCmd, MyLib.GCPlayerCmd.Builder>)ToLua.CheckObject <Google.ProtocolBuffers.AbstractBuilderLite <MyLib.GCPlayerCmd, MyLib.GCPlayerCmd.Builder> >(L, 1);
                System.IO.Stream          arg0 = (System.IO.Stream)ToLua.ToObject(L, 2);
                MyLib.GCPlayerCmd.Builder o    = obj.MergeFrom(arg0);
                ToLua.PushSealed(L, o);
                return(1);
            }
            else if (count == 3 && TypeChecker.CheckTypes <Google.ProtocolBuffers.CodedInputStream, Google.ProtocolBuffers.ExtensionRegistry>(L, 2))
            {
                Google.ProtocolBuffers.AbstractBuilderLite <MyLib.GCPlayerCmd, MyLib.GCPlayerCmd.Builder> obj = (Google.ProtocolBuffers.AbstractBuilderLite <MyLib.GCPlayerCmd, MyLib.GCPlayerCmd.Builder>)ToLua.CheckObject <Google.ProtocolBuffers.AbstractBuilderLite <MyLib.GCPlayerCmd, MyLib.GCPlayerCmd.Builder> >(L, 1);
                Google.ProtocolBuffers.CodedInputStream  arg0 = (Google.ProtocolBuffers.CodedInputStream)ToLua.ToObject(L, 2);
                Google.ProtocolBuffers.ExtensionRegistry arg1 = (Google.ProtocolBuffers.ExtensionRegistry)ToLua.ToObject(L, 3);
                MyLib.GCPlayerCmd.Builder o = obj.MergeFrom(arg0, arg1);
                ToLua.PushSealed(L, o);
                return(1);
            }
            else if (count == 3 && TypeChecker.CheckTypes <Google.ProtocolBuffers.ByteString, Google.ProtocolBuffers.ExtensionRegistry>(L, 2))
            {
                Google.ProtocolBuffers.AbstractBuilderLite <MyLib.GCPlayerCmd, MyLib.GCPlayerCmd.Builder> obj = (Google.ProtocolBuffers.AbstractBuilderLite <MyLib.GCPlayerCmd, MyLib.GCPlayerCmd.Builder>)ToLua.CheckObject <Google.ProtocolBuffers.AbstractBuilderLite <MyLib.GCPlayerCmd, MyLib.GCPlayerCmd.Builder> >(L, 1);
                Google.ProtocolBuffers.ByteString        arg0 = (Google.ProtocolBuffers.ByteString)ToLua.ToObject(L, 2);
                Google.ProtocolBuffers.ExtensionRegistry arg1 = (Google.ProtocolBuffers.ExtensionRegistry)ToLua.ToObject(L, 3);
                MyLib.GCPlayerCmd.Builder o = obj.MergeFrom(arg0, arg1);
                ToLua.PushSealed(L, o);
                return(1);
            }
            else if (count == 3 && TypeChecker.CheckTypes <byte[], Google.ProtocolBuffers.ExtensionRegistry>(L, 2))
            {
                Google.ProtocolBuffers.AbstractBuilderLite <MyLib.GCPlayerCmd, MyLib.GCPlayerCmd.Builder> obj = (Google.ProtocolBuffers.AbstractBuilderLite <MyLib.GCPlayerCmd, MyLib.GCPlayerCmd.Builder>)ToLua.CheckObject <Google.ProtocolBuffers.AbstractBuilderLite <MyLib.GCPlayerCmd, MyLib.GCPlayerCmd.Builder> >(L, 1);
                byte[] arg0 = ToLua.CheckByteBuffer(L, 2);
                Google.ProtocolBuffers.ExtensionRegistry arg1 = (Google.ProtocolBuffers.ExtensionRegistry)ToLua.ToObject(L, 3);
                MyLib.GCPlayerCmd.Builder o = obj.MergeFrom(arg0, arg1);
                ToLua.PushSealed(L, o);
                return(1);
            }
            else if (count == 3 && TypeChecker.CheckTypes <System.IO.Stream, Google.ProtocolBuffers.ExtensionRegistry>(L, 2))
            {
                Google.ProtocolBuffers.AbstractBuilderLite <MyLib.GCPlayerCmd, MyLib.GCPlayerCmd.Builder> obj = (Google.ProtocolBuffers.AbstractBuilderLite <MyLib.GCPlayerCmd, MyLib.GCPlayerCmd.Builder>)ToLua.CheckObject <Google.ProtocolBuffers.AbstractBuilderLite <MyLib.GCPlayerCmd, MyLib.GCPlayerCmd.Builder> >(L, 1);
                System.IO.Stream arg0 = (System.IO.Stream)ToLua.ToObject(L, 2);
                Google.ProtocolBuffers.ExtensionRegistry arg1 = (Google.ProtocolBuffers.ExtensionRegistry)ToLua.ToObject(L, 3);
                MyLib.GCPlayerCmd.Builder o = obj.MergeFrom(arg0, arg1);
                ToLua.PushSealed(L, o);
                return(1);
            }
            else
            {
                return(LuaDLL.luaL_throw(L, "invalid arguments to method: Google.ProtocolBuffers.AbstractBuilderLite<MyLib.GCPlayerCmd,MyLib.GCPlayerCmd.Builder>.MergeFrom"));
            }
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e));
        }
    }
Beispiel #30
0
 protected override bool ParseUnknownField(CodedInputStream input, UnknownFieldSet.Builder unknownFields,
                                           ExtensionRegistry extensionRegistry, uint tag)
 {
     return(unknownFields.MergeFieldFrom(input, extensionRegistry, this, tag));
 }
Beispiel #31
0
 protected virtual bool ParseUnknownField(CodedInputStream input, UnknownFieldSet.Builder unknownFields,
                                          ExtensionRegistry extensionRegistry, uint tag)
 {
     return(unknownFields.MergeFieldFrom(tag, input));
 }
 public override Builder MergeFrom(CodedInputStream input, ExtensionRegistry extensionRegistry)
 {
     wrappedBuilder.WeakMergeFrom(input, extensionRegistry);
     return(this);
 }
 /// <summary>
 /// Parse a single field from <paramref name="input"/> and merge it
 /// into this set.
 /// </summary>
 /// <param name="tag">The field's tag number, which was already parsed.</param>
 /// <param name="input">The coded input stream containing the field</param>
 /// <returns>false if the tag is an "end group" tag, true otherwise</returns>
 public bool MergeFieldFrom(uint tag, CodedInputStream input)
 {
     int number = WireFormat.GetTagFieldNumber(tag);
     switch (WireFormat.GetTagWireType(tag)) {
       case WireFormat.WireType.Varint:
     GetFieldBuilder(number).AddVarint(input.ReadUInt64());
     return true;
       case WireFormat.WireType.Fixed64:
     GetFieldBuilder(number).AddFixed64(input.ReadFixed64());
     return true;
       case WireFormat.WireType.LengthDelimited:
     GetFieldBuilder(number).AddLengthDelimited(input.ReadBytes());
     return true;
       case WireFormat.WireType.StartGroup: {
     Builder subBuilder = CreateBuilder();
     input.ReadUnknownGroup(number, subBuilder);
     GetFieldBuilder(number).AddGroup(subBuilder.Build());
     return true;
       }
       case WireFormat.WireType.EndGroup:
     return false;
       case WireFormat.WireType.Fixed32:
     GetFieldBuilder(number).AddFixed32(input.ReadFixed32());
     return true;
       default:
     throw InvalidProtocolBufferException.InvalidWireType();
     }
 }
Beispiel #34
0
 public CodedInputStream CreateCodedInput()
 {
     return(CodedInputStream.CreateInstance(this.bytes));
 }
            /// <summary>
            /// Like <see cref="MergeFrom(CodedInputStream, ExtensionRegistry, IBuilder)" />
            /// but parses a single field.
            /// </summary>
            /// <param name="input">The input to read the field from</param>
            /// <param name="extensionRegistry">Registry to use when an extension field is encountered</param>
            /// <param name="builder">Builder to merge field into, if it's a known field</param>
            /// <param name="tag">The tag, which should already have been read from the input</param>
            /// <returns>true unless the tag is an end-group tag</returns>
            internal bool MergeFieldFrom(CodedInputStream input, 
          ExtensionRegistry extensionRegistry, IBuilder builder, uint tag)
            {
                MessageDescriptor type = builder.DescriptorForType;
                if (type.Options.MessageSetWireFormat && tag == WireFormat.MessageSetTag.ItemStart) {
                  MergeMessageSetExtensionFromCodedStream(input, extensionRegistry, builder);
                  return true;
                }

                WireFormat.WireType wireType = WireFormat.GetTagWireType(tag);
                int fieldNumber = WireFormat.GetTagFieldNumber(tag);

                FieldDescriptor field;
                IMessage defaultFieldInstance = null;

                if (type.IsExtensionNumber(fieldNumber)) {
                  ExtensionInfo extension = extensionRegistry[type, fieldNumber];
                  if (extension == null) {
                field = null;
                  } else {
                field = extension.Descriptor;
                defaultFieldInstance = extension.DefaultInstance;
                  }
                } else {
                  field = type.FindFieldByNumber(fieldNumber);
                }

                // Unknown field or wrong wire type. Skip.
                if (field == null || wireType != WireFormat.GetWireType(field)) {
                  return MergeFieldFrom(tag, input);
                }

                if (field.IsPacked) {
                  int length = (int)input.ReadRawVarint32();
                  int limit = input.PushLimit(length);
                  if (field.FieldType == FieldType.Enum) {
                while (!input.ReachedLimit) {
                  int rawValue = input.ReadEnum();
                  object value = field.EnumType.FindValueByNumber(rawValue);
                  if (value == null) {
                // If the number isn't recognized as a valid value for this
                // enum, drop it (don't even add it to unknownFields).
                return true;
                  }
                  builder.WeakAddRepeatedField(field, value);
                }
                  } else {
                while (!input.ReachedLimit) {
                  Object value = input.ReadPrimitiveField(field.FieldType);
                  builder.WeakAddRepeatedField(field, value);
                }
                  }
                  input.PopLimit(limit);
                } else {
                  object value;
                  switch (field.FieldType) {
                case FieldType.Group:
                case FieldType.Message: {
                IBuilder subBuilder;
                if (defaultFieldInstance != null) {
                  subBuilder = defaultFieldInstance.WeakCreateBuilderForType();
                } else {
                  subBuilder = builder.CreateBuilderForField(field);
                }
                if (!field.IsRepeated) {
                  subBuilder.WeakMergeFrom((IMessage)builder[field]);
                }
                if (field.FieldType == FieldType.Group) {
                  input.ReadGroup(field.FieldNumber, subBuilder, extensionRegistry);
                } else {
                  input.ReadMessage(subBuilder, extensionRegistry);
                }
                value = subBuilder.WeakBuild();
                break;
                  }
                case FieldType.Enum: {
                int rawValue = input.ReadEnum();
                value = field.EnumType.FindValueByNumber(rawValue);
                // If the number isn't recognized as a valid value for this enum,
                // drop it.
                if (value == null) {
                  MergeVarintField(fieldNumber, (ulong)rawValue);
                  return true;
                }
                break;
                  }
                default:
                  value = input.ReadPrimitiveField(field.FieldType);
                  break;
                  }
                  if (field.IsRepeated) {
                builder.WeakAddRepeatedField(field, value);
                  } else {
                builder[field] = value;
                  }
                }
                return true;
            }
Beispiel #36
0
 /// <summary>
 /// Creates a CodedInputStream from this ByteString's data.
 /// </summary>
 public CodedInputStream CreateCodedInput()
 {
     // We trust CodedInputStream not to reveal the provided byte array or modify it
     return(CodedInputStream.CreateInstance(bytes));
 }
            /// <summary>
            /// Called by MergeFieldFrom to parse a MessageSet extension.
            /// </summary>
            private void MergeMessageSetExtensionFromCodedStream(CodedInputStream input,
          ExtensionRegistry extensionRegistry, IBuilder builder)
            {
                MessageDescriptor type = builder.DescriptorForType;

                // The wire format for MessageSet is:
                //   message MessageSet {
                //     repeated group Item = 1 {
                //       required int32 typeId = 2;
                //       required bytes message = 3;
                //     }
                //   }
                // "typeId" is the extension's field number.  The extension can only be
                // a message type, where "message" contains the encoded bytes of that
                // message.
                //
                // In practice, we will probably never see a MessageSet item in which
                // the message appears before the type ID, or where either field does not
                // appear exactly once.  However, in theory such cases are valid, so we
                // should be prepared to accept them.

                int typeId = 0;
                ByteString rawBytes = null;  // If we encounter "message" before "typeId"
                IBuilder subBuilder = null;
                FieldDescriptor field = null;

                while (true) {
                  uint tag = input.ReadTag();
                  if (tag == 0) {
                break;
                  }

                  if (tag == WireFormat.MessageSetTag.TypeID) {
                typeId = input.ReadInt32();
                // Zero is not a valid type ID.
                if (typeId != 0) {
                  ExtensionInfo extension = extensionRegistry[type, typeId];
                  if (extension != null) {
                field = extension.Descriptor;
                subBuilder = extension.DefaultInstance.WeakCreateBuilderForType();
                IMessage originalMessage = (IMessage)builder[field];
                if (originalMessage != null) {
                  subBuilder.WeakMergeFrom(originalMessage);
                }
                if (rawBytes != null) {
                  // We already encountered the message.  Parse it now.
                  // TODO(jonskeet): Check this is okay. It's subtly different from the Java, as it doesn't create an input stream from rawBytes.
                  // In fact, why don't we just call MergeFrom(rawBytes)? And what about the extension registry?
                  subBuilder.WeakMergeFrom(rawBytes.CreateCodedInput());
                  rawBytes = null;
                }
                  } else {
                // Unknown extension number.  If we already saw data, put it
                // in rawBytes.
                if (rawBytes != null) {
                  MergeField(typeId, UnknownField.CreateBuilder().AddLengthDelimited(rawBytes).Build());
                  rawBytes = null;
                }
                  }
                }
                  } else if (tag == WireFormat.MessageSetTag.Message) {
                if (typeId == 0) {
                  // We haven't seen a type ID yet, so we have to store the raw bytes for now.
                  rawBytes = input.ReadBytes();
                } else if (subBuilder == null) {
                  // We don't know how to parse this.  Ignore it.
                  MergeField(typeId, UnknownField.CreateBuilder().AddLengthDelimited(input.ReadBytes()).Build());
                } else {
                  // We already know the type, so we can parse directly from the input
                  // with no copying.  Hooray!
                  input.ReadMessage(subBuilder, extensionRegistry);
                }
                  } else {
                // Unknown tag.  Skip it.
                if (!input.SkipField(tag)) {
                  break;  // end of group
                }
                  }
                }

                input.CheckLastTagWas(WireFormat.MessageSetTag.ItemEnd);

                if (subBuilder != null) {
                  builder[field] = subBuilder.WeakBuild();
                }
            }
Beispiel #38
0
 IBuilder IBuilder.WeakMergeFrom(CodedInputStream input)
 {
     return(MergeFrom(input));
 }
Beispiel #39
0
 IBuilder IBuilder.WeakMergeFrom(CodedInputStream input, ExtensionRegistry registry)
 {
     return(MergeFrom(input, registry));
 }
        /// <summary>
        /// Method we'll use to build messageReader, with the first parameter fixed to TMessage.CreateBuilder. Note that we
        /// have to introduce another type parameter (TMessage2) as we can't constrain TMessage for just a single method
        /// (and we can't do it at the type level because we don't know TBuilder). However, by constraining TMessage2
        /// to not only implement IMessage appropriately but also to derive from TMessage2, we can avoid doing a cast
        /// for every message; the implicit reference conversion will be fine. In practice, TMessage2 and TMessage will
        /// be the same type when we construct the generic method by reflection.
        /// </summary>
        private static TMessage BuildImpl <TMessage2, TBuilder>(Func <TBuilder> builderBuilder, CodedInputStream input, ExtensionRegistry registry)
            where TBuilder : IBuilder <TMessage2, TBuilder>
            where TMessage2 : TMessage, IMessage <TMessage2, TBuilder>
        {
            TBuilder builder = builderBuilder();

            input.ReadMessage(builder, registry);
            return(builder.Build());
        }