Encodes and writes protocol message fields.

This class is generally used by generated code to write appropriate primitives to the stream. It effectively encapsulates the lowest levels of protocol buffer format. Unlike some other implementations, this does not include combined "write tag and value" methods. Generated code knows the exact byte representations of the tags they're going to write, so there's no need to re-encode them each time. Manually-written code calling this class should just call one of the WriteTag overloads before each value.

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

Esempio n. 1
1
 public static byte[] ProtoToByteArray(IMessage message)
 {
     int size = message.CalculateSize();
     byte[] buffer = new byte[size];
     CodedOutputStream output = new CodedOutputStream(buffer);
     message.WriteTo(output);
     return buffer;
 }
Esempio n. 2
1
 public static byte[] ToByteArray(this IMessage message)
 {
     Preconditions.CheckNotNull(message, "message");
     byte[] result = new byte[message.CalculateSize()];
     CodedOutputStream output = new CodedOutputStream(result);
     message.WriteTo(output);
     output.CheckNoSpaceLeft();
     return result;
 }
Esempio n. 3
0
    public void OnPlayerRequestGameTest(byte[] pBuf)
    {
        GameProto.PlayerRequestGameTest oTest = GameProto.PlayerRequestGameTest.Parser.ParseFrom(pBuf);
        if (oTest == null)
        {
            H5Helper.H5LogStr("OnTest error parse");
            return;
        }

        H5Helper.H5LogStr(oTest.SzTest.ToString());

        oTest.SzTest = String.Format("{0}, {1}, {2}, {3}, {4}, {5}",
                                     "sessionobject.cs", 106, "SessionObject::OnRecv", dw1++,
                                     ToString(), DateTime.Now.ToLocalTime().ToString());

        byte[]          pData   = new byte[1024];
        FxNet.NetStream pStream = new FxNet.NetStream(FxNet.NetStream.ENetStreamType.ENetStreamType_Write, pData, 1024);
        pStream.WriteString("GameProto.PlayerRequestGameTest");
        byte[] pProto = new byte[oTest.CalculateSize()];
        Google.Protobuf.CodedOutputStream oStream = new Google.Protobuf.CodedOutputStream(pProto);
        oTest.WriteTo(oStream);
        pStream.WriteData(pProto, (uint)pProto.Length);

        m_pSession.Send(pData, 1024 - pStream.GetLeftLen());
    }
Esempio n. 4
0
 static ByteString EncodeObject (object value, Type type, MemoryStream buffer, CodedOutputStream stream)
 {
     buffer.SetLength (0);
     if (value != null && !type.IsInstanceOfType (value))
         throw new ArgumentException ("Value of type " + value.GetType () + " cannot be encoded to type " + type);
     if (value == null && !type.IsSubclassOf (typeof(RemoteObject)) && !IsACollectionType (type))
         throw new ArgumentException ("null cannot be encoded to type " + type);
     if (value == null)
         stream.WriteUInt64 (0);
     else if (value is Enum)
         stream.WriteInt32 ((int)value);
     else {
         switch (Type.GetTypeCode (type)) {
         case TypeCode.Int32:
             stream.WriteInt32 ((int)value);
             break;
         case TypeCode.Int64:
             stream.WriteInt64 ((long)value);
             break;
         case TypeCode.UInt32:
             stream.WriteUInt32 ((uint)value);
             break;
         case TypeCode.UInt64:
             stream.WriteUInt64 ((ulong)value);
             break;
         case TypeCode.Single:
             stream.WriteFloat ((float)value);
             break;
         case TypeCode.Double:
             stream.WriteDouble ((double)value);
             break;
         case TypeCode.Boolean:
             stream.WriteBool ((bool)value);
             break;
         case TypeCode.String:
             stream.WriteString ((string)value);
             break;
         default:
             if (type.Equals (typeof(byte[])))
                 stream.WriteBytes (ByteString.CopyFrom ((byte[])value));
             else if (IsAClassType (type))
                 stream.WriteUInt64 (((RemoteObject)value).id);
             else if (IsAMessageType (type))
                 ((IMessage)value).WriteTo (buffer);
             else if (IsAListType (type))
                 WriteList (value, type, buffer);
             else if (IsADictionaryType (type))
                 WriteDictionary (value, type, buffer);
             else if (IsASetType (type))
                 WriteSet (value, type, buffer);
             else if (IsATupleType (type))
                 WriteTuple (value, type, buffer);
             else
                 throw new ArgumentException (type + " is not a serializable type");
             break;
         }
     }
     stream.Flush ();
     return ByteString.CopyFrom (buffer.GetBuffer (), 0, (int)buffer.Length);
 }
Esempio n. 5
0
 public static byte[] ToByteArray(this IMessage self, String filePath)
 {
     byte[] ret = new byte[self.CalculateSize()];
     Google.Protobuf.CodedOutputStream os = new Google.Protobuf.CodedOutputStream(ret);
     self.WriteTo(os);
     return(ret);
 }
Esempio n. 6
0
 /// <summary>
 /// Encode an object of the given type using the protocol buffer encoding scheme.
 /// Should not be called directly. This interface is used by service client stubs.
 /// </summary>
 public static ByteString Encode (object value, Type type)
 {
     using (var buffer = new MemoryStream ()) {
         var stream = new CodedOutputStream (buffer, true);
         return EncodeObject (value, type, buffer, stream);
     }
 }
Esempio n. 7
0
 static ByteString EncodeObject (object value, MemoryStream buffer, CodedOutputStream stream)
 {
     buffer.SetLength (0);
     if (value == null) {
         stream.WriteUInt64 (0);
     } else if (value is Enum) {
         stream.WriteInt32 ((int)value);
     } else {
         Type type = value.GetType ();
         switch (Type.GetTypeCode (type)) {
         case TypeCode.Int32:
             stream.WriteInt32 ((int)value);
             break;
         case TypeCode.Int64:
             stream.WriteInt64 ((long)value);
             break;
         case TypeCode.UInt32:
             stream.WriteUInt32 ((uint)value);
             break;
         case TypeCode.UInt64:
             stream.WriteUInt64 ((ulong)value);
             break;
         case TypeCode.Single:
             stream.WriteFloat ((float)value);
             break;
         case TypeCode.Double:
             stream.WriteDouble ((double)value);
             break;
         case TypeCode.Boolean:
             stream.WriteBool ((bool)value);
             break;
         case TypeCode.String:
             stream.WriteString ((string)value);
             break;
         default:
             if (type == typeof(byte[]))
                 stream.WriteBytes (ByteString.CopyFrom ((byte[])value));
             else if (TypeUtils.IsAClassType (type))
                 stream.WriteUInt64 (ObjectStore.Instance.AddInstance (value));
             else if (TypeUtils.IsAMessageType (type))
                 WriteMessage (value, stream);
             else if (TypeUtils.IsAListCollectionType (type))
                 WriteList (value, stream);
             else if (TypeUtils.IsADictionaryCollectionType (type))
                 WriteDictionary (value, stream);
             else if (TypeUtils.IsASetCollectionType (type))
                 WriteSet (value, stream);
             else if (TypeUtils.IsATupleCollectionType (type))
                 WriteTuple (value, stream);
             else
                 throw new ArgumentException (type + " is not a serializable type");
             break;
         }
     }
     stream.Flush ();
     return ByteString.CopyFrom (buffer.GetBuffer (), 0, (int)buffer.Length);
 }
