104 lines
3.2 KiB
C#
104 lines
3.2 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Reflection;
|
|
using System.Collections;
|
|
|
|
namespace JD.Serialization
|
|
{
|
|
/// <summary>
|
|
/// Base class for UAF serializers
|
|
/// </summary>
|
|
public abstract class Serializer
|
|
{
|
|
protected ITypeMap TypeMap { get; private set; }
|
|
public SerializationFlags Flags { get; set; }
|
|
public bool RethrowExceptions { get; set; }
|
|
|
|
/// <summary>
|
|
/// Whether to consider properties marked with a <see cref="UafSerializableSpecialAttribute"/> attribute.
|
|
/// </summary>
|
|
public bool IncludeSpecialFields { get; set; }
|
|
|
|
/// <summary>
|
|
/// Whether to serialize stringid as strings
|
|
/// </summary>
|
|
public bool SerializeStringIdAsString { get; set; }
|
|
|
|
public Serializer(ITypeMap typeMap)
|
|
{
|
|
RethrowExceptions = true;
|
|
TypeMap = typeMap;
|
|
Flags = SerializationFlags.Default;
|
|
}
|
|
|
|
public object LoadObjectFromFile(string file, Type type = null, PropertyInfo property = null)
|
|
{
|
|
return LoadObjectFromFileImplementation(file, type);
|
|
}
|
|
|
|
public bool SaveObjectToFile(object obj, string file)
|
|
{
|
|
return SaveObjectToFileImplementation(obj, file);
|
|
}
|
|
|
|
protected abstract object LoadObjectFromFileImplementation(string file, Type type);
|
|
protected abstract bool SaveObjectToFileImplementation(object obj, string file);
|
|
|
|
protected static IList CreateNewList(Type t)
|
|
{
|
|
return (IList)Activator.CreateInstance(typeof(UAFList<>).MakeGenericType(t));
|
|
}
|
|
|
|
protected static int ColorF32ToU8(float val)
|
|
{
|
|
float res = val * 256.0f;
|
|
if (res > 255.0f)
|
|
res = 255.0f;
|
|
else if (res < 0.0f)
|
|
res = 0.0f;
|
|
|
|
return (int)res;
|
|
}
|
|
|
|
protected string FormatPropertyName(PropertyInfo property)
|
|
{
|
|
var originalNameAttribute = property.GetAttribute<OriginalPropertyNameAttribute>();
|
|
if (originalNameAttribute != null)
|
|
{
|
|
return originalNameAttribute.OriginalPropertyName;
|
|
}
|
|
return property.Name;
|
|
}
|
|
|
|
protected string FormatTypeName(Type type)
|
|
{
|
|
type = TypeMap.ToSerializationType(type);
|
|
|
|
string result = type.Name;
|
|
int indexOfTemplate = result.LastIndexOf("`");
|
|
|
|
if (indexOfTemplate >= 0)
|
|
result = result.Substring(0, indexOfTemplate);
|
|
return result;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Property should serialize if its serialization flags are compatible with the Serializer.
|
|
/// </summary>
|
|
public bool ShouldSerialize(PropertyInfo propertyInfo)
|
|
{
|
|
return propertyInfo.IsSerializable(Flags);
|
|
}
|
|
|
|
protected IEnumerable<PropertyInfo> SerializableFields(Type type)
|
|
{
|
|
return type.SerializableFields(Flags, IncludeSpecialFields);
|
|
}
|
|
|
|
protected bool IsCollection(Type type)
|
|
{
|
|
return typeof(IUAFCollection).IsAssignableFrom(type);
|
|
}
|
|
}
|
|
}
|