ProtobufHelper.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. using System;
  2. using System.ComponentModel;
  3. using System.IO;
  4. using Microsoft.IO;
  5. using ProtoBuf;
  6. namespace ETModel
  7. {
  8. public static class ProtobufHelper
  9. {
  10. private static readonly RecyclableMemoryStreamManager recyclableMemoryStreamManager = new RecyclableMemoryStreamManager();
  11. public static byte[] ToBytes(object message)
  12. {
  13. using (MemoryStream ms = new MemoryStream())
  14. {
  15. Serializer.Serialize(ms, message);
  16. return ms.ToArray();
  17. }
  18. }
  19. public static T FromBytes<T>(byte[] bytes)
  20. {
  21. T t;
  22. using (MemoryStream ms = recyclableMemoryStreamManager.GetStream("protobuf", bytes, 0, bytes.Length))
  23. {
  24. t = Serializer.Deserialize<T>(ms);
  25. }
  26. ISupportInitialize iSupportInitialize = t as ISupportInitialize;
  27. if (iSupportInitialize == null)
  28. {
  29. return t;
  30. }
  31. iSupportInitialize.EndInit();
  32. return t;
  33. }
  34. public static T FromBytes<T>(byte[] bytes, int index, int length)
  35. {
  36. T t;
  37. using (MemoryStream ms = recyclableMemoryStreamManager.GetStream("protobuf", bytes, index, length))
  38. {
  39. t = Serializer.Deserialize<T>(ms);
  40. }
  41. ISupportInitialize iSupportInitialize = t as ISupportInitialize;
  42. if (iSupportInitialize == null)
  43. {
  44. return t;
  45. }
  46. iSupportInitialize.EndInit();
  47. return t;
  48. }
  49. public static object FromBytes(Type type, byte[] bytes)
  50. {
  51. object t;
  52. using (MemoryStream ms = recyclableMemoryStreamManager.GetStream("protobuf", bytes, 0, bytes.Length))
  53. {
  54. t = Serializer.NonGeneric.Deserialize(type, ms);
  55. }
  56. ISupportInitialize iSupportInitialize = t as ISupportInitialize;
  57. if (iSupportInitialize == null)
  58. {
  59. return t;
  60. }
  61. iSupportInitialize.EndInit();
  62. return t;
  63. }
  64. public static object FromBytes(Type type, byte[] bytes, int index, int length)
  65. {
  66. object t;
  67. using (MemoryStream ms = recyclableMemoryStreamManager.GetStream("protobuf", bytes, index, length))
  68. {
  69. t = Serializer.NonGeneric.Deserialize(type, ms);
  70. }
  71. ISupportInitialize iSupportInitialize = t as ISupportInitialize;
  72. if (iSupportInitialize == null)
  73. {
  74. return t;
  75. }
  76. iSupportInitialize.EndInit();
  77. return t;
  78. }
  79. public static object FromStream(Type type, Stream stream)
  80. {
  81. object t = Serializer.NonGeneric.Deserialize(type, stream);
  82. ISupportInitialize iSupportInitialize = t as ISupportInitialize;
  83. if (iSupportInitialize == null)
  84. {
  85. return t;
  86. }
  87. iSupportInitialize.EndInit();
  88. return t;
  89. }
  90. }
  91. }