Esempio n. 8
0
 public void LoginReq(string userName)
 {
     byte[] send_data = new byte[1024];
     loginReq.Id = userName;
     Google.Protobuf.CodedOutputStream reqStream = new Google.Protobuf.CodedOutputStream(send_data);
     // Make MemoryStream
     loginReq.WriteTo(reqStream);
     Send(send_data, send_data.Length, DnaInfo.packet_type.LoginReq);
 }
Esempio n. 9
0
    static Proto3Objects.PersonVector SerializeArrayProto3(IList <Person> original)
    {
        Console.WriteLine("Google.Protobuf");

        Proto3Objects.PersonVector copy = default(Proto3Objects.PersonVector);
        MemoryStream stream             = null;

        var person = new Proto3Objects.PersonVector();

        person.List.AddRange(original.Select(x => new Proto3Objects.Person
        {
            Age       = x.Age,
            FirstName = x.FirstName,
            LastName  = x.LastName,
            Sex       = (Proto3Objects.Sex)(int) x.Sex
        }));

        using (new Measure("Serialize"))
        {
            for (int i = 0; i < Iteration; i++)
            {
                using (var writeStream = new Google.Protobuf.CodedOutputStream(stream = new MemoryStream(), true))
                {
                    person.WriteTo(writeStream);
                }
            }
        }

        byte[] inputBytes = stream.ToArray();

        using (new Measure("Deserialize"))
        {
            for (int i = 0; i < Iteration; i++)
            {
                copy = Proto3Objects.PersonVector.Parser.ParseFrom(inputBytes);
            }
        }

        using (new Measure("ReSerialize"))
        {
            for (int i = 0; i < Iteration; i++)
            {
                using (var writeStream = new Google.Protobuf.CodedOutputStream(stream = new MemoryStream(), true))
                {
                    copy.WriteTo(writeStream);
                }
            }
        }

        if (!dryRun)
        {
            Console.WriteLine(string.Format("{0,15}   {1}", "Binary Size", ToHumanReadableSize(stream.Position)));
        }

        return(copy);
    }
Esempio n. 10
0
 public void ValueTypeToByteString ()
 {
     // From Google's protobuf documentation, varint encoding example:
     // 300 = 1010 1100 0000 0010 = 0xAC 0x02
     const int value = 300;
     var buffer = new byte [2];
     var codedStream = new CodedOutputStream (buffer);
     codedStream.WriteUInt32 (value);
     Assert.AreEqual ("ac02", buffer.ToHexString ());
 }
Esempio n. 11
0
        /// <summary>
        /// Convert class ByteString
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static byte[] MarshalByte(Google.Protobuf.IMessage msg)
        {
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                var s = new Google.Protobuf.CodedOutputStream(ms);
                msg.WriteTo(s);
                s.Flush();

                return(ms.ToArray());
            }
        }
Esempio n. 12
0
 public void ValueTypeToByteString()
 {
     // From Google's protobuf documentation, varint encoding example:
     // 300 = 1010 1100 0000 0010 = 0xAC 0x02
     const int value = 300;
     var buffer = new byte [2];
     var codedStream = new CodedOutputStream (buffer);
     codedStream.WriteUInt32 (value);
     string hex = ("0x" + BitConverter.ToString (buffer)).Replace ("-", " 0x");
     Assert.AreEqual ("0xAC 0x02", hex);
 }
Esempio n. 13
0
 public override void SaveModel(GraphModel model, string path)
 {
     using (var output = File.Create(path))
     {
         using (Google.Protobuf.CodedOutputStream ff = new Google.Protobuf.CodedOutputStream(output))
         {
             (model as OnnxGraphModel).ProtoModel.WriteTo(ff);
         }
     }
     return;
 }
Esempio n. 14
0
 /// <summary>
 /// Convert class ByteString
 /// </summary>
 /// <param name="msg"></param>
 /// <returns></returns>
 public static Google.Protobuf.ByteString Marshal(Google.Protobuf.IMessage msg)
 {
     using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
     {
         var s = new Google.Protobuf.CodedOutputStream(ms);
         msg.WriteTo(s);
         s.Flush();
         var str = Google.Protobuf.ByteString.CopyFrom(ms.ToArray());
         return(str);
     }
 }
Esempio n. 15
0
 public void Dispose_DisposesUnderlyingStream()
 {
     var memoryStream = new MemoryStream();
     Assert.IsTrue(memoryStream.CanWrite);
     using (var cos = new CodedOutputStream(memoryStream))
     {
         cos.WriteRawByte(0);
         Assert.AreEqual(0, memoryStream.Position); // Not flushed yet
     }
     Assert.AreEqual(1, memoryStream.ToArray().Length); // Flushed data from CodedOutputStream to MemoryStream
     Assert.IsFalse(memoryStream.CanWrite); // Disposed
 }
Esempio n. 16
0
 public void Dispose_WithLeaveOpen()
 {
     var memoryStream = new MemoryStream();
     Assert.IsTrue(memoryStream.CanWrite);
     using (var cos = new CodedOutputStream(memoryStream, true))
     {
         cos.WriteRawByte(0);
         Assert.AreEqual(0, memoryStream.Position); // Not flushed yet
     }
     Assert.AreEqual(1, memoryStream.Position); // Flushed data from CodedOutputStream to MemoryStream
     Assert.IsTrue(memoryStream.CanWrite); // We left the stream open
 }
