Marshal.cs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Reflection;
  6. using TBL.CSharp.Serialization.Marshal.Context;
  7. namespace TBL.CSharp.Serialization.Marshal
  8. {
  9. /// <summary>
  10. /// Marshal 风格的序列化工具类
  11. /// <para>非线程安全的</para>
  12. /// </summary>
  13. public static class Marshal
  14. {
  15. /// <summary>
  16. /// 类型标记 Id
  17. /// </summary>
  18. public static class TypeId
  19. {
  20. /// <summary>
  21. /// 空引用
  22. /// </summary>
  23. public const byte Null = (byte)'0';
  24. /// <summary>
  25. /// 布尔值
  26. /// </summary>
  27. public const byte True = (byte)'T', False = (byte)'F';
  28. /// <summary>
  29. /// 符号及链接
  30. /// </summary>
  31. public const byte Symbol = (byte)':', SymbolLink = (byte)';';
  32. /// <summary>
  33. /// 对象及链接
  34. /// </summary>
  35. public const byte Object = (byte)'o', ObjectLink = (byte)'&';
  36. /// <summary>
  37. /// 对象字段
  38. /// </summary>
  39. public const byte ObjectFields = (byte)'*';
  40. /// <summary>
  41. /// 对象尾
  42. /// </summary>
  43. public const byte ObjectEnd = (byte)'!';
  44. /// <summary>
  45. /// 字符串
  46. /// </summary>
  47. public const byte String = (byte)'"';
  48. /// <summary>
  49. /// 元组
  50. /// </summary>
  51. public const byte Tuple = (byte)'t';
  52. /// <summary>
  53. /// 容器
  54. /// </summary>
  55. public const byte List = (byte)'[', Dictionary = (byte)'{';
  56. /// <summary>
  57. /// 数字类型
  58. /// </summary>
  59. public const byte
  60. Int8 = (byte)'b',
  61. Int8Unsigned = (byte)'B',
  62. Int16 = (byte)'s',
  63. Int16Unsigned = (byte)'S',
  64. Int32 = (byte)'i',
  65. Int32Unsigned = (byte)'I',
  66. Int64 = (byte)'l',
  67. Int64Unsigned = (byte)'L',
  68. Single = (byte)'r',
  69. Double = (byte)'R';
  70. /// <summary>
  71. /// <see cref="IStreamSerializable"/>
  72. /// </summary>
  73. public const byte SpecialStreamFull = (byte)'W', SpecialStream = (byte)'w';
  74. /// <summary>
  75. /// <see cref="IProxiedSerializable"/>
  76. /// </summary>
  77. public const byte SpecialProxiedFull = (byte)'P', SpecialProxied = (byte)'p';
  78. /// <summary>
  79. /// <see cref="IUnsafeSerializable"/>
  80. /// </summary>
  81. public const byte SpecialUnsafeFull = (byte)'K', SpecialUnsafe = (byte)'k';
  82. /// <summary>
  83. /// 额外支持
  84. /// </summary>
  85. public const byte ExternalSupport = (byte)'E';
  86. /// <summary>
  87. /// 某类型是否应该用构造方法初始化
  88. /// </summary>
  89. public static bool IsShouldInitialize(byte typeId) =>
  90. typeId == SpecialStreamFull ||
  91. typeId == SpecialProxiedFull ||
  92. typeId == SpecialUnsafeFull;
  93. }
  94. /// <summary>
  95. /// 默认的序列化上下文
  96. /// </summary>
  97. private static readonly MarshalContextBasic DefaultContext = new MarshalContextBasic();
  98. /// <summary>
  99. /// 类型字段缓存表
  100. /// </summary>
  101. private static readonly IDictionary<Type, FieldInfo[]> TypeFieldsCache = new Dictionary<Type, FieldInfo[]>();
  102. #region Type
  103. /// <summary>
  104. /// 元组类型表
  105. /// </summary>
  106. public static readonly ISet<Type> ValueTupleTypes = new HashSet<Type>()
  107. {
  108. typeof(ValueTuple<>),
  109. typeof(ValueTuple<,>),
  110. typeof(ValueTuple<,,>),
  111. typeof(ValueTuple<,,,>),
  112. typeof(ValueTuple<,,,,>),
  113. typeof(ValueTuple<,,,,,>),
  114. typeof(ValueTuple<,,,,,,>),
  115. typeof(ValueTuple<,,,,,,,>)
  116. };
  117. /// <summary>
  118. /// 是否为可序列化元组
  119. /// </summary>
  120. public static bool IsSerializableTuple(this Type type)
  121. {
  122. return type.IsGenericType && type.IsValueType &&
  123. ValueTupleTypes.Contains(type.GetGenericTypeDefinition());
  124. }
  125. /// <summary>
  126. /// 获取一个类型的实例字段
  127. /// </summary>
  128. public static IEnumerable<FieldInfo> GetInstanceFields(this Type type) =>
  129. type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
  130. /// <summary>
  131. /// 该字段是否不参与序列化
  132. /// </summary>
  133. public static bool IsNonSerialized(this Type type, FieldInfo field) =>
  134. field.IsNotSerialized || type.GetEvent(field.Name) != null;
  135. #endregion
  136. /// <summary>
  137. /// 获取一个类型的字段组
  138. /// <para>做过缓存处理,重复使用可以提高性能</para>
  139. /// </summary>
  140. public static FieldInfo[] GetTypeFields(Type type)
  141. {
  142. // 使用类型字段缓存加速处理
  143. if (!TypeFieldsCache.TryGetValue(type, out var fieldInfos))
  144. {
  145. TypeFieldsCache.Add(type,
  146. fieldInfos = type.GetInstanceFields()
  147. .Where(field => !type.IsNonSerialized(field)).ToArray());
  148. }
  149. return fieldInfos;
  150. }
  151. /// <summary>
  152. /// 获得字节序转换后的非托管值
  153. /// </summary>
  154. public static unsafe T EndianConvert<T>(this T value) where T : unmanaged
  155. {
  156. var size = sizeof(T);
  157. var data = (byte*) &value;
  158. var buffer = stackalloc byte[size];
  159. var lastIndex = size - 1;
  160. for (var i = 0; i < size; i++)
  161. {
  162. buffer[i] = data[lastIndex - i];
  163. }
  164. return *(T*) buffer;
  165. }
  166. /// <summary>
  167. /// 获得字节序转换后的非托管值
  168. /// </summary>
  169. /// <param name="value">要处理的值</param>
  170. /// <param name="isConvert">是否执行转换,如否则原样输出</param>
  171. public static unsafe T EndianConvert<T>(this T value, bool isConvert) where T : unmanaged =>
  172. isConvert ? value.EndianConvert() : value;
  173. /// <summary>
  174. /// 使用默认上下文序列化对象
  175. /// </summary>
  176. public static void Serialize(this IMarshalSerializer serializer,
  177. object self, Stream stream)
  178. {
  179. DefaultContext.Clear();
  180. serializer.Serialize(self, stream, DefaultContext);
  181. }
  182. /// <summary>
  183. /// 使用默认上下文和指定目标对象进行反序列化
  184. /// <para>序列化结果如不匹配,将不会对目标对象进行操作</para>
  185. /// </summary>
  186. public static object Deserialize(this IMarshalSerializer serializer,
  187. Stream stream, object target)
  188. {
  189. DefaultContext.Clear();
  190. return serializer.Deserialize(stream, DefaultContext, target);
  191. }
  192. /// <summary>
  193. /// 使用默认上下文进行反序列化
  194. /// </summary>
  195. public static object Deserialize(this IMarshalSerializer serializer,
  196. Stream stream) => Deserialize(serializer, stream, null);
  197. }
  198. }