using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Collections; namespace JD.Serialization { /// /// Base class for UAF serializers /// public abstract class Serializer { protected ITypeMap TypeMap { get; private set; } public SerializationFlags Flags { get; set; } public bool RethrowExceptions { get; set; } /// /// Whether to consider properties marked with a attribute. /// public bool IncludeSpecialFields { get; set; } /// /// Whether to serialize stringid as strings /// 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(); 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; } /// /// Property should serialize if its serialization flags are compatible with the Serializer. /// public bool ShouldSerialize(PropertyInfo propertyInfo) { return propertyInfo.IsSerializable(Flags); } protected IEnumerable SerializableFields(Type type) { return type.SerializableFields(Flags, IncludeSpecialFields); } protected bool IsCollection(Type type) { return typeof(IUAFCollection).IsAssignableFrom(type); } } }