Esempio n. 17
0
        /// <summary>
        /// Applies basic AES encryption with the provided <paramref name="key"/>, with generated IV
        /// pasted in front of cipher text, before writing to the disk.
        /// </summary>
        /// <typeparam name="P">Your protobuf type here.</typeparam>
        public static MemoryStream ProtoToStream <P>(P save, byte[] key)
            where P : IMessage <P>, new()
        {
            MemoryStream             memStream = new MemoryStream();
            AesCryptoServiceProvider aes       = new AesCryptoServiceProvider();

            aes.Key = key;
            aes.GenerateIV();
            aes.Mode    = CipherMode.CBC;
            aes.Padding = PaddingMode.PKCS7;
            // Debug.Log(aes.BlockSize);
            // Debug.Log(aes.KeySize);
            // Debug.Log(aes.FeedbackSize);
            // Debug.Log(aes.Padding);

            //Simply paste the initialization vector in front of cipher text.
            memStream.Write(aes.IV, 0, 16);

            // Debug.Log("Key " + BitConverter.ToString(aes.Key));
            // Debug.Log("IV " + BitConverter.ToString(aes.IV));
            // using (MemoryStream ms = new MemoryStream())
            // {
            //     using (Google.Protobuf.CodedOutputStream cos = new CodedOutputStream(ms))
            //     {
            //         save.WriteTo(cos);
            //     }
            //     Debug.Log(save);
            //     var a = ms.ToArray();
            //     Debug.Log(string.Join(" ", a.Select(x => x.ToString("X2"))));
            //     Debug.Log(a.Length);

            //     using (MemoryStream ms2 = new MemoryStream())
            //     {
            //         using (var cryptoStream = new CryptoStream(ms2, aes.CreateEncryptor(), CryptoStreamMode.Write))
            //         {
            //             cryptoStream.Write(a, 0, a.Length);
            //         }
            //         Debug.Log(string.Join(" ", ms2.ToArray().Select(x => x.ToString("X2"))));
            //         Debug.Log(ms2.ToArray().Length);
            //     }
            // }

            using (var cryptoStream = new CryptoStream(memStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
            {
                using (Google.Protobuf.CodedOutputStream cos = new Google.Protobuf.CodedOutputStream(cryptoStream))
                {
                    save.WriteTo(cos);
                }
            }
            // Debug.Log(string.Join( " " , memStream.ToArray().Select(x => x.ToString("X2"))));
            // Debug.Log(memStream.ToArray().Length);
            return(memStream);
        }
Esempio n. 18
0
    public void MakeTeam()
    {
        GameProto.PlayerRequestLoginMakeTeam oTeam = new GameProto.PlayerRequestLoginMakeTeam();
        byte[]          pData   = new byte[1024];
        FxNet.NetStream pStream = new FxNet.NetStream(FxNet.NetStream.ENetStreamType.ENetStreamType_Write, pData, 1024);
        pStream.WriteString("GameProto.PlayerRequestLoginMakeTeam");
        byte[] pProto = new byte[oTeam.CalculateSize()];
        Google.Protobuf.CodedOutputStream oStream = new Google.Protobuf.CodedOutputStream(pProto);
        oTeam.WriteTo(oStream);
        pStream.WriteData(pProto, (uint)pProto.Length);

        m_pSession.Send(pData, 1024 - pStream.GetLeftLen());
    }
        private byte[] StringToByteBuffer(string str)
        {
            int t = CodedOutputStream.ComputeTagSize(9);
            int s = CodedOutputStream.ComputeStringSize(str);

            s += t;
            byte[] bytes = new byte[s];
            CodedOutputStream cos = new CodedOutputStream(bytes);
            cos.WriteTag((9 << 3) + 2);
            cos.WriteString(str);
            cos.Flush();
            return bytes;
        }
Esempio n. 20
0
    public void SendReq(GameState request, out String response)
    {
        byte[] bytes = new byte[request.CalculateSize()];
        Google.Protobuf.CodedOutputStream codedOutputStream = new Google.Protobuf.CodedOutputStream(bytes);
        request.WriteTo(codedOutputStream);
        codedOutputStream.Flush();
        codedOutputStream.CheckNoSpaceLeft();
        networkStream.Write(bytes, 0, bytes.Length);
        networkStream.Flush();
        byte[] toRead    = new byte[tcpClient.ReceiveBufferSize];
        int    bytesRead = networkStream.Read(toRead, 0, tcpClient.ReceiveBufferSize);

        response = Encoding.UTF8.GetString(toRead, 0, bytesRead);
    }
Esempio n. 21
0
    void ChattingGUI()
    {
        Rect commentRect = new Rect(220, 450, 300, 30);

        m_sendComment = GUI.TextField(commentRect, m_sendComment, 15);

        bool isSent = GUI.Button(new Rect(530, 450, 100, 30), "말하기");

        if (Event.current.isKey && Event.current.keyCode == KeyCode.Return)
        {
            if (m_sendComment == m_prevComment)
            {
                isSent        = true;
                m_prevComment = "";
            }
            else
            {
                m_prevComment = m_sendComment;
            }
        }

        if (isSent == true)
        {
            var requestPkt = new CSMsgPackPacket.ChatReqPkt();
            requestPkt.UserID = m_NickName;
            requestPkt.Msg    = m_sendComment;

            System.IO.MemoryStream reqStream = new System.IO.MemoryStream();
            var output = new Google.Protobuf.CodedOutputStream(reqStream);
            requestPkt.WriteTo(output);

            PostSendPacket(PACKET_ID.PACKET_ID_SIMPLE_CHAT, reqStream.ToArray());

            m_sendComment = "";
        }


        if (GUI.Button(new Rect(700, 560, 80, 30), "나가기"))
        {
            m_state = ChatState.LEAVE;
        }

        if (m_transport.IsConnected)
        {
            // 콩장수의(클라이언트 측) 메시지 표시.
            DispBalloon(ref m_message, new Vector2(600.0f, 200.0f), new Vector2(340.0f, 360.0f), Color.green, false);
            GUI.DrawTexture(new Rect(600.0f, 370.0f, 145.0f, 200.0f), this.texture_daizu);
        }
    }
Esempio n. 22
0
    public void SendReq(GameState gameState, out string recievedMessage)
    {
        byte[] bytes = new byte[gameState.CalculateSize()];
        Google.Protobuf.CodedOutputStream codedOutputStream = new Google.Protobuf.CodedOutputStream(bytes);
        gameState.WriteTo(codedOutputStream);
        codedOutputStream.Flush();

        client.SendFrame(bytes, false);
        //recievedMessage = client.ReceiveFrameString();
        if (!client.TryReceiveFrameString(new TimeSpan(0, 0, 1), out recievedMessage))
        {
            recievedMessage = "";
            UnityEditor.EditorApplication.isPlaying = false;
        }
    }
Esempio n. 23
0
        /// <summary>
        /// Writes the given value using WriteRawVarint32() and WriteRawVarint64() and
        /// checks that the result matches the given bytes
        /// </summary>
        private static void AssertWriteVarint(byte[] data, ulong value)
        {
            // Only do 32-bit write if the value fits in 32 bits.
            if ((value >> 32) == 0)
            {
                MemoryStream rawOutput = new MemoryStream();
                CodedOutputStream output = new CodedOutputStream(rawOutput);
                output.WriteRawVarint32((uint) value);
                output.Flush();
                Assert.AreEqual(data, rawOutput.ToArray());
                // Also try computing size.
                Assert.AreEqual(data.Length, CodedOutputStream.ComputeRawVarint32Size((uint) value));
            }

            {
                MemoryStream rawOutput = new MemoryStream();
                CodedOutputStream output = new CodedOutputStream(rawOutput);
                output.WriteRawVarint64(value);
                output.Flush();
                Assert.AreEqual(data, rawOutput.ToArray());

                // Also try computing size.
                Assert.AreEqual(data.Length, CodedOutputStream.ComputeRawVarint64Size(value));
            }

            // Try different buffer sizes.
            for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2)
            {
                // Only do 32-bit write if the value fits in 32 bits.
                if ((value >> 32) == 0)
                {
                    MemoryStream rawOutput = new MemoryStream();
                    CodedOutputStream output =
                        new CodedOutputStream(rawOutput, bufferSize);
                    output.WriteRawVarint32((uint) value);
                    output.Flush();
                    Assert.AreEqual(data, rawOutput.ToArray());
                }

                {
                    MemoryStream rawOutput = new MemoryStream();
                    CodedOutputStream output = new CodedOutputStream(rawOutput, bufferSize);
                    output.WriteRawVarint64(value);
                    output.Flush();
                    Assert.AreEqual(data, rawOutput.ToArray());
                }
            }
        }
Esempio n. 24
0
    public void InvitePlayer()
    {
        GameProto.PlayerRequestLoginInviteTeam oTeam = new GameProto.PlayerRequestLoginInviteTeam();
        oTeam.QwPlayerId = m_qwPlayerId;
        byte[]          pData   = new byte[1024];
        FxNet.NetStream pStream = new FxNet.NetStream(FxNet.NetStream.ENetStreamType.ENetStreamType_Write, pData, 1024);
        pStream.WriteString("GameProto.PlayerRequestLoginInviteTeam");
        byte[] pProto = new byte[oTeam.CalculateSize()];
        Google.Protobuf.CodedOutputStream oStream = new Google.Protobuf.CodedOutputStream(pProto);
        oTeam.WriteTo(oStream);
        pStream.WriteData(pProto, (uint)pProto.Length);

        H5Manager.Instance().GetLoginSession().Send(pData, 1024 - pStream.GetLeftLen());

        //m_pSession.Send(pData, 1024 - pStream.GetLeftLen());
    }
Esempio n. 25
0
     public void WriteTo(pb.CodedOutputStream output)
     {
 #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
         output.WriteRawMessage(this);
 #else
         if (ClientId.Length != 0)
         {
             output.WriteRawTag(10);
             output.WriteString(ClientId);
         }
         if (MessageId.Length != 0)
         {
             output.WriteRawTag(18);
             output.WriteString(MessageId);
         }
         if (Type != MessageType.Undefined)
         {
             output.WriteRawTag(24);
             output.WriteEnum((int)Type);
         }
         if (time_ != null)
         {
             output.WriteRawTag(34);
             output.WriteMessage(Time);
         }
         if (Status != MessageStatus.Undefined)
         {
             output.WriteRawTag(40);
             output.WriteEnum((int)Status);
         }
         if (Payload.Length != 0)
         {
             output.WriteRawTag(50);
             output.WriteBytes(Payload);
         }
         if (Response != ResponseType.Undefined)
         {
             output.WriteRawTag(56);
             output.WriteEnum((int)Response);
         }
         if (_unknownFields != null)
         {
             _unknownFields.WriteTo(output);
         }
 #endif
     }
Esempio n. 26
0
    public void OnRoleData(string szData)
    {
        SampleDebuger.Log(szData);
        RoleDataRet oData = JsonUtility.FromJson <RoleDataRet>(szData);

        GameProto.PlayerRequestLogin oTest = new GameProto.PlayerRequestLogin();
        oTest.SzToken    = oData.token;
        oTest.QwPlayerId = oData.data.id;
        oTest.SzAvatar   = oData.data.avatar;
        oTest.SzNickName = oData.data.nick_name;
        oTest.DwSex      = oData.data.sex;
        oTest.DwBalance  = oData.data.balance;

        StartCoroutine(H5Helper.SendGet(oData.data.avatar, delegate(Texture2D tex)
        {
            PlayerData.Instance().SetHeadTex(tex);
        })
                       );

        PlayerData.Instance().SetPlayerId(oData.data.id);
        PlayerData.Instance().SetName(oData.data.nick_name);
        PlayerData.Instance().SetHeadImage(oData.data.avatar);
        PlayerData.Instance().SetSex(oData.data.sex);
        PlayerData.Instance().SetBalance(oData.data.balance);
        PlayerData.Instance().SetToken(oData.token);

        byte[]          pData   = new byte[2048];
        FxNet.NetStream pStream = new FxNet.NetStream(FxNet.NetStream.ENetStreamType.ENetStreamType_Write, pData, 2048);
        pStream.WriteString("GameProto.PlayerRequestLogin");
        byte[] pProto = new byte[oTest.CalculateSize()];
        Google.Protobuf.CodedOutputStream oStream = new Google.Protobuf.CodedOutputStream(pProto);
        oTest.WriteTo(oStream);
        pStream.WriteData(pProto, (uint)pProto.Length);

        m_pSession.Send(pData, 2048 - pStream.GetLeftLen());

        if (!string.IsNullOrEmpty(oData.game_ip))
        {
            PlayerData.Instance().SetGameIp(oData.game_ip);
            PlayerData.Instance().SetGamePort((ushort)oData.game_port);
        }
    }
Esempio n. 27
0
        public void TestRoundTripNegativeEnums()
        {
            NegativeEnumMessage msg = new NegativeEnumMessage
            {
                Value = NegativeEnum.MinusOne,
                Values = { NegativeEnum.NEGATIVE_ENUM_ZERO, NegativeEnum.MinusOne, NegativeEnum.FiveBelow },
                PackedValues = { NegativeEnum.NEGATIVE_ENUM_ZERO, NegativeEnum.MinusOne, NegativeEnum.FiveBelow }
            };

            Assert.AreEqual(58, msg.CalculateSize());

            byte[] bytes = new byte[58];
            CodedOutputStream output = new CodedOutputStream(bytes);

            msg.WriteTo(output);
            Assert.AreEqual(0, output.SpaceLeft);

            NegativeEnumMessage copy = NegativeEnumMessage.Parser.ParseFrom(bytes);
            Assert.AreEqual(msg, copy);
        }
        private byte[] ObjectToByteBuffer(int descriptorId, object obj)
        {
            IMessage u = (IMessage)obj;

            int size = u.CalculateSize();
            byte[] bytes = new byte[size];
            CodedOutputStream cos = new CodedOutputStream(bytes);
            u.WriteTo(cos);
            
            cos.Flush();
            WrappedMessage wm = new WrappedMessage();
            wm.WrappedMessageBytes = ByteString.CopyFrom(bytes);
            wm.WrappedDescriptorId = descriptorId;

            byte[] msgBytes = new byte[wm.CalculateSize()];
            CodedOutputStream msgCos = new CodedOutputStream(msgBytes);
            wm.WriteTo(msgCos);
            msgCos.Flush();
            return msgBytes;
        }
Esempio n. 29
0
    byte[] _Serialize()
    {
        mSample.Id   = 7761;
        mSample.Name = "Cho Myeong Geun";

        mJsonText = GetjsonText();

        var bufSize = mSample.CalculateSize();

        using (var memStream = new MemoryStream(bufSize))
        {
            using (var outStream = new PB.CodedOutputStream(memStream))
            {
                mSample.WriteTo(outStream);
                outStream.Flush();

                return(memStream.ToArray());
            }
        }
    }
Esempio n. 30
0
        public void SimpleProtobufUsage ()
        {
            const string SERVICE = "a";
            const string METHOD = "b";

            var request = new Request ();
            request.Service = SERVICE;
            request.Procedure = METHOD;

            Assert.AreEqual (METHOD, request.Procedure);
            Assert.AreEqual (SERVICE, request.Service);

            var buffer = new byte [request.CalculateSize ()];
            var stream = new CodedOutputStream (buffer);
            request.WriteTo (stream);

            Request reqCopy = Request.Parser.ParseFrom (buffer);

            Assert.AreEqual (METHOD, reqCopy.Procedure);
            Assert.AreEqual (SERVICE, reqCopy.Service);
        }
Esempio n. 31
0
    public void IntoInviteTeam(object pParam)
    {
        GameProto.LoginNotifyPlayerInviteTeam oInvite = pParam as GameProto.LoginNotifyPlayerInviteTeam;
        if (oInvite == null)
        {
            H5Helper.H5AlertString("IntoInviteTeam parse error!!!!");
            return;
        }
        GameProto.PlayerRequestLoginEnterTeam oRequest = new GameProto.PlayerRequestLoginEnterTeam();
        oRequest.DwTeamServerId = oInvite.DwTeamServerId;
        oRequest.QwTeamId       = oInvite.QwTeamId;

        byte[]          pData   = new byte[1024];
        FxNet.NetStream pStream = new FxNet.NetStream(FxNet.NetStream.ENetStreamType.ENetStreamType_Write, pData, 1024);
        pStream.WriteString("GameProto.PlayerRequestLoginEnterTeam");
        byte[] pProto = new byte[oRequest.CalculateSize()];
        Google.Protobuf.CodedOutputStream oStream = new Google.Protobuf.CodedOutputStream(pProto);
        oRequest.WriteTo(oStream);
        pStream.WriteData(pProto, (uint)pProto.Length);

        m_pSession.Send(pData, 1024 - pStream.GetLeftLen());
    }
Esempio n. 32
0
    private void SaveAs(string name)
    {
        Environment.SetEnvironmentVariable("MONO_REFLECTION_SERIALIZER", "yes"); //So that iOS don't complain about protobuf's JITing
        Debug.Log("Saved : " + Application.persistentDataPath);
        using (FileStream file = File.Create(Application.persistentDataPath + "/" + name))
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            des.Key = Key;
            des.GenerateIV();

            file.Write(des.IV, 0, 8);
            //Debug.Log("Writing " + BitConverter.ToString(des.IV));

            using (var cryptoStream = new CryptoStream(file, des.CreateEncryptor(), CryptoStreamMode.Write))
            {
                using (Google.Protobuf.CodedOutputStream cos = new Google.Protobuf.CodedOutputStream(cryptoStream))
                {
                    local.WriteTo(cos);
                }
            }
        }
    }
