123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227 |
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Reflection;
- using TBL.CSharp.Serialization.Marshal.Context;
- namespace TBL.CSharp.Serialization.Marshal
- {
- /// <summary>
- /// Marshal 风格的序列化工具类
- /// <para>非线程安全的</para>
- /// </summary>
- public static class Marshal
- {
- /// <summary>
- /// 类型标记 Id
- /// </summary>
- public static class TypeId
- {
- /// <summary>
- /// 空引用
- /// </summary>
- public const byte Null = (byte)'0';
-
- /// <summary>
- /// 布尔值
- /// </summary>
- public const byte True = (byte)'T', False = (byte)'F';
-
- /// <summary>
- /// 符号及链接
- /// </summary>
- public const byte Symbol = (byte)':', SymbolLink = (byte)';';
- /// <summary>
- /// 对象及链接
- /// </summary>
- public const byte Object = (byte)'o', ObjectLink = (byte)'&';
- /// <summary>
- /// 对象字段
- /// </summary>
- public const byte ObjectFields = (byte)'*';
- /// <summary>
- /// 对象尾
- /// </summary>
- public const byte ObjectEnd = (byte)'!';
- /// <summary>
- /// 字符串
- /// </summary>
- public const byte String = (byte)'"';
- /// <summary>
- /// 元组
- /// </summary>
- public const byte Tuple = (byte)'t';
- /// <summary>
- /// 容器
- /// </summary>
- public const byte List = (byte)'[', Dictionary = (byte)'{';
- /// <summary>
- /// 数字类型
- /// </summary>
- public const byte
- Int8 = (byte)'b',
- Int8Unsigned = (byte)'B',
- Int16 = (byte)'s',
- Int16Unsigned = (byte)'S',
- Int32 = (byte)'i',
- Int32Unsigned = (byte)'I',
- Int64 = (byte)'l',
- Int64Unsigned = (byte)'L',
- Single = (byte)'r',
- Double = (byte)'R';
- /// <summary>
- /// <see cref="IStreamSerializable"/>
- /// </summary>
- public const byte SpecialStreamFull = (byte)'W', SpecialStream = (byte)'w';
- /// <summary>
- /// <see cref="IProxiedSerializable"/>
- /// </summary>
- public const byte SpecialProxiedFull = (byte)'P', SpecialProxied = (byte)'p';
- /// <summary>
- /// <see cref="IUnsafeSerializable"/>
- /// </summary>
- public const byte SpecialUnsafeFull = (byte)'K', SpecialUnsafe = (byte)'k';
- /// <summary>
- /// 额外支持
- /// </summary>
- public const byte ExternalSupport = (byte)'E';
- /// <summary>
- /// 某类型是否应该用构造方法初始化
- /// </summary>
- public static bool IsShouldInitialize(byte typeId) =>
- typeId == SpecialStreamFull ||
- typeId == SpecialProxiedFull ||
- typeId == SpecialUnsafeFull;
- }
- /// <summary>
- /// 默认的序列化上下文
- /// </summary>
- private static readonly MarshalContextBasic DefaultContext = new MarshalContextBasic();
- /// <summary>
- /// 类型字段缓存表
- /// </summary>
- private static readonly IDictionary<Type, FieldInfo[]> TypeFieldsCache = new Dictionary<Type, FieldInfo[]>();
- #region Type
- /// <summary>
- /// 元组类型表
- /// </summary>
- public static readonly ISet<Type> ValueTupleTypes = new HashSet<Type>()
- {
- typeof(ValueTuple<>),
- typeof(ValueTuple<,>),
- typeof(ValueTuple<,,>),
- typeof(ValueTuple<,,,>),
- typeof(ValueTuple<,,,,>),
- typeof(ValueTuple<,,,,,>),
- typeof(ValueTuple<,,,,,,>),
- typeof(ValueTuple<,,,,,,,>)
- };
-
- /// <summary>
- /// 是否为可序列化元组
- /// </summary>
- public static bool IsSerializableTuple(this Type type)
- {
- return type.IsGenericType && type.IsValueType &&
- ValueTupleTypes.Contains(type.GetGenericTypeDefinition());
- }
-
- /// <summary>
- /// 获取一个类型的实例字段
- /// </summary>
- public static IEnumerable<FieldInfo> GetInstanceFields(this Type type) =>
- type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
- /// <summary>
- /// 该字段是否不参与序列化
- /// </summary>
- public static bool IsNonSerialized(this Type type, FieldInfo field) =>
- field.IsNotSerialized || type.GetEvent(field.Name) != null;
- #endregion
-
- /// <summary>
- /// 获取一个类型的字段组
- /// <para>做过缓存处理,重复使用可以提高性能</para>
- /// </summary>
- public static FieldInfo[] GetTypeFields(Type type)
- {
- // 使用类型字段缓存加速处理
- if (!TypeFieldsCache.TryGetValue(type, out var fieldInfos))
- {
- TypeFieldsCache.Add(type,
- fieldInfos = type.GetInstanceFields()
- .Where(field => !type.IsNonSerialized(field)).ToArray());
- }
- return fieldInfos;
- }
- /// <summary>
- /// 获得字节序转换后的非托管值
- /// </summary>
- public static unsafe T EndianConvert<T>(this T value) where T : unmanaged
- {
- var size = sizeof(T);
- var data = (byte*) &value;
- var buffer = stackalloc byte[size];
- var lastIndex = size - 1;
- for (var i = 0; i < size; i++)
- {
- buffer[i] = data[lastIndex - i];
- }
- return *(T*) buffer;
- }
- /// <summary>
- /// 获得字节序转换后的非托管值
- /// </summary>
- /// <param name="value">要处理的值</param>
- /// <param name="isConvert">是否执行转换,如否则原样输出</param>
- public static unsafe T EndianConvert<T>(this T value, bool isConvert) where T : unmanaged =>
- isConvert ? value.EndianConvert() : value;
- /// <summary>
- /// 使用默认上下文序列化对象
- /// </summary>
- public static void Serialize(this IMarshalSerializer serializer,
- object self, Stream stream)
- {
- DefaultContext.Clear();
- serializer.Serialize(self, stream, DefaultContext);
- }
- /// <summary>
- /// 使用默认上下文和指定目标对象进行反序列化
- /// <para>序列化结果如不匹配,将不会对目标对象进行操作</para>
- /// </summary>
- public static object Deserialize(this IMarshalSerializer serializer,
- Stream stream, object target)
- {
- DefaultContext.Clear();
- return serializer.Deserialize(stream, DefaultContext, target);
- }
- /// <summary>
- /// 使用默认上下文进行反序列化
- /// </summary>
- public static object Deserialize(this IMarshalSerializer serializer,
- Stream stream) => Deserialize(serializer, stream, null);
- }
- }
|