ProtobufHelper.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using System;
  2. using System.IO;
  3. using ProtoBuf;
  4. namespace ET
  5. {
  6. public static class ProtobufHelper
  7. {
  8. static ProtobufHelper()
  9. {
  10. var types = Game.EventSystem.GetTypes();
  11. foreach (Type type in types)
  12. {
  13. if (type.GetCustomAttributes(typeof (ProtoContractAttribute), false).Length == 0)
  14. {
  15. continue;
  16. }
  17. if (!type.IsSubclassOf(typeof (ProtoObject)))
  18. {
  19. continue;
  20. }
  21. Serializer.NonGeneric.PrepareSerializer(type);
  22. }
  23. }
  24. public static void Init()
  25. {
  26. }
  27. public static object FromBytes(Type type, byte[] bytes, int index, int count)
  28. {
  29. using (MemoryStream stream = new MemoryStream(bytes, index, count))
  30. {
  31. return ProtoBuf.Serializer.Deserialize(type, stream);
  32. }
  33. }
  34. public static byte[] ToBytes(object message)
  35. {
  36. using (MemoryStream stream = new MemoryStream())
  37. {
  38. ProtoBuf.Serializer.Serialize(stream, message);
  39. return stream.ToArray();
  40. }
  41. }
  42. public static void ToStream(object message, MemoryStream stream)
  43. {
  44. ProtoBuf.Serializer.Serialize(stream, message);
  45. }
  46. public static object FromStream(Type type, MemoryStream stream)
  47. {
  48. return ProtoBuf.Serializer.Deserialize(type, stream);
  49. }
  50. }
  51. }