Esempio n. 33
0
    public void NotIntoInviteTeam(object pParam)
    {
        GameProto.LoginNotifyPlayerInviteTeam oInvite = pParam as GameProto.LoginNotifyPlayerInviteTeam;
        if (oInvite == null)
        {
            SampleDebuger.LogError("NotIntoInviteTeam parse error!!!!");
            return;
        }

        GameProto.PlayerRequestLoginRefuseEnterTeam oRequest = new GameProto.PlayerRequestLoginRefuseEnterTeam();
        oRequest.QwPlayerId = oInvite.QwPlayerId;
        oRequest.SzReason   = "refused!!!";

        byte[]          pData   = new byte[1024];
        FxNet.NetStream pStream = new FxNet.NetStream(FxNet.NetStream.ENetStreamType.ENetStreamType_Write, pData, 1024);
        pStream.WriteString("GameProto.PlayerRequestLoginRefuseEnterTeam");
        byte[] pProto = new byte[oRequest.CalculateSize()];
        Google.Protobuf.CodedOutputStream oStream = new Google.Protobuf.CodedOutputStream(pProto);
        oRequest.WriteTo(oStream);
        pStream.WriteData(pProto, (uint)pProto.Length);

        m_pSession.Send(pData, 1024 - pStream.GetLeftLen());
    }
