using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using GameProto;
using Google.Protobuf;
///
/// ProtoBuf工具
///
public partial class ProtobufUtility
{
private const int BufferHead = 4;
///
/// 消息压入内存流。
///
///
///
public static void ToStream(object message, MemoryStream stream)
{
((IMessage)message).WriteTo(stream);
}
///
/// 消息压入内存流。
///
///
///
public static void ToStream(object message, Stream stream)
{
((IMessage)message).WriteTo(stream);
}
///
/// 消息压入内存流。
///
///
///
public static void ToStreamWithHead(CSPkg packet, MemoryStream stream)
{
byte[] data = packet.ToByteArray();
byte[] head = BitConverter.GetBytes(data.Length);
byte[] ret = head.Concat(data).ToArray();
stream.Write(ret);
((MemoryStream)stream).SetLength(BufferHead + data.Length);
}
///
/// 比特流解析。
///
///
///
///
///
///
public static object FromBytes(Type type, byte[] bytes, int index, int count)
{
object message = Activator.CreateInstance(type);
((IMessage)message).MergeFrom(bytes, index, count);
ISupportInitialize iSupportInitialize = message as ISupportInitialize;
if (iSupportInitialize == null)
{
return message;
}
iSupportInitialize.EndInit();
return message;
}
///
/// 比特流解析。
///
///
///
///
///
///
public static object FromBytes(object instance, byte[] bytes, int index, int count)
{
object message = instance;
((IMessage)message).MergeFrom(bytes, index, count);
ISupportInitialize iSupportInitialize = message as ISupportInitialize;
if (iSupportInitialize == null)
{
return message;
}
iSupportInitialize.EndInit();
return message;
}
///
/// 从内存流取出。
///
///
///
///
public static object FromStream(Type type, MemoryStream stream)
{
object message = Activator.CreateInstance(type);
((IMessage)message).MergeFrom(stream.GetBuffer(), (int)stream.Position, (int)stream.Length);
ISupportInitialize iSupportInitialize = message as ISupportInitialize;
if (iSupportInitialize == null)
{
return message;
}
iSupportInitialize.EndInit();
return message;
}
///
/// 从内存流取出。
///
///
///
///
public static object FromStream(object message, MemoryStream stream)
{
// TODO 这个message最好从池中获取,减少gc
((IMessage)message).MergeFrom(stream.GetBuffer(), (int)stream.Position, (int)stream.Length);
ISupportInitialize iSupportInitialize = message as ISupportInitialize;
if (iSupportInitialize == null)
{
return message;
}
iSupportInitialize.EndInit();
return message;
}
public static byte[] ToBytes(object message)
{
return ((IMessage)message).ToByteArray();
}
///
/// 序列化protobuf
///
///
///
public static byte[] Serialize(object message)
{
return ((IMessage)message).ToByteArray();
}
///
/// 反序列化protobuf
///
///
///
///
public static T Deserialize(byte[] dataBytes) where T : IMessage, new()
{
T msg = new T();
msg = (T)msg.Descriptor.Parser.ParseFrom(dataBytes);
return msg;
}
public static int GetHighOrder(int cmdMerge)
{
return cmdMerge >> 16;
}
public static int GetLowOrder(int cmdMerge)
{
return cmdMerge & 65535;
}
}