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
{
///
/// Marshal 风格的序列化工具类
/// 非线程安全的
///
public static class Marshal
{
///
/// 类型标记 Id
///
public static class TypeId
{
///
/// 空引用
///
public const byte Null = (byte)'0';
///
/// 布尔值
///
public const byte True = (byte)'T', False = (byte)'F';
///
/// 符号及链接
///
public const byte Symbol = (byte)':', SymbolLink = (byte)';';
///
/// 对象及链接
///
public const byte Object = (byte)'o', ObjectLink = (byte)'&';
///
/// 对象字段
///
public const byte ObjectFields = (byte)'*';
///
/// 对象尾
///
public const byte ObjectEnd = (byte)'!';
///
/// 字符串
///
public const byte String = (byte)'"';
///
/// 元组
///
public const byte Tuple = (byte)'t';
///
/// 容器
///
public const byte List = (byte)'[', Dictionary = (byte)'{';
///
/// 数字类型
///
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';
///
///
///
public const byte SpecialStreamFull = (byte)'W', SpecialStream = (byte)'w';
///
///
///
public const byte SpecialProxiedFull = (byte)'P', SpecialProxied = (byte)'p';
///
///
///
public const byte SpecialUnsafeFull = (byte)'K', SpecialUnsafe = (byte)'k';
///
/// 额外支持
///
public const byte ExternalSupport = (byte)'E';
///
/// 某类型是否应该用构造方法初始化
///
public static bool IsShouldInitialize(byte typeId) =>
typeId == SpecialStreamFull ||
typeId == SpecialProxiedFull ||
typeId == SpecialUnsafeFull;
}
///
/// 默认的序列化上下文
///
private static readonly MarshalContextBasic DefaultContext = new MarshalContextBasic();
///
/// 类型字段缓存表
///
private static readonly IDictionary TypeFieldsCache = new Dictionary();
#region Type
///
/// 元组类型表
///
public static readonly ISet ValueTupleTypes = new HashSet()
{
typeof(ValueTuple<>),
typeof(ValueTuple<,>),
typeof(ValueTuple<,,>),
typeof(ValueTuple<,,,>),
typeof(ValueTuple<,,,,>),
typeof(ValueTuple<,,,,,>),
typeof(ValueTuple<,,,,,,>),
typeof(ValueTuple<,,,,,,,>)
};
///
/// 是否为可序列化元组
///
public static bool IsSerializableTuple(this Type type)
{
return type.IsGenericType && type.IsValueType &&
ValueTupleTypes.Contains(type.GetGenericTypeDefinition());
}
///
/// 获取一个类型的实例字段
///
public static IEnumerable GetInstanceFields(this Type type) =>
type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
///
/// 该字段是否不参与序列化
///
public static bool IsNonSerialized(this Type type, FieldInfo field) =>
field.IsNotSerialized || type.GetEvent(field.Name) != null;
#endregion
///
/// 获取一个类型的字段组
/// 做过缓存处理,重复使用可以提高性能
///
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;
}
///
/// 获得字节序转换后的非托管值
///
public static unsafe T EndianConvert(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;
}
///
/// 获得字节序转换后的非托管值
///
/// 要处理的值
/// 是否执行转换,如否则原样输出
public static unsafe T EndianConvert(this T value, bool isConvert) where T : unmanaged =>
isConvert ? value.EndianConvert() : value;
///
/// 使用默认上下文序列化对象
///
public static void Serialize(this IMarshalSerializer serializer,
object self, Stream stream)
{
DefaultContext.Clear();
serializer.Serialize(self, stream, DefaultContext);
}
///
/// 使用默认上下文和指定目标对象进行反序列化
/// 序列化结果如不匹配,将不会对目标对象进行操作
///
public static object Deserialize(this IMarshalSerializer serializer,
Stream stream, object target)
{
DefaultContext.Clear();
return serializer.Deserialize(stream, DefaultContext, target);
}
///
/// 使用默认上下文进行反序列化
///
public static object Deserialize(this IMarshalSerializer serializer,
Stream stream) => Deserialize(serializer, stream, null);
}
}