Esempio n. 34
0
    public void OnRoleData(string szData)
    {
        Debug.Log(szData);
        RoleDataRet oData = JsonUtility.FromJson <RoleDataRet>(szData);

        GameProto.PlayerRequestLogin oTest = new GameProto.PlayerRequestLogin();
        oTest.SzToken    = oData.token;
        oTest.QwPlayerId = oData.data.id;
        oTest.SzAvatar   = oData.data.avatar;
        oTest.SzNickName = oData.data.nick_name;
        oTest.DwSex      = oData.data.sex;
        oTest.DwBalance  = oData.data.balance;

        byte[]          pData   = new byte[2048];
        FxNet.NetStream pStream = new FxNet.NetStream(FxNet.NetStream.ENetStreamType.ENetStreamType_Write, pData, 2048);
        pStream.WriteString("GameProto.PlayerRequestLogin");
        byte[] pProto = new byte[oTest.CalculateSize()];
        Google.Protobuf.CodedOutputStream oStream = new Google.Protobuf.CodedOutputStream(pProto);
        oTest.WriteTo(oStream);
        pStream.WriteData(pProto, (uint)pProto.Length);

        m_pSession.Send(pData, 2048 - pStream.GetLeftLen());
    }
Esempio n. 35
0
        /// <summary>
        /// Applies basic AES encryption with the provided <paramref name="key">, with generated IV
        /// pasted in front of cipher text, before writing to the disk.
        /// </summary>
        /// <typeparam name="P">Your protobuf type here.</typeparam>
        public static MemoryStream ProtoToStream <P>(P save, byte[] key)
            where P : IMessage <P>, new()
        {
            MemoryStream             memStream = new MemoryStream();
            AesCryptoServiceProvider aes       = new AesCryptoServiceProvider();

            aes.Key = key;
            aes.GenerateIV();

            //Simply paste the initialization vector in front of cipher text.
            memStream.Write(aes.IV, 0, 16);

            //Debug.Log("Writing " + BitConverter.ToString(des.IV));

            using (var cryptoStream = new CryptoStream(memStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
            {
                using (Google.Protobuf.CodedOutputStream cos = new Google.Protobuf.CodedOutputStream(cryptoStream))
                {
                    save.WriteTo(cos);
                }
            }
            return(memStream);
        }
Esempio n. 36
0
        public void SetUp ()
        {
            // Create a request object and get the binary representation of it
            expectedRequest = new Request ("TestService", "ProcedureNoArgsNoReturn");
            using (var stream = new MemoryStream ()) {
                var codedStream = new CodedOutputStream (stream, true);
                codedStream.WriteInt32 (expectedRequest.ToProtobufMessage ().CalculateSize ());
                expectedRequest.ToProtobufMessage ().WriteTo (codedStream);
                codedStream.Flush ();
                requestBytes = stream.ToArray ();
            }

            // Create a response object and get the binary representation of it
            expectedResponse = new Response ();
            expectedResponse.Error = "SomeErrorMessage";
            expectedResponse.Time = 42;
            using (var stream = new MemoryStream ()) {
                var codedStream = new CodedOutputStream (stream, true);
                codedStream.WriteInt32 (expectedResponse.ToProtobufMessage ().CalculateSize ());
                expectedResponse.ToProtobufMessage ().WriteTo (codedStream);
                codedStream.Flush ();
                responseBytes = stream.ToArray ();
            }
        }
Esempio n. 37
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);
            }
        }
Esempio n. 38
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);
        }
Esempio n. 39
0
        public void DuplicateKeys_LastEntryWins()
        {
            var memoryStream = new MemoryStream();
            var output = new CodedOutputStream(memoryStream);

            var key = 10;
            var value1 = 20;
            var value2 = 30;

            // First entry
            output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited);
            output.WriteLength(4);
            output.WriteTag(1, WireFormat.WireType.Varint);
            output.WriteInt32(key);
            output.WriteTag(2, WireFormat.WireType.Varint);
            output.WriteInt32(value1);

            // Second entry - same key, different value
            output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited);
            output.WriteLength(4);
            output.WriteTag(1, WireFormat.WireType.Varint);
            output.WriteInt32(key);
            output.WriteTag(2, WireFormat.WireType.Varint);
            output.WriteInt32(value2);
            output.Flush();

            var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray());
            Assert.AreEqual(value2, parsed.MapInt32Int32[key]);
        }
Esempio n. 40
0
        public void MapFieldOrderIsIrrelevant()
        {
            var memoryStream = new MemoryStream();
            var output = new CodedOutputStream(memoryStream);

            output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited);

            var key = 10;
            var value = 20;

            // Each field can be represented in a single byte, with a single byte tag.
            // Total message size: 4 bytes.
            output.WriteLength(4);
            output.WriteTag(2, WireFormat.WireType.Varint);
            output.WriteInt32(value);
            output.WriteTag(1, WireFormat.WireType.Varint);
            output.WriteInt32(key);
            output.Flush();

            var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray());
            Assert.AreEqual(value, parsed.MapInt32Int32[key]);
        }
Esempio n. 41
0
        public void MapWithOnlyValue()
        {
            // Hand-craft the stream to contain a single entry with just a value.
            var memoryStream = new MemoryStream();
            var output = new CodedOutputStream(memoryStream);
            output.WriteTag(TestMap.MapInt32ForeignMessageFieldNumber, WireFormat.WireType.LengthDelimited);
            var nestedMessage = new ForeignMessage { C = 20 };
            // Size of the entry (tag, size written by WriteMessage, data written by WriteMessage)
            output.WriteLength(2 + nestedMessage.CalculateSize());
            output.WriteTag(2, WireFormat.WireType.LengthDelimited);
            output.WriteMessage(nestedMessage);
            output.Flush();

            var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray());
            Assert.AreEqual(nestedMessage, parsed.MapInt32ForeignMessage[0]);
        }
Esempio n. 42
0
        public void ExtraEndGroupThrows()
        {
            var message = SampleMessages.CreateFullTestAllTypes();
            var stream = new MemoryStream();
            var output = new CodedOutputStream(stream);

            output.WriteTag(TestAllTypes.SingleFixed32FieldNumber, WireFormat.WireType.Fixed32);
            output.WriteFixed32(123);
            output.WriteTag(100, WireFormat.WireType.EndGroup);

            output.Flush();

            stream.Position = 0;
            Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseFrom(stream));
        }
Esempio n. 43
0
        public void WriteString(string value)
        {
            int num = CodedOutputStream.smethod_0(CodedOutputStream.Utf8Encoding, value);

            while (true)
            {
IL_19C:
                uint arg_157_0 = 887200780u;
                while (true)
                {
                    uint num2;
                    switch ((num2 = (arg_157_0 ^ 428672786u)) % 14u)
                    {
                    case 0u:
                        this.position += num;
                        arg_157_0      = 576530064u;
                        continue;

                    case 1u:
                    {
                        byte[] value2 = CodedOutputStream.smethod_7(CodedOutputStream.Utf8Encoding, value);
                        arg_157_0 = 743111088u;
                        continue;
                    }

                    case 2u:
                        return;

                    case 3u:
                        arg_157_0 = (num2 * 3739319746u ^ 4238686882u);
                        continue;

                    case 4u:
                    {
                        int num3;
                        this.buffer[this.position + num3] = (byte)CodedOutputStream.smethod_5(value, num3);
                        num3++;
                        arg_157_0 = 1717125292u;
                        continue;
                    }

                    case 5u:
                        goto IL_19C;

                    case 6u:
                        CodedOutputStream.smethod_6(CodedOutputStream.Utf8Encoding, value, 0, CodedOutputStream.smethod_4(value), this.buffer, this.position);
                        arg_157_0 = 515054194u;
                        continue;

                    case 7u:
                        arg_157_0 = (((num == CodedOutputStream.smethod_4(value)) ? 1803967215u : 493454172u) ^ num2 * 2638214450u);
                        continue;

                    case 8u:
                        this.WriteLength(num);
                        arg_157_0 = (((this.limit - this.position < num) ? 125227529u : 1907771947u) ^ num2 * 1824877807u);
                        continue;

                    case 10u:
                    {
                        int num3;
                        arg_157_0 = ((num3 < num) ? 47776578u : 2121854163u);
                        continue;
                    }

                    case 11u:
                        arg_157_0 = (num2 * 1129511727u ^ 632133917u);
                        continue;

                    case 12u:
                    {
                        byte[] value2;
                        this.WriteRawBytes(value2);
                        arg_157_0 = (num2 * 286972294u ^ 188635011u);
                        continue;
                    }

                    case 13u:
                    {
                        int num3 = 0;
                        arg_157_0 = (num2 * 4058509186u ^ 2320074371u);
                        continue;
                    }
                    }
                    goto Block_4;
                }
            }
            Block_4 :;
        }
Esempio n. 44
0
 public void WriteSInt32(int value)
 {
     this.WriteRawVarint32(CodedOutputStream.EncodeZigZag32(value));
 }
Esempio n. 45
0
 public void WriteSInt64(long value)
 {
     this.WriteRawVarint64(CodedOutputStream.EncodeZigZag64(value));
 }
Esempio n. 46
0
 public static int ComputeInt64Size(long value)
 {
     return(CodedOutputStream.ComputeRawVarint64Size((ulong)value));
 }
 public static void Initialize(CodedOutputStream codedOutputStream, out WriteBufferHelper instance)
 {
     instance.bufferWriter      = null;
     instance.codedOutputStream = codedOutputStream;
 }
        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);
            }
        }
Esempio n. 49
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);
        }
Esempio n. 50
0
    private void ImportYarn(AssetImportContext ctx)
    {
        var    sourceText = File.ReadAllText(ctx.assetPath);
        string fileName   = System.IO.Path.GetFileNameWithoutExtension(ctx.assetPath);

        try
        {
            // Compile the source code into a compiled Yarn program (or
            // generate a parse error)
            compilationStatus = Compiler.CompileString(sourceText, fileName, out var compiledProgram, out var stringTable);

            // Create a container for storing the bytes
            var programContainer = ScriptableObject.CreateInstance <YarnProgram>();

            using (var memoryStream = new MemoryStream())
                using (var outputStream = new Google.Protobuf.CodedOutputStream(memoryStream))
                {
                    // Serialize the compiled program to memory
                    compiledProgram.WriteTo(outputStream);
                    outputStream.Flush();

                    byte[] compiledBytes = memoryStream.ToArray();

                    programContainer.compiledProgram = compiledBytes;

                    // Add this container to the imported asset; it will be
                    // what the user interacts with in Unity
                    ctx.AddObjectToAsset("Program", programContainer, YarnEditorUtility.GetYarnDocumentIconTexture());
                    ctx.SetMainObject(programContainer);

                    isSuccesfullyCompiled = true;

                    // var outPath = Path.ChangeExtension(ctx.assetPath, ".yarnc");
                    // File.WriteAllBytes(outPath, compiledBytes);
                }

            if (stringTable.Count > 0)
            {
                using (var memoryStream = new MemoryStream())
                    using (var textWriter = new StreamWriter(memoryStream)) {
                        // Generate the localised .csv file

                        // Use the invariant culture when writing the CSV
                        var configuration = new CsvHelper.Configuration.Configuration(
                            System.Globalization.CultureInfo.InvariantCulture
                            );

                        var csv = new CsvHelper.CsvWriter(
                            textWriter,   // write into this stream
                            configuration // use this configuration
                            );

                        var lines = stringTable.Select(x => new {
                            id         = x.Key,
                            text       = x.Value.text,
                            file       = x.Value.fileName,
                            node       = x.Value.nodeName,
                            lineNumber = x.Value.lineNumber
                        });

                        csv.WriteRecords(lines);

                        textWriter.Flush();

                        memoryStream.Position = 0;

                        using (var reader = new StreamReader(memoryStream)) {
                            var textAsset = new TextAsset(reader.ReadToEnd());
                            textAsset.name = $"{fileName} ({baseLanguageID})";

                            ctx.AddObjectToAsset("Strings", textAsset);

                            programContainer.baseLocalisationStringTable = textAsset;
                            baseLanguage = textAsset;
                            programContainer.localizations = localizations;
                        }

                        stringIDs = lines.Select(l => l.id).ToArray();
                    }
            }
        }
        catch (Yarn.Compiler.ParseException e)
        {
            isSuccesfullyCompiled   = false;
            compilationErrorMessage = e.Message;
            var message = FormatError(sourceText, compilationErrorMessage);
            Debug.LogError(message);
            return;
        }
    }
Esempio n. 51
0
        public void MapWithOnlyKey_MessageValue()
        {
            // Hand-craft the stream to contain a single entry with just a key.
            var memoryStream = new MemoryStream();
            var output = new CodedOutputStream(memoryStream);
            output.WriteTag(TestMap.MapInt32ForeignMessageFieldNumber, WireFormat.WireType.LengthDelimited);
            int key = 10;
            output.WriteLength(1 + CodedOutputStream.ComputeInt32Size(key));
            output.WriteTag(1, WireFormat.WireType.Varint);
            output.WriteInt32(key);
            output.Flush();

            var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray());
            Assert.AreEqual(new ForeignMessage(), parsed.MapInt32ForeignMessage[key]);
        }
Esempio n. 52
0
        public void WriteFloat(float value)
        {
            byte[] array = CodedOutputStream.smethod_3(value);
            while (true)
            {
IL_14C:
                uint arg_11B_0 = 1042150926u;
                while (true)
                {
                    uint num;
                    switch ((num = (arg_11B_0 ^ 1022855066u)) % 9u)
                    {
                    case 0u:
                    {
                        byte[] arg_ED_0 = this.buffer;
                        int    num2     = this.position;
                        this.position  = num2 + 1;
                        arg_ED_0[num2] = array[0];
                        byte[] arg_108_0 = this.buffer;
                        num2            = this.position;
                        this.position   = num2 + 1;
                        arg_108_0[num2] = array[1];
                        arg_11B_0       = (num * 458216763u ^ 884498142u);
                        continue;
                    }

                    case 1u:
                        return;

                    case 2u:
                        goto IL_14C;

                    case 4u:
                    {
                        byte[] arg_A8_0 = this.buffer;
                        int    num2     = this.position;
                        this.position  = num2 + 1;
                        arg_A8_0[num2] = array[2];
                        byte[] arg_C3_0 = this.buffer;
                        num2           = this.position;
                        this.position  = num2 + 1;
                        arg_C3_0[num2] = array[3];
                        arg_11B_0      = (num * 2383484455u ^ 688700656u);
                        continue;
                    }

                    case 5u:
                        this.WriteRawBytes(array, 0, 4);
                        arg_11B_0 = 1532374059u;
                        continue;

                    case 6u:
                        arg_11B_0 = ((this.limit - this.position < 4) ? 842348969u : 206970980u);
                        continue;

                    case 7u:
                        ByteArray.Reverse(array);
                        arg_11B_0 = (num * 1074657787u ^ 895898004u);
                        continue;

                    case 8u:
                        arg_11B_0 = ((BitConverter.IsLittleEndian ? 4106246718u : 3865512180u) ^ num * 3960773342u);
                        continue;
                    }
                    goto Block_3;
                }
            }
            Block_3 :;
        }
Esempio n. 53
0
 private static void TestNetwork()
 {
     var info = new NetMessage.PB_UserInfo();
     info.Guid = 1000L;
     info.Level = 5;
     info.NickName = "limotao";
     byte[] data = new byte[info.CalculateSize()];
     var buff = new Google.Protobuf.CodedOutputStream(data);
     info.WriteTo(buff);
     Console.ReadKey();
     string message = Convert.ToBase64String(data);
     //mSocketClient.Send(data, 0, data.Length);
     mSocketClient.Send(message);
     //Google.Protobuf.MessageParser<NetMessage.PB_UserInfo>()
     Console.ReadKey();
     mSocketClient.Close(0, "logout!");
 }
Esempio n. 54
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);
        }
Esempio n. 55
0
        public void MapIgnoresExtraFieldsWithinEntryMessages()
        {
            // Hand-craft the stream to contain a single entry with three fields
            var memoryStream = new MemoryStream();
            var output = new CodedOutputStream(memoryStream);

            output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited);

            var key = 10; // Field 1 
            var value = 20; // Field 2
            var extra = 30; // Field 3

            // Each field can be represented in a single byte, with a single byte tag.
            // Total message size: 6 bytes.
            output.WriteLength(6);
            output.WriteTag(1, WireFormat.WireType.Varint);
            output.WriteInt32(key);
            output.WriteTag(2, WireFormat.WireType.Varint);
            output.WriteInt32(value);
            output.WriteTag(3, WireFormat.WireType.Varint);
            output.WriteInt32(extra);
            output.Flush();

            var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray());
            Assert.AreEqual(value, parsed.MapInt32Int32[key]);
        }
Esempio n. 56
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);
        }
Esempio n. 57
0
        public void MapNonContiguousEntries()
        {
            var memoryStream = new MemoryStream();
            var output = new CodedOutputStream(memoryStream);

            // Message structure:
            // Entry for MapInt32Int32
            // Entry for MapStringString
            // Entry for MapInt32Int32

            // First entry
            var key1 = 10;
            var value1 = 20;
            output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited);
            output.WriteLength(4);
            output.WriteTag(1, WireFormat.WireType.Varint);
            output.WriteInt32(key1);
            output.WriteTag(2, WireFormat.WireType.Varint);
            output.WriteInt32(value1);

            // Second entry
            var key2 = "a";
            var value2 = "b";
            output.WriteTag(TestMap.MapStringStringFieldNumber, WireFormat.WireType.LengthDelimited);
            output.WriteLength(6); // 3 bytes per entry: tag, size, character
            output.WriteTag(1, WireFormat.WireType.LengthDelimited);
            output.WriteString(key2);
            output.WriteTag(2, WireFormat.WireType.LengthDelimited);
            output.WriteString(value2);

            // Third entry
            var key3 = 15;
            var value3 = 25;
            output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited);
            output.WriteLength(4);
            output.WriteTag(1, WireFormat.WireType.Varint);
            output.WriteInt32(key3);
            output.WriteTag(2, WireFormat.WireType.Varint);
            output.WriteInt32(value3);

            output.Flush();
            var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray());
            var expected = new TestMap
            {
                MapInt32Int32 = { { key1, value1 }, { key3, value3 } },
                MapStringString = { { key2, value2 } }
            };
            Assert.AreEqual(expected, parsed);
        }
Esempio n. 58
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());
        }
Esempio n. 59
0
        public void IgnoreUnknownFields_RealDataStillRead()
        {
            var message = SampleMessages.CreateFullTestAllTypes();
            var stream = new MemoryStream();
            var output = new CodedOutputStream(stream);
            var unusedFieldNumber = 23456;
            Assert.IsFalse(TestAllTypes.Descriptor.Fields.InDeclarationOrder().Select(x => x.FieldNumber).Contains(unusedFieldNumber));
            output.WriteTag(unusedFieldNumber, WireFormat.WireType.LengthDelimited);
            output.WriteString("ignore me");
            message.WriteTo(output);
            output.Flush();

            stream.Position = 0;
            var parsed = TestAllTypes.Parser.ParseFrom(stream);
            Assert.AreEqual(message, parsed);
        }
Esempio n. 60
0
 public void WriteTo(pb.CodedOutputStream output)
 {
     throw new System.NotImplementedException();
 }