From 270428dc0e47c8f3651e02cb1d5be7d1b60eb55c Mon Sep 17 00:00:00 2001 From: spatialfree Date: Fri, 5 Jun 2020 12:17:40 -0700 Subject: [PATCH] removed an unused serialization library --- Assets/Source/Converters.meta | 8 - Assets/Source/Converters/Unity.meta | 8 - .../Unity/AnimationCurve_DirectConverter.cs | 47 - .../AnimationCurve_DirectConverter.cs.meta | 11 - .../Unity/Bounds_DirectConverter.cs | 42 - .../Unity/Bounds_DirectConverter.cs.meta | 11 - .../Unity/GUIStyleState_DirectConverter.cs | 42 - .../GUIStyleState_DirectConverter.cs.meta | 11 - .../Unity/GUIStyle_DirectConverter.cs | 162 ---- .../Unity/GUIStyle_DirectConverter.cs.meta | 11 - .../Unity/Gradient_DirectConverter.cs | 42 - .../Unity/Gradient_DirectConverter.cs.meta | 11 - .../Unity/Keyframe_DirectConverter.cs | 52 -- .../Unity/Keyframe_DirectConverter.cs.meta | 11 - .../Unity/LayerMask_DirectConverter.cs | 37 - .../Unity/LayerMask_DirectConverter.cs.meta | 11 - .../Unity/RectOffset_DirectConverter.cs | 52 -- .../Unity/RectOffset_DirectConverter.cs.meta | 11 - .../Converters/Unity/Rect_DirectConverter.cs | 52 -- .../Unity/Rect_DirectConverter.cs.meta | 11 - .../Converters/Unity/UnityEvent_Converter.cs | 42 - .../Unity/UnityEvent_Converter.cs.meta | 11 - Assets/Source/Converters/fsArrayConverter.cs | 80 -- .../Converters/fsArrayConverter.cs.meta | 11 - Assets/Source/Converters/fsDateConverter.cs | 96 -- .../Source/Converters/fsDateConverter.cs.meta | 11 - .../Converters/fsDictionaryConverter.cs | 171 ---- .../Converters/fsDictionaryConverter.cs.meta | 11 - Assets/Source/Converters/fsEnumConverter.cs | 105 --- .../Source/Converters/fsEnumConverter.cs.meta | 11 - .../Source/Converters/fsForwardConverter.cs | 86 -- .../Converters/fsForwardConverter.cs.meta | 11 - Assets/Source/Converters/fsGuidConverter.cs | 39 - .../Source/Converters/fsGuidConverter.cs.meta | 11 - .../Converters/fsIEnumerableConverter.cs | 145 --- .../Converters/fsIEnumerableConverter.cs.meta | 11 - .../Converters/fsKeyValuePairConverter.cs | 62 -- .../fsKeyValuePairConverter.cs.meta | 11 - .../Source/Converters/fsNullableConverter.cs | 29 - .../Converters/fsNullableConverter.cs.meta | 11 - .../Source/Converters/fsPrimitiveConverter.cs | 125 --- .../Converters/fsPrimitiveConverter.cs.meta | 11 - .../Source/Converters/fsReflectedConverter.cs | 93 -- .../Converters/fsReflectedConverter.cs.meta | 11 - Assets/Source/Converters/fsTypeConverter.cs | 44 - .../Source/Converters/fsTypeConverter.cs.meta | 11 - .../Converters/fsWeakReferenceConverter.cs | 65 -- .../fsWeakReferenceConverter.cs.meta | 11 - Assets/Source/Internal.meta | 8 - .../Internal/fsCyclicReferenceManager.cs | 90 -- .../Internal/fsCyclicReferenceManager.cs.meta | 11 - Assets/Source/Internal/fsOption.cs | 37 - Assets/Source/Internal/fsOption.cs.meta | 11 - .../Source/Internal/fsPortableReflection.cs | 400 --------- .../Internal/fsPortableReflection.cs.meta | 11 - Assets/Source/Internal/fsTypeExtensions.cs | 78 -- .../Source/Internal/fsTypeExtensions.cs.meta | 11 - Assets/Source/Internal/fsVersionManager.cs | 132 --- .../Source/Internal/fsVersionManager.cs.meta | 11 - Assets/Source/Internal/fsVersionedType.cs | 49 - .../Source/Internal/fsVersionedType.cs.meta | 11 - Assets/Source/Reflection.meta | 8 - Assets/Source/Reflection/fsMetaProperty.cs | 152 ---- .../Source/Reflection/fsMetaProperty.cs.meta | 11 - Assets/Source/Reflection/fsMetaType.cs | 336 ------- Assets/Source/Reflection/fsMetaType.cs.meta | 11 - .../Source/Reflection/fsReflectionUtility.cs | 49 - .../Reflection/fsReflectionUtility.cs.meta | 11 - Assets/Source/Reflection/fsTypeCache.cs | 167 ---- Assets/Source/Reflection/fsTypeCache.cs.meta | 11 - Assets/Source/fsAotCompilationManager.cs | 132 --- Assets/Source/fsAotCompilationManager.cs.meta | 11 - Assets/Source/fsBaseConverter.cs | 119 --- Assets/Source/fsBaseConverter.cs.meta | 11 - Assets/Source/fsConfig.cs | 94 -- Assets/Source/fsConfig.cs.meta | 11 - Assets/Source/fsContext.cs | 47 - Assets/Source/fsContext.cs.meta | 11 - Assets/Source/fsConverter.cs | 15 - Assets/Source/fsConverter.cs.meta | 11 - Assets/Source/fsConverterRegistrar.cs | 36 - Assets/Source/fsConverterRegistrar.cs.meta | 11 - Assets/Source/fsData.cs | 394 -------- Assets/Source/fsData.cs.meta | 11 - Assets/Source/fsDirectConverter.cs | 39 - Assets/Source/fsDirectConverter.cs.meta | 11 - Assets/Source/fsExceptions.cs | 16 - Assets/Source/fsExceptions.cs.meta | 11 - Assets/Source/fsISerializationCallbacks.cs | 97 -- .../Source/fsISerializationCallbacks.cs.meta | 11 - Assets/Source/fsIgnoreAttribute.cs | 10 - Assets/Source/fsIgnoreAttribute.cs.meta | 11 - Assets/Source/fsJsonParser.cs | 505 ----------- Assets/Source/fsJsonParser.cs.meta | 11 - Assets/Source/fsJsonPrinter.cs | 287 ------ Assets/Source/fsJsonPrinter.cs.meta | 11 - Assets/Source/fsMemberSerialization.cs | 21 - Assets/Source/fsMemberSerialization.cs.meta | 11 - Assets/Source/fsObjectAttribute.cs | 52 -- Assets/Source/fsObjectAttribute.cs.meta | 11 - Assets/Source/fsObjectProcessor.cs | 68 -- Assets/Source/fsObjectProcessor.cs.meta | 11 - Assets/Source/fsPropertyAttribute.cs | 28 - Assets/Source/fsPropertyAttribute.cs.meta | 11 - Assets/Source/fsResult.cs | 187 ---- Assets/Source/fsResult.cs.meta | 11 - Assets/Source/fsSerializer.cs | 843 ------------------ Assets/Source/fsSerializer.cs.meta | 11 - 108 files changed, 6794 deletions(-) delete mode 100644 Assets/Source/Converters.meta delete mode 100644 Assets/Source/Converters/Unity.meta delete mode 100644 Assets/Source/Converters/Unity/AnimationCurve_DirectConverter.cs delete mode 100644 Assets/Source/Converters/Unity/AnimationCurve_DirectConverter.cs.meta delete mode 100644 Assets/Source/Converters/Unity/Bounds_DirectConverter.cs delete mode 100644 Assets/Source/Converters/Unity/Bounds_DirectConverter.cs.meta delete mode 100644 Assets/Source/Converters/Unity/GUIStyleState_DirectConverter.cs delete mode 100644 Assets/Source/Converters/Unity/GUIStyleState_DirectConverter.cs.meta delete mode 100644 Assets/Source/Converters/Unity/GUIStyle_DirectConverter.cs delete mode 100644 Assets/Source/Converters/Unity/GUIStyle_DirectConverter.cs.meta delete mode 100644 Assets/Source/Converters/Unity/Gradient_DirectConverter.cs delete mode 100644 Assets/Source/Converters/Unity/Gradient_DirectConverter.cs.meta delete mode 100644 Assets/Source/Converters/Unity/Keyframe_DirectConverter.cs delete mode 100644 Assets/Source/Converters/Unity/Keyframe_DirectConverter.cs.meta delete mode 100644 Assets/Source/Converters/Unity/LayerMask_DirectConverter.cs delete mode 100644 Assets/Source/Converters/Unity/LayerMask_DirectConverter.cs.meta delete mode 100644 Assets/Source/Converters/Unity/RectOffset_DirectConverter.cs delete mode 100644 Assets/Source/Converters/Unity/RectOffset_DirectConverter.cs.meta delete mode 100644 Assets/Source/Converters/Unity/Rect_DirectConverter.cs delete mode 100644 Assets/Source/Converters/Unity/Rect_DirectConverter.cs.meta delete mode 100644 Assets/Source/Converters/Unity/UnityEvent_Converter.cs delete mode 100644 Assets/Source/Converters/Unity/UnityEvent_Converter.cs.meta delete mode 100644 Assets/Source/Converters/fsArrayConverter.cs delete mode 100644 Assets/Source/Converters/fsArrayConverter.cs.meta delete mode 100644 Assets/Source/Converters/fsDateConverter.cs delete mode 100644 Assets/Source/Converters/fsDateConverter.cs.meta delete mode 100644 Assets/Source/Converters/fsDictionaryConverter.cs delete mode 100644 Assets/Source/Converters/fsDictionaryConverter.cs.meta delete mode 100644 Assets/Source/Converters/fsEnumConverter.cs delete mode 100644 Assets/Source/Converters/fsEnumConverter.cs.meta delete mode 100644 Assets/Source/Converters/fsForwardConverter.cs delete mode 100644 Assets/Source/Converters/fsForwardConverter.cs.meta delete mode 100644 Assets/Source/Converters/fsGuidConverter.cs delete mode 100644 Assets/Source/Converters/fsGuidConverter.cs.meta delete mode 100644 Assets/Source/Converters/fsIEnumerableConverter.cs delete mode 100644 Assets/Source/Converters/fsIEnumerableConverter.cs.meta delete mode 100644 Assets/Source/Converters/fsKeyValuePairConverter.cs delete mode 100644 Assets/Source/Converters/fsKeyValuePairConverter.cs.meta delete mode 100644 Assets/Source/Converters/fsNullableConverter.cs delete mode 100644 Assets/Source/Converters/fsNullableConverter.cs.meta delete mode 100644 Assets/Source/Converters/fsPrimitiveConverter.cs delete mode 100644 Assets/Source/Converters/fsPrimitiveConverter.cs.meta delete mode 100644 Assets/Source/Converters/fsReflectedConverter.cs delete mode 100644 Assets/Source/Converters/fsReflectedConverter.cs.meta delete mode 100644 Assets/Source/Converters/fsTypeConverter.cs delete mode 100644 Assets/Source/Converters/fsTypeConverter.cs.meta delete mode 100644 Assets/Source/Converters/fsWeakReferenceConverter.cs delete mode 100644 Assets/Source/Converters/fsWeakReferenceConverter.cs.meta delete mode 100644 Assets/Source/Internal.meta delete mode 100644 Assets/Source/Internal/fsCyclicReferenceManager.cs delete mode 100644 Assets/Source/Internal/fsCyclicReferenceManager.cs.meta delete mode 100644 Assets/Source/Internal/fsOption.cs delete mode 100644 Assets/Source/Internal/fsOption.cs.meta delete mode 100644 Assets/Source/Internal/fsPortableReflection.cs delete mode 100644 Assets/Source/Internal/fsPortableReflection.cs.meta delete mode 100644 Assets/Source/Internal/fsTypeExtensions.cs delete mode 100644 Assets/Source/Internal/fsTypeExtensions.cs.meta delete mode 100644 Assets/Source/Internal/fsVersionManager.cs delete mode 100644 Assets/Source/Internal/fsVersionManager.cs.meta delete mode 100644 Assets/Source/Internal/fsVersionedType.cs delete mode 100644 Assets/Source/Internal/fsVersionedType.cs.meta delete mode 100644 Assets/Source/Reflection.meta delete mode 100644 Assets/Source/Reflection/fsMetaProperty.cs delete mode 100644 Assets/Source/Reflection/fsMetaProperty.cs.meta delete mode 100644 Assets/Source/Reflection/fsMetaType.cs delete mode 100644 Assets/Source/Reflection/fsMetaType.cs.meta delete mode 100644 Assets/Source/Reflection/fsReflectionUtility.cs delete mode 100644 Assets/Source/Reflection/fsReflectionUtility.cs.meta delete mode 100644 Assets/Source/Reflection/fsTypeCache.cs delete mode 100644 Assets/Source/Reflection/fsTypeCache.cs.meta delete mode 100644 Assets/Source/fsAotCompilationManager.cs delete mode 100644 Assets/Source/fsAotCompilationManager.cs.meta delete mode 100644 Assets/Source/fsBaseConverter.cs delete mode 100644 Assets/Source/fsBaseConverter.cs.meta delete mode 100644 Assets/Source/fsConfig.cs delete mode 100644 Assets/Source/fsConfig.cs.meta delete mode 100644 Assets/Source/fsContext.cs delete mode 100644 Assets/Source/fsContext.cs.meta delete mode 100644 Assets/Source/fsConverter.cs delete mode 100644 Assets/Source/fsConverter.cs.meta delete mode 100644 Assets/Source/fsConverterRegistrar.cs delete mode 100644 Assets/Source/fsConverterRegistrar.cs.meta delete mode 100644 Assets/Source/fsData.cs delete mode 100644 Assets/Source/fsData.cs.meta delete mode 100644 Assets/Source/fsDirectConverter.cs delete mode 100644 Assets/Source/fsDirectConverter.cs.meta delete mode 100644 Assets/Source/fsExceptions.cs delete mode 100644 Assets/Source/fsExceptions.cs.meta delete mode 100644 Assets/Source/fsISerializationCallbacks.cs delete mode 100644 Assets/Source/fsISerializationCallbacks.cs.meta delete mode 100644 Assets/Source/fsIgnoreAttribute.cs delete mode 100644 Assets/Source/fsIgnoreAttribute.cs.meta delete mode 100644 Assets/Source/fsJsonParser.cs delete mode 100644 Assets/Source/fsJsonParser.cs.meta delete mode 100644 Assets/Source/fsJsonPrinter.cs delete mode 100644 Assets/Source/fsJsonPrinter.cs.meta delete mode 100644 Assets/Source/fsMemberSerialization.cs delete mode 100644 Assets/Source/fsMemberSerialization.cs.meta delete mode 100644 Assets/Source/fsObjectAttribute.cs delete mode 100644 Assets/Source/fsObjectAttribute.cs.meta delete mode 100644 Assets/Source/fsObjectProcessor.cs delete mode 100644 Assets/Source/fsObjectProcessor.cs.meta delete mode 100644 Assets/Source/fsPropertyAttribute.cs delete mode 100644 Assets/Source/fsPropertyAttribute.cs.meta delete mode 100644 Assets/Source/fsResult.cs delete mode 100644 Assets/Source/fsResult.cs.meta delete mode 100644 Assets/Source/fsSerializer.cs delete mode 100644 Assets/Source/fsSerializer.cs.meta diff --git a/Assets/Source/Converters.meta b/Assets/Source/Converters.meta deleted file mode 100644 index ba313d8..0000000 --- a/Assets/Source/Converters.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 1b1ed4807593b5042b522b04c705a36c -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/Converters/Unity.meta b/Assets/Source/Converters/Unity.meta deleted file mode 100644 index 3e993dd..0000000 --- a/Assets/Source/Converters/Unity.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: c9b1df9bbef7286479721c8d6f6f5a72 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/Converters/Unity/AnimationCurve_DirectConverter.cs b/Assets/Source/Converters/Unity/AnimationCurve_DirectConverter.cs deleted file mode 100644 index 76409c2..0000000 --- a/Assets/Source/Converters/Unity/AnimationCurve_DirectConverter.cs +++ /dev/null @@ -1,47 +0,0 @@ -#if !NO_UNITY -using System; -using System.Collections.Generic; -using UnityEngine; - -namespace FullSerializer { - partial class fsConverterRegistrar { - public static Internal.DirectConverters.AnimationCurve_DirectConverter Register_AnimationCurve_DirectConverter; - } -} - -namespace FullSerializer.Internal.DirectConverters { - public class AnimationCurve_DirectConverter : fsDirectConverter { - protected override fsResult DoSerialize(AnimationCurve model, Dictionary serialized) { - var result = fsResult.Success; - - result += SerializeMember(serialized, null, "keys", model.keys); - result += SerializeMember(serialized, null, "preWrapMode", model.preWrapMode); - result += SerializeMember(serialized, null, "postWrapMode", model.postWrapMode); - - return result; - } - - protected override fsResult DoDeserialize(Dictionary data, ref AnimationCurve model) { - var result = fsResult.Success; - - var t0 = model.keys; - result += DeserializeMember(data, null, "keys", out t0); - model.keys = t0; - - var t1 = model.preWrapMode; - result += DeserializeMember(data, null, "preWrapMode", out t1); - model.preWrapMode = t1; - - var t2 = model.postWrapMode; - result += DeserializeMember(data, null, "postWrapMode", out t2); - model.postWrapMode = t2; - - return result; - } - - public override object CreateInstance(fsData data, Type storageType) { - return new AnimationCurve(); - } - } -} -#endif \ No newline at end of file diff --git a/Assets/Source/Converters/Unity/AnimationCurve_DirectConverter.cs.meta b/Assets/Source/Converters/Unity/AnimationCurve_DirectConverter.cs.meta deleted file mode 100644 index c8dc1fe..0000000 --- a/Assets/Source/Converters/Unity/AnimationCurve_DirectConverter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 2476f8660fdb77f4cbe97b4c53e760fd -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/Converters/Unity/Bounds_DirectConverter.cs b/Assets/Source/Converters/Unity/Bounds_DirectConverter.cs deleted file mode 100644 index 134b5d4..0000000 --- a/Assets/Source/Converters/Unity/Bounds_DirectConverter.cs +++ /dev/null @@ -1,42 +0,0 @@ -#if !NO_UNITY -using System; -using System.Collections.Generic; -using UnityEngine; - -namespace FullSerializer { - partial class fsConverterRegistrar { - public static Internal.DirectConverters.Bounds_DirectConverter Register_Bounds_DirectConverter; - } -} - -namespace FullSerializer.Internal.DirectConverters { - public class Bounds_DirectConverter : fsDirectConverter { - protected override fsResult DoSerialize(Bounds model, Dictionary serialized) { - var result = fsResult.Success; - - result += SerializeMember(serialized, null, "center", model.center); - result += SerializeMember(serialized, null, "size", model.size); - - return result; - } - - protected override fsResult DoDeserialize(Dictionary data, ref Bounds model) { - var result = fsResult.Success; - - var t0 = model.center; - result += DeserializeMember(data, null, "center", out t0); - model.center = t0; - - var t1 = model.size; - result += DeserializeMember(data, null, "size", out t1); - model.size = t1; - - return result; - } - - public override object CreateInstance(fsData data, Type storageType) { - return new Bounds(); - } - } -} -#endif \ No newline at end of file diff --git a/Assets/Source/Converters/Unity/Bounds_DirectConverter.cs.meta b/Assets/Source/Converters/Unity/Bounds_DirectConverter.cs.meta deleted file mode 100644 index 82f81e1..0000000 --- a/Assets/Source/Converters/Unity/Bounds_DirectConverter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 891b0567146e2334b880d3a41f3c26f1 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/Converters/Unity/GUIStyleState_DirectConverter.cs b/Assets/Source/Converters/Unity/GUIStyleState_DirectConverter.cs deleted file mode 100644 index 0100d49..0000000 --- a/Assets/Source/Converters/Unity/GUIStyleState_DirectConverter.cs +++ /dev/null @@ -1,42 +0,0 @@ -#if !NO_UNITY -using System; -using System.Collections.Generic; -using UnityEngine; - -namespace FullSerializer { - partial class fsConverterRegistrar { - public static Internal.DirectConverters.GUIStyleState_DirectConverter Register_GUIStyleState_DirectConverter; - } -} - -namespace FullSerializer.Internal.DirectConverters { - public class GUIStyleState_DirectConverter : fsDirectConverter { - protected override fsResult DoSerialize(GUIStyleState model, Dictionary serialized) { - var result = fsResult.Success; - - result += SerializeMember(serialized, null, "background", model.background); - result += SerializeMember(serialized, null, "textColor", model.textColor); - - return result; - } - - protected override fsResult DoDeserialize(Dictionary data, ref GUIStyleState model) { - var result = fsResult.Success; - - var t0 = model.background; - result += DeserializeMember(data, null, "background", out t0); - model.background = t0; - - var t2 = model.textColor; - result += DeserializeMember(data, null, "textColor", out t2); - model.textColor = t2; - - return result; - } - - public override object CreateInstance(fsData data, Type storageType) { - return new GUIStyleState(); - } - } -} -#endif \ No newline at end of file diff --git a/Assets/Source/Converters/Unity/GUIStyleState_DirectConverter.cs.meta b/Assets/Source/Converters/Unity/GUIStyleState_DirectConverter.cs.meta deleted file mode 100644 index 9d7405d..0000000 --- a/Assets/Source/Converters/Unity/GUIStyleState_DirectConverter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: dd89cb6fc1667534fb89879ab916ad17 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/Converters/Unity/GUIStyle_DirectConverter.cs b/Assets/Source/Converters/Unity/GUIStyle_DirectConverter.cs deleted file mode 100644 index cfb3b41..0000000 --- a/Assets/Source/Converters/Unity/GUIStyle_DirectConverter.cs +++ /dev/null @@ -1,162 +0,0 @@ -#if !NO_UNITY -using System; -using System.Collections.Generic; -using UnityEngine; - -namespace FullSerializer { - partial class fsConverterRegistrar { - public static Internal.DirectConverters.GUIStyle_DirectConverter Register_GUIStyle_DirectConverter; - } -} - -namespace FullSerializer.Internal.DirectConverters { - public class GUIStyle_DirectConverter : fsDirectConverter { - protected override fsResult DoSerialize(GUIStyle model, Dictionary serialized) { - var result = fsResult.Success; - - result += SerializeMember(serialized, null, "active", model.active); - result += SerializeMember(serialized, null, "alignment", model.alignment); - result += SerializeMember(serialized, null, "border", model.border); - result += SerializeMember(serialized, null, "clipping", model.clipping); - result += SerializeMember(serialized, null, "contentOffset", model.contentOffset); - result += SerializeMember(serialized, null, "fixedHeight", model.fixedHeight); - result += SerializeMember(serialized, null, "fixedWidth", model.fixedWidth); - result += SerializeMember(serialized, null, "focused", model.focused); - result += SerializeMember(serialized, null, "font", model.font); - result += SerializeMember(serialized, null, "fontSize", model.fontSize); - result += SerializeMember(serialized, null, "fontStyle", model.fontStyle); - result += SerializeMember(serialized, null, "hover", model.hover); - result += SerializeMember(serialized, null, "imagePosition", model.imagePosition); - result += SerializeMember(serialized, null, "margin", model.margin); - result += SerializeMember(serialized, null, "name", model.name); - result += SerializeMember(serialized, null, "normal", model.normal); - result += SerializeMember(serialized, null, "onActive", model.onActive); - result += SerializeMember(serialized, null, "onFocused", model.onFocused); - result += SerializeMember(serialized, null, "onHover", model.onHover); - result += SerializeMember(serialized, null, "onNormal", model.onNormal); - result += SerializeMember(serialized, null, "overflow", model.overflow); - result += SerializeMember(serialized, null, "padding", model.padding); - result += SerializeMember(serialized, null, "richText", model.richText); - result += SerializeMember(serialized, null, "stretchHeight", model.stretchHeight); - result += SerializeMember(serialized, null, "stretchWidth", model.stretchWidth); - result += SerializeMember(serialized, null, "wordWrap", model.wordWrap); - - return result; - } - - protected override fsResult DoDeserialize(Dictionary data, ref GUIStyle model) { - var result = fsResult.Success; - - var t0 = model.active; - result += DeserializeMember(data, null, "active", out t0); - model.active = t0; - - var t2 = model.alignment; - result += DeserializeMember(data, null, "alignment", out t2); - model.alignment = t2; - - var t3 = model.border; - result += DeserializeMember(data, null, "border", out t3); - model.border = t3; - - var t4 = model.clipping; - result += DeserializeMember(data, null, "clipping", out t4); - model.clipping = t4; - - var t5 = model.contentOffset; - result += DeserializeMember(data, null, "contentOffset", out t5); - model.contentOffset = t5; - - var t6 = model.fixedHeight; - result += DeserializeMember(data, null, "fixedHeight", out t6); - model.fixedHeight = t6; - - var t7 = model.fixedWidth; - result += DeserializeMember(data, null, "fixedWidth", out t7); - model.fixedWidth = t7; - - var t8 = model.focused; - result += DeserializeMember(data, null, "focused", out t8); - model.focused = t8; - - var t9 = model.font; - result += DeserializeMember(data, null, "font", out t9); - model.font = t9; - - var t10 = model.fontSize; - result += DeserializeMember(data, null, "fontSize", out t10); - model.fontSize = t10; - - var t11 = model.fontStyle; - result += DeserializeMember(data, null, "fontStyle", out t11); - model.fontStyle = t11; - - var t12 = model.hover; - result += DeserializeMember(data, null, "hover", out t12); - model.hover = t12; - - var t13 = model.imagePosition; - result += DeserializeMember(data, null, "imagePosition", out t13); - model.imagePosition = t13; - - var t16 = model.margin; - result += DeserializeMember(data, null, "margin", out t16); - model.margin = t16; - - var t17 = model.name; - result += DeserializeMember(data, null, "name", out t17); - model.name = t17; - - var t18 = model.normal; - result += DeserializeMember(data, null, "normal", out t18); - model.normal = t18; - - var t19 = model.onActive; - result += DeserializeMember(data, null, "onActive", out t19); - model.onActive = t19; - - var t20 = model.onFocused; - result += DeserializeMember(data, null, "onFocused", out t20); - model.onFocused = t20; - - var t21 = model.onHover; - result += DeserializeMember(data, null, "onHover", out t21); - model.onHover = t21; - - var t22 = model.onNormal; - result += DeserializeMember(data, null, "onNormal", out t22); - model.onNormal = t22; - - var t23 = model.overflow; - result += DeserializeMember(data, null, "overflow", out t23); - model.overflow = t23; - - var t24 = model.padding; - result += DeserializeMember(data, null, "padding", out t24); - model.padding = t24; - - var t25 = model.richText; - result += DeserializeMember(data, null, "richText", out t25); - model.richText = t25; - - var t26 = model.stretchHeight; - result += DeserializeMember(data, null, "stretchHeight", out t26); - model.stretchHeight = t26; - - var t27 = model.stretchWidth; - result += DeserializeMember(data, null, "stretchWidth", out t27); - model.stretchWidth = t27; - - var t28 = model.wordWrap; - result += DeserializeMember(data, null, "wordWrap", out t28); - model.wordWrap = t28; - - return result; - } - - public override object CreateInstance(fsData data, Type storageType) { - return new GUIStyle(); - } - } -} -#endif \ No newline at end of file diff --git a/Assets/Source/Converters/Unity/GUIStyle_DirectConverter.cs.meta b/Assets/Source/Converters/Unity/GUIStyle_DirectConverter.cs.meta deleted file mode 100644 index 3354ca5..0000000 --- a/Assets/Source/Converters/Unity/GUIStyle_DirectConverter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 49fa198b11ff8fe4d96d54ab58be73fd -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/Converters/Unity/Gradient_DirectConverter.cs b/Assets/Source/Converters/Unity/Gradient_DirectConverter.cs deleted file mode 100644 index 94742a4..0000000 --- a/Assets/Source/Converters/Unity/Gradient_DirectConverter.cs +++ /dev/null @@ -1,42 +0,0 @@ -#if !NO_UNITY -using System; -using System.Collections.Generic; -using UnityEngine; - -namespace FullSerializer { - partial class fsConverterRegistrar { - public static Internal.DirectConverters.Gradient_DirectConverter Register_Gradient_DirectConverter; - } -} - -namespace FullSerializer.Internal.DirectConverters { - public class Gradient_DirectConverter : fsDirectConverter { - protected override fsResult DoSerialize(Gradient model, Dictionary serialized) { - var result = fsResult.Success; - - result += SerializeMember(serialized, null, "alphaKeys", model.alphaKeys); - result += SerializeMember(serialized, null, "colorKeys", model.colorKeys); - - return result; - } - - protected override fsResult DoDeserialize(Dictionary data, ref Gradient model) { - var result = fsResult.Success; - - var t0 = model.alphaKeys; - result += DeserializeMember(data, null, "alphaKeys", out t0); - model.alphaKeys = t0; - - var t1 = model.colorKeys; - result += DeserializeMember(data, null, "colorKeys", out t1); - model.colorKeys = t1; - - return result; - } - - public override object CreateInstance(fsData data, Type storageType) { - return new Gradient(); - } - } -} -#endif \ No newline at end of file diff --git a/Assets/Source/Converters/Unity/Gradient_DirectConverter.cs.meta b/Assets/Source/Converters/Unity/Gradient_DirectConverter.cs.meta deleted file mode 100644 index afd0fb5..0000000 --- a/Assets/Source/Converters/Unity/Gradient_DirectConverter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: bdeec5510c4eaad4fa61e836562c3d45 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/Converters/Unity/Keyframe_DirectConverter.cs b/Assets/Source/Converters/Unity/Keyframe_DirectConverter.cs deleted file mode 100644 index 34b3b58..0000000 --- a/Assets/Source/Converters/Unity/Keyframe_DirectConverter.cs +++ /dev/null @@ -1,52 +0,0 @@ -#if !NO_UNITY -using System; -using System.Collections.Generic; -using UnityEngine; - -namespace FullSerializer { - partial class fsConverterRegistrar { - public static Internal.DirectConverters.Keyframe_DirectConverter Register_Keyframe_DirectConverter; - } -} - -namespace FullSerializer.Internal.DirectConverters { - public class Keyframe_DirectConverter : fsDirectConverter { - protected override fsResult DoSerialize(Keyframe model, Dictionary serialized) { - var result = fsResult.Success; - - result += SerializeMember(serialized, null, "time", model.time); - result += SerializeMember(serialized, null, "value", model.value); - result += SerializeMember(serialized, null, "inTangent", model.inTangent); - result += SerializeMember(serialized, null, "outTangent", model.outTangent); - - return result; - } - - protected override fsResult DoDeserialize(Dictionary data, ref Keyframe model) { - var result = fsResult.Success; - - var t0 = model.time; - result += DeserializeMember(data, null, "time", out t0); - model.time = t0; - - var t1 = model.value; - result += DeserializeMember(data, null, "value", out t1); - model.value = t1; - - var t3 = model.inTangent; - result += DeserializeMember(data, null, "inTangent", out t3); - model.inTangent = t3; - - var t4 = model.outTangent; - result += DeserializeMember(data, null, "outTangent", out t4); - model.outTangent = t4; - - return result; - } - - public override object CreateInstance(fsData data, Type storageType) { - return new Keyframe(); - } - } -} -#endif \ No newline at end of file diff --git a/Assets/Source/Converters/Unity/Keyframe_DirectConverter.cs.meta b/Assets/Source/Converters/Unity/Keyframe_DirectConverter.cs.meta deleted file mode 100644 index a7ff1a0..0000000 --- a/Assets/Source/Converters/Unity/Keyframe_DirectConverter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: e3ff33c51e3301d44b8d70f16d1eb169 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/Converters/Unity/LayerMask_DirectConverter.cs b/Assets/Source/Converters/Unity/LayerMask_DirectConverter.cs deleted file mode 100644 index 7dd794b..0000000 --- a/Assets/Source/Converters/Unity/LayerMask_DirectConverter.cs +++ /dev/null @@ -1,37 +0,0 @@ -#if !NO_UNITY -using System; -using System.Collections.Generic; -using UnityEngine; - -namespace FullSerializer { - partial class fsConverterRegistrar { - public static Internal.DirectConverters.LayerMask_DirectConverter Register_LayerMask_DirectConverter; - } -} - -namespace FullSerializer.Internal.DirectConverters { - public class LayerMask_DirectConverter : fsDirectConverter { - protected override fsResult DoSerialize(LayerMask model, Dictionary serialized) { - var result = fsResult.Success; - - result += SerializeMember(serialized, null, "value", model.value); - - return result; - } - - protected override fsResult DoDeserialize(Dictionary data, ref LayerMask model) { - var result = fsResult.Success; - - var t0 = model.value; - result += DeserializeMember(data, null, "value", out t0); - model.value = t0; - - return result; - } - - public override object CreateInstance(fsData data, Type storageType) { - return new LayerMask(); - } - } -} -#endif \ No newline at end of file diff --git a/Assets/Source/Converters/Unity/LayerMask_DirectConverter.cs.meta b/Assets/Source/Converters/Unity/LayerMask_DirectConverter.cs.meta deleted file mode 100644 index 725c35b..0000000 --- a/Assets/Source/Converters/Unity/LayerMask_DirectConverter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 6ba002c4a5beab644b8b40ecc769956c -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/Converters/Unity/RectOffset_DirectConverter.cs b/Assets/Source/Converters/Unity/RectOffset_DirectConverter.cs deleted file mode 100644 index cb3e246..0000000 --- a/Assets/Source/Converters/Unity/RectOffset_DirectConverter.cs +++ /dev/null @@ -1,52 +0,0 @@ -#if !NO_UNITY -using System; -using System.Collections.Generic; -using UnityEngine; - -namespace FullSerializer { - partial class fsConverterRegistrar { - public static Internal.DirectConverters.RectOffset_DirectConverter Register_RectOffset_DirectConverter; - } -} - -namespace FullSerializer.Internal.DirectConverters { - public class RectOffset_DirectConverter : fsDirectConverter { - protected override fsResult DoSerialize(RectOffset model, Dictionary serialized) { - var result = fsResult.Success; - - result += SerializeMember(serialized, null, "bottom", model.bottom); - result += SerializeMember(serialized, null, "left", model.left); - result += SerializeMember(serialized, null, "right", model.right); - result += SerializeMember(serialized, null, "top", model.top); - - return result; - } - - protected override fsResult DoDeserialize(Dictionary data, ref RectOffset model) { - var result = fsResult.Success; - - var t0 = model.bottom; - result += DeserializeMember(data, null, "bottom", out t0); - model.bottom = t0; - - var t2 = model.left; - result += DeserializeMember(data, null, "left", out t2); - model.left = t2; - - var t3 = model.right; - result += DeserializeMember(data, null, "right", out t3); - model.right = t3; - - var t4 = model.top; - result += DeserializeMember(data, null, "top", out t4); - model.top = t4; - - return result; - } - - public override object CreateInstance(fsData data, Type storageType) { - return new RectOffset(); - } - } -} -#endif \ No newline at end of file diff --git a/Assets/Source/Converters/Unity/RectOffset_DirectConverter.cs.meta b/Assets/Source/Converters/Unity/RectOffset_DirectConverter.cs.meta deleted file mode 100644 index 1a9c76b..0000000 --- a/Assets/Source/Converters/Unity/RectOffset_DirectConverter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: c677229cfd3fa6b4690b364b9529fc9e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/Converters/Unity/Rect_DirectConverter.cs b/Assets/Source/Converters/Unity/Rect_DirectConverter.cs deleted file mode 100644 index 4f506f2..0000000 --- a/Assets/Source/Converters/Unity/Rect_DirectConverter.cs +++ /dev/null @@ -1,52 +0,0 @@ -#if !NO_UNITY -using System; -using System.Collections.Generic; -using UnityEngine; - -namespace FullSerializer { - partial class fsConverterRegistrar { - public static Internal.DirectConverters.Rect_DirectConverter Register_Rect_DirectConverter; - } -} - -namespace FullSerializer.Internal.DirectConverters { - public class Rect_DirectConverter : fsDirectConverter { - protected override fsResult DoSerialize(Rect model, Dictionary serialized) { - var result = fsResult.Success; - - result += SerializeMember(serialized, null, "xMin", model.xMin); - result += SerializeMember(serialized, null, "yMin", model.yMin); - result += SerializeMember(serialized, null, "xMax", model.xMax); - result += SerializeMember(serialized, null, "yMax", model.yMax); - - return result; - } - - protected override fsResult DoDeserialize(Dictionary data, ref Rect model) { - var result = fsResult.Success; - - var t0 = model.xMin; - result += DeserializeMember(data, null, "xMin", out t0); - model.xMin = t0; - - var t1 = model.yMin; - result += DeserializeMember(data, null, "yMin", out t1); - model.yMin = t1; - - var t2 = model.xMax; - result += DeserializeMember(data, null, "xMax", out t2); - model.xMax = t2; - - var t3 = model.yMax; - result += DeserializeMember(data, null, "yMax", out t3); - model.yMax = t3; - - return result; - } - - public override object CreateInstance(fsData data, Type storageType) { - return new Rect(); - } - } -} -#endif \ No newline at end of file diff --git a/Assets/Source/Converters/Unity/Rect_DirectConverter.cs.meta b/Assets/Source/Converters/Unity/Rect_DirectConverter.cs.meta deleted file mode 100644 index 0041b2b..0000000 --- a/Assets/Source/Converters/Unity/Rect_DirectConverter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 9c430350334bb384791e23b7f1b5bf9d -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/Converters/Unity/UnityEvent_Converter.cs b/Assets/Source/Converters/Unity/UnityEvent_Converter.cs deleted file mode 100644 index 1aec155..0000000 --- a/Assets/Source/Converters/Unity/UnityEvent_Converter.cs +++ /dev/null @@ -1,42 +0,0 @@ -#if !NO_UNITY -using System; -using UnityEngine; -using UnityEngine.Events; - -namespace FullSerializer { - partial class fsConverterRegistrar { - public static Internal.Converters.UnityEvent_Converter Register_UnityEvent_Converter; - } -} - -namespace FullSerializer.Internal.Converters { - // The standard FS reflection converter has started causing Unity to crash when processing - // UnityEvent. We can send the serialization through JsonUtility which appears to work correctly - // instead. - // - // We have to support legacy serialization formats so importing works as expected. - public class UnityEvent_Converter : fsConverter { - public override bool CanProcess(Type type) { - return typeof(UnityEvent).Resolve().IsAssignableFrom(type) && type.IsGenericType == false; - } - - public override bool RequestCycleSupport(Type storageType) { - return false; - } - - public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType) { - Type objectType = (Type)instance; - - fsResult result = fsResult.Success; - instance = JsonUtility.FromJson(fsJsonPrinter.CompressedJson(data), objectType); - return result; - } - - public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType) { - fsResult result = fsResult.Success; - serialized = fsJsonParser.Parse(JsonUtility.ToJson(instance)); - return result; - } - } -} -#endif \ No newline at end of file diff --git a/Assets/Source/Converters/Unity/UnityEvent_Converter.cs.meta b/Assets/Source/Converters/Unity/UnityEvent_Converter.cs.meta deleted file mode 100644 index d7c811d..0000000 --- a/Assets/Source/Converters/Unity/UnityEvent_Converter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 45faf466f4f7d9c45b3f35d23689c56a -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/Converters/fsArrayConverter.cs b/Assets/Source/Converters/fsArrayConverter.cs deleted file mode 100644 index 42cd08d..0000000 --- a/Assets/Source/Converters/fsArrayConverter.cs +++ /dev/null @@ -1,80 +0,0 @@ -using System; -using System.Collections; - -namespace FullSerializer.Internal { - public class fsArrayConverter : fsConverter { - public override bool CanProcess(Type type) { - return type.IsArray; - } - - public override bool RequestCycleSupport(Type storageType) { - return false; - } - - public override bool RequestInheritanceSupport(Type storageType) { - return false; - } - - public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType) { - // note: IList[index] is **significantly** faster than Array.Get, so make sure we use - // that instead. - - IList arr = (Array)instance; - Type elementType = storageType.GetElementType(); - - var result = fsResult.Success; - - serialized = fsData.CreateList(arr.Count); - var serializedList = serialized.AsList; - - for (int i = 0; i < arr.Count; ++i) { - object item = arr[i]; - - fsData serializedItem; - - var itemResult = Serializer.TrySerialize(elementType, item, out serializedItem); - result.AddMessages(itemResult); - if (itemResult.Failed) continue; - - serializedList.Add(serializedItem); - } - - return result; - } - - public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType) { - var result = fsResult.Success; - - // Verify that we actually have an List - if ((result += CheckType(data, fsDataType.Array)).Failed) { - return result; - } - - Type elementType = storageType.GetElementType(); - - var serializedList = data.AsList; - var list = new ArrayList(serializedList.Count); - int existingCount = list.Count; - - for (int i = 0; i < serializedList.Count; ++i) { - var serializedItem = serializedList[i]; - object deserialized = null; - if (i < existingCount) deserialized = list[i]; - - var itemResult = Serializer.TryDeserialize(serializedItem, elementType, ref deserialized); - result.AddMessages(itemResult); - if (itemResult.Failed) continue; - - if (i < existingCount) list[i] = deserialized; - else list.Add(deserialized); - } - - instance = list.ToArray(elementType); - return result; - } - - public override object CreateInstance(fsData data, Type storageType) { - return fsMetaType.Get(Serializer.Config, storageType).CreateInstance(); - } - } -} \ No newline at end of file diff --git a/Assets/Source/Converters/fsArrayConverter.cs.meta b/Assets/Source/Converters/fsArrayConverter.cs.meta deleted file mode 100644 index 0b7bd94..0000000 --- a/Assets/Source/Converters/fsArrayConverter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ff26f497131ae3b4db5c02bf6ad36cbc -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/Converters/fsDateConverter.cs b/Assets/Source/Converters/fsDateConverter.cs deleted file mode 100644 index d3e3fee..0000000 --- a/Assets/Source/Converters/fsDateConverter.cs +++ /dev/null @@ -1,96 +0,0 @@ -using System; -using System.Globalization; - -namespace FullSerializer.Internal { - /// - /// Supports serialization for DateTime, DateTimeOffset, and TimeSpan. - /// - public class fsDateConverter : fsConverter { - // The format strings that we use when serializing DateTime and DateTimeOffset types. - private const string DefaultDateTimeFormatString = @"o"; - private const string DateTimeOffsetFormatString = @"o"; - - private string DateTimeFormatString { - get { - return Serializer.Config.CustomDateTimeFormatString ?? DefaultDateTimeFormatString; - } - } - - public override bool CanProcess(Type type) { - return - type == typeof(DateTime) || - type == typeof(DateTimeOffset) || - type == typeof(TimeSpan); - } - - public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType) { - if (instance is DateTime) { - var dateTime = (DateTime)instance; - serialized = new fsData(dateTime.ToString(DateTimeFormatString)); - return fsResult.Success; - } - - if (instance is DateTimeOffset) { - var dateTimeOffset = (DateTimeOffset)instance; - serialized = new fsData(dateTimeOffset.ToString(DateTimeOffsetFormatString)); - return fsResult.Success; - } - - if (instance is TimeSpan) { - var timeSpan = (TimeSpan)instance; - serialized = new fsData(timeSpan.ToString()); - return fsResult.Success; - } - - throw new InvalidOperationException("FullSerializer Internal Error -- Unexpected serialization type"); - } - - public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType) { - if (data.IsString == false) { - return fsResult.Fail("Date deserialization requires a string, not " + data.Type); - } - - if (storageType == typeof(DateTime)) { - DateTime result; - if (DateTime.TryParse(data.AsString, null, DateTimeStyles.RoundtripKind, out result)) { - instance = result; - return fsResult.Success; - } - - // DateTime.TryParse can fail for some valid DateTime instances. Try to use Convert.ToDateTime. - if (fsGlobalConfig.AllowInternalExceptions) { - try { - instance = Convert.ToDateTime(data.AsString); - return fsResult.Success; - } catch (Exception e) { - return fsResult.Fail("Unable to parse " + data.AsString + " into a DateTime; got exception " + e); - } - } - - return fsResult.Fail("Unable to parse " + data.AsString + " into a DateTime"); - } - - if (storageType == typeof(DateTimeOffset)) { - DateTimeOffset result; - if (DateTimeOffset.TryParse(data.AsString, null, DateTimeStyles.RoundtripKind, out result)) { - instance = result; - return fsResult.Success; - } - - return fsResult.Fail("Unable to parse " + data.AsString + " into a DateTimeOffset"); - } - - if (storageType == typeof(TimeSpan)) { - TimeSpan result; - if (TimeSpan.TryParse(data.AsString, out result)) { - instance = result; - return fsResult.Success; - } - - return fsResult.Fail("Unable to parse " + data.AsString + " into a TimeSpan"); - } - - throw new InvalidOperationException("FullSerializer Internal Error -- Unexpected deserialization type"); - } - } -} \ No newline at end of file diff --git a/Assets/Source/Converters/fsDateConverter.cs.meta b/Assets/Source/Converters/fsDateConverter.cs.meta deleted file mode 100644 index 31c579f..0000000 --- a/Assets/Source/Converters/fsDateConverter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: e3dcd313c5acdc442a22f755080c67a9 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/Converters/fsDictionaryConverter.cs b/Assets/Source/Converters/fsDictionaryConverter.cs deleted file mode 100644 index 5f39875..0000000 --- a/Assets/Source/Converters/fsDictionaryConverter.cs +++ /dev/null @@ -1,171 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Reflection; - -namespace FullSerializer.Internal { - // While the generic IEnumerable converter can handle dictionaries, we process them separately here because - // we support a few more advanced use-cases with dictionaries, such as inline strings. Further, dictionary - // processing in general is a bit more advanced because a few of the collection implementations are buggy. - public class fsDictionaryConverter : fsConverter { - public override bool CanProcess(Type type) { - return typeof(IDictionary).IsAssignableFrom(type); - } - - public override object CreateInstance(fsData data, Type storageType) { - return fsMetaType.Get(Serializer.Config, storageType).CreateInstance(); - } - - public override fsResult TryDeserialize(fsData data, ref object instance_, Type storageType) { - var instance = (IDictionary)instance_; - var result = fsResult.Success; - - Type keyStorageType, valueStorageType; - GetKeyValueTypes(instance.GetType(), out keyStorageType, out valueStorageType); - - if (data.IsList) { - var list = data.AsList; - for (int i = 0; i < list.Count; ++i) { - var item = list[i]; - - fsData keyData, valueData; - if ((result += CheckType(item, fsDataType.Object)).Failed) return result; - if ((result += CheckKey(item, "Key", out keyData)).Failed) return result; - if ((result += CheckKey(item, "Value", out valueData)).Failed) return result; - - object keyInstance = null, valueInstance = null; - if ((result += Serializer.TryDeserialize(keyData, keyStorageType, ref keyInstance)).Failed) return result; - if ((result += Serializer.TryDeserialize(valueData, valueStorageType, ref valueInstance)).Failed) return result; - - AddItemToDictionary(instance, keyInstance, valueInstance); - } - } - else if (data.IsDictionary) { - foreach (var entry in data.AsDictionary) { - if (fsSerializer.IsReservedKeyword(entry.Key)) continue; - - fsData keyData = new fsData(entry.Key), valueData = entry.Value; - object keyInstance = null, valueInstance = null; - - if ((result += Serializer.TryDeserialize(keyData, keyStorageType, ref keyInstance)).Failed) return result; - if ((result += Serializer.TryDeserialize(valueData, valueStorageType, ref valueInstance)).Failed) return result; - - AddItemToDictionary(instance, keyInstance, valueInstance); - } - } - else { - return FailExpectedType(data, fsDataType.Array, fsDataType.Object); - } - - return result; - } - - public override fsResult TrySerialize(object instance_, out fsData serialized, Type storageType) { - serialized = fsData.Null; - - var result = fsResult.Success; - - var instance = (IDictionary)instance_; - - Type keyStorageType, valueStorageType; - GetKeyValueTypes(instance.GetType(), out keyStorageType, out valueStorageType); - - // No other way to iterate dictionaries and still have access to the key/value info - IDictionaryEnumerator enumerator = instance.GetEnumerator(); - - bool allStringKeys = true; - var serializedKeys = new List(instance.Count); - var serializedValues = new List(instance.Count); - while (enumerator.MoveNext()) { - fsData keyData, valueData; - if ((result += Serializer.TrySerialize(keyStorageType, enumerator.Key, out keyData)).Failed) return result; - if ((result += Serializer.TrySerialize(valueStorageType, enumerator.Value, out valueData)).Failed) return result; - - serializedKeys.Add(keyData); - serializedValues.Add(valueData); - - allStringKeys &= keyData.IsString; - } - - if (allStringKeys) { - serialized = fsData.CreateDictionary(); - var serializedDictionary = serialized.AsDictionary; - - for (int i = 0; i < serializedKeys.Count; ++i) { - fsData key = serializedKeys[i]; - fsData value = serializedValues[i]; - serializedDictionary[key.AsString] = value; - } - } - else { - serialized = fsData.CreateList(serializedKeys.Count); - var serializedList = serialized.AsList; - - for (int i = 0; i < serializedKeys.Count; ++i) { - fsData key = serializedKeys[i]; - fsData value = serializedValues[i]; - - var container = new Dictionary(); - container["Key"] = key; - container["Value"] = value; - serializedList.Add(new fsData(container)); - } - } - - return result; - } - - private fsResult AddItemToDictionary(IDictionary dictionary, object key, object value) { - // Because we're operating through the IDictionary interface by default (and not the - // generic one), we normally send items through IDictionary.Add(object, object). This - // works fine in the general case, except that the add method verifies that it's - // parameter types are proper types. However, mono is buggy and these type checks do - // not consider null a subtype of the parameter types, and exceptions get thrown. So, - // we have to special case adding null items via the generic functions (which do not - // do the null check), which is slow and messy. - // - // An example of a collection that fails deserialization without this method is - // `new SortedList { { 0, null } }`. (SortedDictionary is fine because - // it properly handles null values). - if (key == null || value == null) { - // Life would be much easier if we had MakeGenericType available, but we don't. So - // we're going to find the correct generic KeyValuePair type via a bit of trickery. - // All dictionaries extend ICollection>, so we just - // fetch the ICollection<> type with the proper generic arguments, and then we take - // the KeyValuePair<> generic argument, and whola! we have our proper generic type. - - var collectionType = fsReflectionUtility.GetInterface(dictionary.GetType(), typeof(ICollection<>)); - if (collectionType == null) { - return fsResult.Warn(dictionary.GetType() + " does not extend ICollection"); - } - - var keyValuePairType = collectionType.GetGenericArguments()[0]; - object keyValueInstance = Activator.CreateInstance(keyValuePairType, key, value); - MethodInfo add = collectionType.GetFlattenedMethod("Add"); - add.Invoke(dictionary, new object[] { keyValueInstance }); - return fsResult.Success; - } - - // We use the inline set methods instead of dictionary.Add; dictionary.Add will throw an exception - // if the key already exists. - dictionary[key] = value; - return fsResult.Success; - } - - private static void GetKeyValueTypes(Type dictionaryType, out Type keyStorageType, out Type valueStorageType) { - // All dictionaries extend IDictionary, so we just fetch the generic arguments from it - var interfaceType = fsReflectionUtility.GetInterface(dictionaryType, typeof(IDictionary<,>)); - if (interfaceType != null) { - var genericArgs = interfaceType.GetGenericArguments(); - keyStorageType = genericArgs[0]; - valueStorageType = genericArgs[1]; - } - - else { - // Fetching IDictionary<,> failed... we have to encode full type information :( - keyStorageType = typeof(object); - valueStorageType = typeof(object); - } - } - } -} \ No newline at end of file diff --git a/Assets/Source/Converters/fsDictionaryConverter.cs.meta b/Assets/Source/Converters/fsDictionaryConverter.cs.meta deleted file mode 100644 index 8282a6b..0000000 --- a/Assets/Source/Converters/fsDictionaryConverter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 5c1fd84fc9c6dda4088367b5859c04a5 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/Converters/fsEnumConverter.cs b/Assets/Source/Converters/fsEnumConverter.cs deleted file mode 100644 index 66d6ecb..0000000 --- a/Assets/Source/Converters/fsEnumConverter.cs +++ /dev/null @@ -1,105 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace FullSerializer.Internal { - /// - /// Serializes and deserializes enums by their current name. - /// - public class fsEnumConverter : fsConverter { - public override bool CanProcess(Type type) { - return type.Resolve().IsEnum; - } - - public override bool RequestCycleSupport(Type storageType) { - return false; - } - - public override bool RequestInheritanceSupport(Type storageType) { - return false; - } - - public override object CreateInstance(fsData data, Type storageType) { - // In .NET compact, Enum.ToObject(Type, Object) is defined but the overloads like - // Enum.ToObject(Type, int) are not -- so we get around this by boxing the value. - return Enum.ToObject(storageType, (object)0); - } - - public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType) { - if (Serializer.Config.SerializeEnumsAsInteger) { - serialized = new fsData(Convert.ToInt64(instance)); - } - else if (fsPortableReflection.GetAttribute(storageType) != null) { - long instanceValue = Convert.ToInt64(instance); - var result = new StringBuilder(); - - bool first = true; - foreach (var value in Enum.GetValues(storageType)) { - long integralValue = Convert.ToInt64(value); - bool isSet = (instanceValue & integralValue) != 0; - - if (isSet) { - if (first == false) result.Append(","); - first = false; - result.Append(value.ToString()); - } - } - - serialized = new fsData(result.ToString()); - } - else { - serialized = new fsData(Enum.GetName(storageType, instance)); - } - return fsResult.Success; - } - - public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType) { - if (data.IsString) { - string[] enumValues = data.AsString.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); - - long instanceValue = 0; - for (int i = 0; i < enumValues.Length; ++i) { - string enumValue = enumValues[i]; - - // Verify that the enum name exists; Enum.TryParse is only available in .NET 4.0 - // and above :(. - if (ArrayContains(Enum.GetNames(storageType), enumValue) == false) { - return fsResult.Fail("Cannot find enum name " + enumValue + " on type " + storageType); - } - - long flagValue = (long)Convert.ChangeType(Enum.Parse(storageType, enumValue), typeof(long)); - instanceValue |= flagValue; - } - - instance = Enum.ToObject(storageType, (object)instanceValue); - return fsResult.Success; - } - - else if (data.IsInt64) { - int enumValue = (int)data.AsInt64; - - // In .NET compact, Enum.ToObject(Type, Object) is defined but the overloads like - // Enum.ToObject(Type, int) are not -- so we get around this by boxing the value. - instance = Enum.ToObject(storageType, (object)enumValue); - - return fsResult.Success; - } - - return fsResult.Fail("EnumConverter encountered an unknown JSON data type"); - } - - /// - /// Returns true if the given value is contained within the specified array. - /// - private static bool ArrayContains(T[] values, T value) { - // note: We don't use LINQ because this function will *not* allocate - for (int i = 0; i < values.Length; ++i) { - if (EqualityComparer.Default.Equals(values[i], value)) { - return true; - } - } - - return false; - } - } -} \ No newline at end of file diff --git a/Assets/Source/Converters/fsEnumConverter.cs.meta b/Assets/Source/Converters/fsEnumConverter.cs.meta deleted file mode 100644 index 7ed8d51..0000000 --- a/Assets/Source/Converters/fsEnumConverter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: c560df084b66b254ab5e9bdfc847c7bd -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/Converters/fsForwardConverter.cs b/Assets/Source/Converters/fsForwardConverter.cs deleted file mode 100644 index f9b8f95..0000000 --- a/Assets/Source/Converters/fsForwardConverter.cs +++ /dev/null @@ -1,86 +0,0 @@ -using System; - -namespace FullSerializer { - /// - /// This allows you to forward serialization of an object to one of its members. For example, - /// - /// [fsForward("Values")] - /// struct Wrapper { - /// public int[] Values; - /// } - /// - /// Then `Wrapper` will be serialized into a JSON array of integers. It will be as if `Wrapper` - /// doesn't exist. - /// - [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct)] - public sealed class fsForwardAttribute : Attribute { - /// - /// The name of the member we should serialize as. - /// - public string MemberName; - - /// - /// Forward object serialization to an instance member. See class comment. - /// - /// The name of the member that we should serialize this object as. - public fsForwardAttribute(string memberName) { - MemberName = memberName; - } - } -} - -namespace FullSerializer.Internal { - public class fsForwardConverter : fsConverter { - private string _memberName; - - public fsForwardConverter(fsForwardAttribute attribute) { - _memberName = attribute.MemberName; - } - - public override bool CanProcess(Type type) { - throw new NotSupportedException("Please use the [fsForward(...)] attribute."); - } - - private fsResult GetProperty(object instance, out fsMetaProperty property) { - var properties = fsMetaType.Get(Serializer.Config, instance.GetType()).Properties; - for (int i = 0; i < properties.Length; ++i) { - if (properties[i].MemberName == _memberName) { - property = properties[i]; - return fsResult.Success; - } - } - - property = default(fsMetaProperty); - return fsResult.Fail("No property named \"" + _memberName + "\" on " + instance.GetType().CSharpName()); - } - - public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType) { - serialized = fsData.Null; - var result = fsResult.Success; - - fsMetaProperty property; - if ((result += GetProperty(instance, out property)).Failed) return result; - - var actualInstance = property.Read(instance); - return Serializer.TrySerialize(property.StorageType, actualInstance, out serialized); - } - - public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType) { - var result = fsResult.Success; - - fsMetaProperty property; - if ((result += GetProperty(instance, out property)).Failed) return result; - - object actualInstance = null; - if ((result += Serializer.TryDeserialize(data, property.StorageType, ref actualInstance)).Failed) - return result; - - property.Write(instance, actualInstance); - return result; - } - - public override object CreateInstance(fsData data, Type storageType) { - return fsMetaType.Get(Serializer.Config, storageType).CreateInstance(); - } - } -} \ No newline at end of file diff --git a/Assets/Source/Converters/fsForwardConverter.cs.meta b/Assets/Source/Converters/fsForwardConverter.cs.meta deleted file mode 100644 index cd3c404..0000000 --- a/Assets/Source/Converters/fsForwardConverter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 89892b3279cd6e249838f8b44cc0f838 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/Converters/fsGuidConverter.cs b/Assets/Source/Converters/fsGuidConverter.cs deleted file mode 100644 index 01d0b80..0000000 --- a/Assets/Source/Converters/fsGuidConverter.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System; - -namespace FullSerializer.Internal { - /// - /// Serializes and deserializes guids. - /// - public class fsGuidConverter : fsConverter { - public override bool CanProcess(Type type) { - return type == typeof(Guid); - } - - public override bool RequestCycleSupport(Type storageType) { - return false; - } - - public override bool RequestInheritanceSupport(Type storageType) { - return false; - } - - public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType) { - var guid = (Guid)instance; - serialized = new fsData(guid.ToString()); - return fsResult.Success; - } - - public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType) { - if (data.IsString) { - instance = new Guid(data.AsString); - return fsResult.Success; - } - - return fsResult.Fail("fsGuidConverter encountered an unknown JSON data type"); - } - - public override object CreateInstance(fsData data, Type storageType) { - return new Guid(); - } - } -} \ No newline at end of file diff --git a/Assets/Source/Converters/fsGuidConverter.cs.meta b/Assets/Source/Converters/fsGuidConverter.cs.meta deleted file mode 100644 index e01bdc0..0000000 --- a/Assets/Source/Converters/fsGuidConverter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 09373a87560925948a4a8343e4edb9ab -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/Converters/fsIEnumerableConverter.cs b/Assets/Source/Converters/fsIEnumerableConverter.cs deleted file mode 100644 index b578adf..0000000 --- a/Assets/Source/Converters/fsIEnumerableConverter.cs +++ /dev/null @@ -1,145 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Reflection; - -namespace FullSerializer.Internal { - /// - /// Provides serialization support for anything which extends from `IEnumerable` and has an `Add` method. - /// - public class fsIEnumerableConverter : fsConverter { - public override bool CanProcess(Type type) { - if (typeof(IEnumerable).IsAssignableFrom(type) == false) return false; - return GetAddMethod(type) != null; - } - - public override object CreateInstance(fsData data, Type storageType) { - return fsMetaType.Get(Serializer.Config, storageType).CreateInstance(); - } - - public override fsResult TrySerialize(object instance_, out fsData serialized, Type storageType) { - var instance = (IEnumerable)instance_; - var result = fsResult.Success; - - Type elementType = GetElementType(storageType); - - serialized = fsData.CreateList(HintSize(instance)); - var serializedList = serialized.AsList; - - foreach (object item in instance) { - fsData itemData; - - // note: We don't fail the entire deserialization even if the item failed - var itemResult = Serializer.TrySerialize(elementType, item, out itemData); - result.AddMessages(itemResult); - if (itemResult.Failed) continue; - - serializedList.Add(itemData); - } - - // Stacks iterate from back to front, which means when we deserialize we will deserialize - // the items in the wrong order, so the stack will get reversed. - if (IsStack(instance.GetType())) { - serializedList.Reverse(); - } - - return result; - } - - private bool IsStack(Type type) { - return type.Resolve().IsGenericType && - type.Resolve().GetGenericTypeDefinition() == typeof(Stack<>); - } - - public override fsResult TryDeserialize(fsData data, ref object instance_, Type storageType) { - var instance = (IEnumerable)instance_; - var result = fsResult.Success; - - if ((result += CheckType(data, fsDataType.Array)).Failed) return result; - - // For general strategy, instance may already have items in it. We will try to deserialize into - // the existing element. - var elementStorageType = GetElementType(storageType); - var addMethod = GetAddMethod(storageType); - var getMethod = storageType.GetFlattenedMethod("get_Item"); - var setMethod = storageType.GetFlattenedMethod("set_Item"); - if (setMethod == null) TryClear(storageType, instance); - var existingSize = TryGetExistingSize(storageType, instance); - - var serializedList = data.AsList; - for (int i = 0; i < serializedList.Count; ++i) { - var itemData = serializedList[i]; - object itemInstance = null; - if (getMethod != null && i < existingSize) { - itemInstance = getMethod.Invoke(instance, new object[] { i }); - } - - // note: We don't fail the entire deserialization even if the item failed - var itemResult = Serializer.TryDeserialize(itemData, elementStorageType, ref itemInstance); - result.AddMessages(itemResult); - if (itemResult.Failed) continue; - - if (setMethod != null && i < existingSize) { - setMethod.Invoke(instance, new object[] { i, itemInstance }); - } - else { - addMethod.Invoke(instance, new object[] { itemInstance }); - } - } - - return result; - } - - private static int HintSize(IEnumerable collection) { - if (collection is ICollection) { - return ((ICollection)collection).Count; - } - return 0; - } - - /// - /// Fetches the element type for objects inside of the collection. - /// - private static Type GetElementType(Type objectType) { - if (objectType.HasElementType) return objectType.GetElementType(); - - Type enumerableList = fsReflectionUtility.GetInterface(objectType, typeof(IEnumerable<>)); - if (enumerableList != null) return enumerableList.GetGenericArguments()[0]; - - return typeof(object); - } - - private static void TryClear(Type type, object instance) { - var clear = type.GetFlattenedMethod("Clear"); - if (clear != null) { - clear.Invoke(instance, null); - } - } - - private static int TryGetExistingSize(Type type, object instance) { - var count = type.GetFlattenedProperty("Count"); - if (count != null) { - return (int)count.GetGetMethod().Invoke(instance, null); - } - return 0; - } - - private static MethodInfo GetAddMethod(Type type) { - // There is a really good chance the type will extend ICollection{}, which will contain - // the add method we want. Just doing type.GetFlattenedMethod() may return the incorrect one -- - // for example, with dictionaries, it'll return Add(TKey, TValue), and we want - // Add(KeyValuePair). - Type collectionInterface = fsReflectionUtility.GetInterface(type, typeof(ICollection<>)); - if (collectionInterface != null) { - MethodInfo add = collectionInterface.GetDeclaredMethod("Add"); - if (add != null) return add; - } - - // Otherwise try and look up a general Add method. - return - type.GetFlattenedMethod("Add") ?? - type.GetFlattenedMethod("Push") ?? - type.GetFlattenedMethod("Enqueue"); - } - } -} \ No newline at end of file diff --git a/Assets/Source/Converters/fsIEnumerableConverter.cs.meta b/Assets/Source/Converters/fsIEnumerableConverter.cs.meta deleted file mode 100644 index 3922170..0000000 --- a/Assets/Source/Converters/fsIEnumerableConverter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 4a7fdd4014dc894458c54513809a2998 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/Converters/fsKeyValuePairConverter.cs b/Assets/Source/Converters/fsKeyValuePairConverter.cs deleted file mode 100644 index 2082d0e..0000000 --- a/Assets/Source/Converters/fsKeyValuePairConverter.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Reflection; - -namespace FullSerializer.Internal { - public class fsKeyValuePairConverter : fsConverter { - public override bool CanProcess(Type type) { - return - type.Resolve().IsGenericType && - type.GetGenericTypeDefinition() == typeof(KeyValuePair<,>); - } - - public override bool RequestCycleSupport(Type storageType) { - return false; - } - - public override bool RequestInheritanceSupport(Type storageType) { - return false; - } - - public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType) { - var result = fsResult.Success; - - fsData keyData, valueData; - if ((result += CheckKey(data, "Key", out keyData)).Failed) return result; - if ((result += CheckKey(data, "Value", out valueData)).Failed) return result; - - var genericArguments = storageType.GetGenericArguments(); - Type keyType = genericArguments[0], valueType = genericArguments[1]; - - object keyObject = null, valueObject = null; - result.AddMessages(Serializer.TryDeserialize(keyData, keyType, ref keyObject)); - result.AddMessages(Serializer.TryDeserialize(valueData, valueType, ref valueObject)); - - instance = Activator.CreateInstance(storageType, keyObject, valueObject); - return result; - } - - public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType) { - PropertyInfo keyProperty = storageType.GetDeclaredProperty("Key"); - PropertyInfo valueProperty = storageType.GetDeclaredProperty("Value"); - - object keyObject = keyProperty.GetValue(instance, null); - object valueObject = valueProperty.GetValue(instance, null); - - var genericArguments = storageType.GetGenericArguments(); - Type keyType = genericArguments[0], valueType = genericArguments[1]; - - var result = fsResult.Success; - - fsData keyData, valueData; - result.AddMessages(Serializer.TrySerialize(keyType, keyObject, out keyData)); - result.AddMessages(Serializer.TrySerialize(valueType, valueObject, out valueData)); - - serialized = fsData.CreateDictionary(); - if (keyData != null) serialized.AsDictionary["Key"] = keyData; - if (valueData != null) serialized.AsDictionary["Value"] = valueData; - - return result; - } - } -} \ No newline at end of file diff --git a/Assets/Source/Converters/fsKeyValuePairConverter.cs.meta b/Assets/Source/Converters/fsKeyValuePairConverter.cs.meta deleted file mode 100644 index 53cd766..0000000 --- a/Assets/Source/Converters/fsKeyValuePairConverter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 7a3857f6e037d454194843e278772b9f -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/Converters/fsNullableConverter.cs b/Assets/Source/Converters/fsNullableConverter.cs deleted file mode 100644 index 09c1223..0000000 --- a/Assets/Source/Converters/fsNullableConverter.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; - -namespace FullSerializer.Internal { - /// - /// The reflected converter will properly serialize nullable types. However, we do it here - /// instead as we can emit less serialization data. - /// - public class fsNullableConverter : fsConverter { - public override bool CanProcess(Type type) { - return - type.Resolve().IsGenericType && - type.GetGenericTypeDefinition() == typeof(Nullable<>); - } - - public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType) { - // null is automatically serialized - return Serializer.TrySerialize(Nullable.GetUnderlyingType(storageType), instance, out serialized); - } - - public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType) { - // null is automatically deserialized - return Serializer.TryDeserialize(data, Nullable.GetUnderlyingType(storageType), ref instance); - } - - public override object CreateInstance(fsData data, Type storageType) { - return storageType; - } - } -} \ No newline at end of file diff --git a/Assets/Source/Converters/fsNullableConverter.cs.meta b/Assets/Source/Converters/fsNullableConverter.cs.meta deleted file mode 100644 index 00f380a..0000000 --- a/Assets/Source/Converters/fsNullableConverter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 71d2abb9701478740b1fbb8720a63a24 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/Converters/fsPrimitiveConverter.cs b/Assets/Source/Converters/fsPrimitiveConverter.cs deleted file mode 100644 index 9ae68b0..0000000 --- a/Assets/Source/Converters/fsPrimitiveConverter.cs +++ /dev/null @@ -1,125 +0,0 @@ -using System; - -namespace FullSerializer.Internal { - public class fsPrimitiveConverter : fsConverter { - public override bool CanProcess(Type type) { - return - type.Resolve().IsPrimitive || - type == typeof(string) || - type == typeof(decimal); - } - - public override bool RequestCycleSupport(Type storageType) { - return false; - } - - public override bool RequestInheritanceSupport(Type storageType) { - return false; - } - - private static bool UseBool(Type type) { - return type == typeof(bool); - } - - private static bool UseInt64(Type type) { - return type == typeof(sbyte) || type == typeof(byte) || - type == typeof(Int16) || type == typeof(UInt16) || - type == typeof(Int32) || type == typeof(UInt32) || - type == typeof(Int64) || type == typeof(UInt64); - } - - private static bool UseDouble(Type type) { - return type == typeof(float) || - type == typeof(double) || - type == typeof(decimal); - } - - private static bool UseString(Type type) { - return type == typeof(string) || - type == typeof(char); - } - - public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType) { - var instanceType = instance.GetType(); - - if (Serializer.Config.Serialize64BitIntegerAsString && (instanceType == typeof(Int64) || instanceType == typeof(UInt64))) { - serialized = new fsData((string)Convert.ChangeType(instance, typeof(string))); - return fsResult.Success; - } - - if (UseBool(instanceType)) { - serialized = new fsData((bool)instance); - return fsResult.Success; - } - - if (UseInt64(instanceType)) { - serialized = new fsData((Int64)Convert.ChangeType(instance, typeof(Int64))); - return fsResult.Success; - } - - if (UseDouble(instanceType)) { - // Casting from float to double introduces floating point jitter, ie, 0.1 becomes 0.100000001490116. - // Casting to decimal as an intermediate step removes the jitter. Not sure why. - if (instance.GetType() == typeof(float) && - // Decimal can't store float.MinValue/float.MaxValue/float.PositiveInfinity/float.NegativeInfinity/float.NaN - an exception gets thrown in that scenario. - (float)instance != float.MinValue && - (float)instance != float.MaxValue && - !float.IsInfinity((float)instance) && - !float.IsNaN((float)instance) - ) { - serialized = new fsData((double)(decimal)(float)instance); - return fsResult.Success; - } - - serialized = new fsData((double)Convert.ChangeType(instance, typeof(double))); - return fsResult.Success; - } - - if (UseString(instanceType)) { - serialized = new fsData((string)Convert.ChangeType(instance, typeof(string))); - return fsResult.Success; - } - - serialized = null; - return fsResult.Fail("Unhandled primitive type " + instance.GetType()); - } - - public override fsResult TryDeserialize(fsData storage, ref object instance, Type storageType) { - var result = fsResult.Success; - - if (UseBool(storageType)) { - if ((result += CheckType(storage, fsDataType.Boolean)).Succeeded) { - instance = storage.AsBool; - } - return result; - } - - if (UseDouble(storageType) || UseInt64(storageType)) { - if (storage.IsDouble) { - instance = Convert.ChangeType(storage.AsDouble, storageType); - } - else if (storage.IsInt64) { - instance = Convert.ChangeType(storage.AsInt64, storageType); - } - else if (Serializer.Config.Serialize64BitIntegerAsString && storage.IsString && - (storageType == typeof(Int64) || storageType == typeof(UInt64))) { - instance = Convert.ChangeType(storage.AsString, storageType); - } - else { - return fsResult.Fail(GetType().Name + " expected number but got " + storage.Type + " in " + storage); - } - return fsResult.Success; - } - - if (UseString(storageType)) { - if ((result += CheckType(storage, fsDataType.String)).Succeeded) { - instance = storage.AsString; - } - return result; - } - - return fsResult.Fail(GetType().Name + ": Bad data; expected bool, number, string, but got " + storage); - } - } -} - diff --git a/Assets/Source/Converters/fsPrimitiveConverter.cs.meta b/Assets/Source/Converters/fsPrimitiveConverter.cs.meta deleted file mode 100644 index f6bfcf2..0000000 --- a/Assets/Source/Converters/fsPrimitiveConverter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 790de8a8a4ec95444ac95d5a812d69b3 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/Converters/fsReflectedConverter.cs b/Assets/Source/Converters/fsReflectedConverter.cs deleted file mode 100644 index 76459ed..0000000 --- a/Assets/Source/Converters/fsReflectedConverter.cs +++ /dev/null @@ -1,93 +0,0 @@ -using System; -using System.Collections; - -#if !UNITY_EDITOR && UNITY_WSA -// For System.Reflection.TypeExtensions -using System.Reflection; -#endif - -namespace FullSerializer.Internal { - public class fsReflectedConverter : fsConverter { - public override bool CanProcess(Type type) { - if (type.Resolve().IsArray || - typeof(ICollection).IsAssignableFrom(type)) { - - return false; - } - - return true; - } - - public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType) { - serialized = fsData.CreateDictionary(); - var result = fsResult.Success; - - fsMetaType metaType = fsMetaType.Get(Serializer.Config, instance.GetType()); - metaType.EmitAotData(); - - for (int i = 0; i < metaType.Properties.Length; ++i) { - fsMetaProperty property = metaType.Properties[i]; - if (property.CanRead == false) continue; - - fsData serializedData; - - var itemResult = Serializer.TrySerialize(property.StorageType, property.OverrideConverterType, - property.Read(instance), out serializedData); - result.AddMessages(itemResult); - if (itemResult.Failed) { - continue; - } - - serialized.AsDictionary[property.JsonName] = serializedData; - } - - return result; - } - - public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType) { - var result = fsResult.Success; - - // Verify that we actually have an Object - if ((result += CheckType(data, fsDataType.Object)).Failed) { - return result; - } - - fsMetaType metaType = fsMetaType.Get(Serializer.Config, storageType); - metaType.EmitAotData(); - - for (int i = 0; i < metaType.Properties.Length; ++i) { - fsMetaProperty property = metaType.Properties[i]; - if (property.CanWrite == false) continue; - - fsData propertyData; - if (data.AsDictionary.TryGetValue(property.JsonName, out propertyData)) { - object deserializedValue = null; - - // We have to read in the existing value, since we need to support partial - // deserialization. However, this is bad for perf. - // TODO: Find a way to avoid this call when we are not doing a partial deserialization - // Maybe through a new property, ie, Serializer.IsPartialSerialization, which just - // gets set when starting a new serialization? We cannot pipe the information - // through CreateInstance unfortunately. - if (property.CanRead) { - deserializedValue = property.Read(instance); - } - - var itemResult = Serializer.TryDeserialize(propertyData, property.StorageType, - property.OverrideConverterType, ref deserializedValue); - result.AddMessages(itemResult); - if (itemResult.Failed) continue; - - property.Write(instance, deserializedValue); - } - } - - return result; - } - - public override object CreateInstance(fsData data, Type storageType) { - fsMetaType metaType = fsMetaType.Get(Serializer.Config, storageType); - return metaType.CreateInstance(); - } - } -} \ No newline at end of file diff --git a/Assets/Source/Converters/fsReflectedConverter.cs.meta b/Assets/Source/Converters/fsReflectedConverter.cs.meta deleted file mode 100644 index d13c2a3..0000000 --- a/Assets/Source/Converters/fsReflectedConverter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: a23ca5511c2d3cc4692dfc7f11d9ed67 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/Converters/fsTypeConverter.cs b/Assets/Source/Converters/fsTypeConverter.cs deleted file mode 100644 index 71264eb..0000000 --- a/Assets/Source/Converters/fsTypeConverter.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System; - -#if !UNITY_EDITOR && UNITY_WSA -// For System.Reflection.TypeExtensions -using System.Reflection; -#endif - -namespace FullSerializer.Internal { - public class fsTypeConverter : fsConverter { - public override bool CanProcess(Type type) { - return typeof(Type).IsAssignableFrom(type); - } - - public override bool RequestCycleSupport(Type type) { - return false; - } - - public override bool RequestInheritanceSupport(Type type) { - return false; - } - - public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType) { - var type = (Type)instance; - serialized = new fsData(type.FullName); - return fsResult.Success; - } - - public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType) { - if (data.IsString == false) { - return fsResult.Fail("Type converter requires a string"); - } - - instance = fsTypeCache.GetType(data.AsString); - if (instance == null) { - return fsResult.Fail("Unable to find type " + data.AsString); - } - return fsResult.Success; - } - - public override object CreateInstance(fsData data, Type storageType) { - return storageType; - } - } -} \ No newline at end of file diff --git a/Assets/Source/Converters/fsTypeConverter.cs.meta b/Assets/Source/Converters/fsTypeConverter.cs.meta deleted file mode 100644 index 0a3d846..0000000 --- a/Assets/Source/Converters/fsTypeConverter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: aba11236805ed6b4a9f9616bc70a02d7 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/Converters/fsWeakReferenceConverter.cs b/Assets/Source/Converters/fsWeakReferenceConverter.cs deleted file mode 100644 index a7ceadd..0000000 --- a/Assets/Source/Converters/fsWeakReferenceConverter.cs +++ /dev/null @@ -1,65 +0,0 @@ -using System; - -namespace FullSerializer.Internal { - /// - /// Serializes and deserializes WeakReferences. - /// - public class fsWeakReferenceConverter : fsConverter { - public override bool CanProcess(Type type) { - return type == typeof(WeakReference); - } - - public override bool RequestCycleSupport(Type storageType) { - return false; - } - - public override bool RequestInheritanceSupport(Type storageType) { - return false; - } - - public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType) { - var weakRef = (WeakReference)instance; - - var result = fsResult.Success; - serialized = fsData.CreateDictionary(); - - if (weakRef.IsAlive) { - fsData data; - if ((result += Serializer.TrySerialize(weakRef.Target, out data)).Failed) { - return result; - } - - serialized.AsDictionary["Target"] = data; - serialized.AsDictionary["TrackResurrection"] = new fsData(weakRef.TrackResurrection); - } - - return result; - } - - public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType) { - var result = fsResult.Success; - - if ((result += CheckType(data, fsDataType.Object)).Failed) return result; - - if (data.AsDictionary.ContainsKey("Target")) { - var targetData = data.AsDictionary["Target"]; - object targetInstance = null; - - if ((result += Serializer.TryDeserialize(targetData, typeof(object), ref targetInstance)).Failed) return result; - - bool trackResurrection = false; - if (data.AsDictionary.ContainsKey("TrackResurrection") && data.AsDictionary["TrackResurrection"].IsBool) { - trackResurrection = data.AsDictionary["TrackResurrection"].AsBool; - } - - instance = new WeakReference(targetInstance, trackResurrection); - } - - return result; - } - - public override object CreateInstance(fsData data, Type storageType) { - return new WeakReference(null); - } - } -} \ No newline at end of file diff --git a/Assets/Source/Converters/fsWeakReferenceConverter.cs.meta b/Assets/Source/Converters/fsWeakReferenceConverter.cs.meta deleted file mode 100644 index 3c62221..0000000 --- a/Assets/Source/Converters/fsWeakReferenceConverter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ebce9d110c1f6744f9a17efb7097f566 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/Internal.meta b/Assets/Source/Internal.meta deleted file mode 100644 index 90ff9a3..0000000 --- a/Assets/Source/Internal.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 3773692a867995d489411837599e3761 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/Internal/fsCyclicReferenceManager.cs b/Assets/Source/Internal/fsCyclicReferenceManager.cs deleted file mode 100644 index 2a7e3ac..0000000 --- a/Assets/Source/Internal/fsCyclicReferenceManager.cs +++ /dev/null @@ -1,90 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Runtime.CompilerServices; - -namespace FullSerializer.Internal { - public class fsCyclicReferenceManager { - // We use the default ReferenceEquals when comparing two objects because - // custom objects may override equals methods. These overriden equals may - // treat equals differently; we want to serialize/deserialize the object - // graph *identically* to how it currently exists. - class ObjectReferenceEqualityComparator : IEqualityComparer { - bool IEqualityComparer.Equals(object x, object y) { - return ReferenceEquals(x, y); - } - - int IEqualityComparer.GetHashCode(object obj) { - return RuntimeHelpers.GetHashCode(obj); - } - - public static readonly IEqualityComparer Instance = new ObjectReferenceEqualityComparator(); - } - - private Dictionary _objectIds = new Dictionary(ObjectReferenceEqualityComparator.Instance); - private int _nextId; - - private Dictionary _marked = new Dictionary(); - private int _depth; - - public void Enter() { - _depth++; - } - - public bool Exit() { - _depth--; - - if (_depth == 0) { - _objectIds = new Dictionary(ObjectReferenceEqualityComparator.Instance); - _nextId = 0; - _marked = new Dictionary(); - } - - if (_depth < 0) { - _depth = 0; - throw new InvalidOperationException("Internal Error - Mismatched Enter/Exit"); - } - - return _depth == 0; - } - - public object GetReferenceObject(int id) { - if (_marked.ContainsKey(id) == false) { - throw new InvalidOperationException("Internal Deserialization Error - Object " + - "definition has not been encountered for object with id=" + id + - "; have you reordered or modified the serialized data? If this is an issue " + - "with an unmodified Full Serializer implementation and unmodified serialization " + - "data, please report an issue with an included test case."); - } - - return _marked[id]; - } - - public void AddReferenceWithId(int id, object reference) { - _marked[id] = reference; - } - - public int GetReferenceId(object item) { - int id; - if (_objectIds.TryGetValue(item, out id) == false) { - id = _nextId++; - _objectIds[item] = id; - } - return id; - } - - public bool IsReference(object item) { - return _marked.ContainsKey(GetReferenceId(item)); - } - - public void MarkSerialized(object item) { - int referenceId = GetReferenceId(item); - - if (_marked.ContainsKey(referenceId)) { - throw new InvalidOperationException("Internal Error - " + item + - " has already been marked as serialized"); - } - - _marked[referenceId] = item; - } - } -} \ No newline at end of file diff --git a/Assets/Source/Internal/fsCyclicReferenceManager.cs.meta b/Assets/Source/Internal/fsCyclicReferenceManager.cs.meta deleted file mode 100644 index e1f59f2..0000000 --- a/Assets/Source/Internal/fsCyclicReferenceManager.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: c34d55229bfe53d47a9ea7cf23687186 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/Internal/fsOption.cs b/Assets/Source/Internal/fsOption.cs deleted file mode 100644 index 02459e3..0000000 --- a/Assets/Source/Internal/fsOption.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System; - -namespace FullSerializer.Internal { - /// - /// Simple option type. This is akin to nullable types. - /// - public struct fsOption { - private bool _hasValue; - private T _value; - - public bool HasValue { - get { return _hasValue; } - } - public bool IsEmpty { - get { return _hasValue == false; } - } - public T Value { - get { - if (IsEmpty) throw new InvalidOperationException("fsOption is empty"); - return _value; - } - } - - public fsOption(T value) { - _hasValue = true; - _value = value; - } - - public static fsOption Empty; - } - - public static class fsOption { - public static fsOption Just(T value) { - return new fsOption(value); - } - } -} \ No newline at end of file diff --git a/Assets/Source/Internal/fsOption.cs.meta b/Assets/Source/Internal/fsOption.cs.meta deleted file mode 100644 index f19b7c8..0000000 --- a/Assets/Source/Internal/fsOption.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ec455db28b0ad7e4095c55696c9c630f -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/Internal/fsPortableReflection.cs b/Assets/Source/Internal/fsPortableReflection.cs deleted file mode 100644 index e6c3df0..0000000 --- a/Assets/Source/Internal/fsPortableReflection.cs +++ /dev/null @@ -1,400 +0,0 @@ -#if !UNITY_EDITOR && UNITY_METRO && !ENABLE_IL2CPP -#define USE_TYPEINFO -#if !UNITY_WINRT_10_0 -#define USE_TYPEINFO_EXTENSIONS -#endif -#endif - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; - -#if USE_TYPEINFO -namespace System { - public static class AssemblyExtensions { -#if USE_TYPEINFO_EXTENSIONS - public static Type[] GetTypes(this Assembly assembly) { - TypeInfo[] infos = assembly.DefinedTypes.ToArray(); - Type[] types = new Type[infos.Length]; - for (int i = 0; i < infos.Length; ++i) { - types[i] = infos[i].AsType(); - } - return types; - } -#endif - - public static Type GetType(this Assembly assembly, string name, bool throwOnError) { - var types = assembly.GetTypes(); - for (int i = 0; i < types.Length; ++i) { - if (types[i].Name == name) { - return types[i]; - } - } - - if (throwOnError) throw new Exception("Type " + name + " was not found"); - return null; - } - } -} -#endif - -namespace FullSerializer.Internal { - /// - /// This wraps reflection types so that it is portable across different Unity runtimes. - /// - public static class fsPortableReflection { - public static Type[] EmptyTypes = { }; - -#region Attribute Queries -#if USE_TYPEINFO - public static TAttribute GetAttribute(Type type) - where TAttribute : Attribute { - - return GetAttribute(type.GetTypeInfo()); - } - - public static Attribute GetAttribute(Type type, Type attributeType) { - return GetAttribute(type.GetTypeInfo(), attributeType, /*shouldCache:*/false); - } - - public static bool HasAttribute(Type type, Type attributeType) { - return GetAttribute(type, attributeType) != null; - } -#endif - - /// - /// Returns true if the given attribute is defined on the given element. - /// - public static bool HasAttribute(MemberInfo element) { - return HasAttribute(element, typeof(TAttribute)); - } - - /// - /// Returns true if the given attribute is defined on the given element. - /// - public static bool HasAttribute(MemberInfo element, bool shouldCache) { - return HasAttribute(element, typeof(TAttribute), shouldCache); - } - - /// - /// Returns true if the given attribute is defined on the given element. - /// - public static bool HasAttribute(MemberInfo element, Type attributeType) { - return HasAttribute(element, attributeType, true); - } - - /// - /// Returns true if the given attribute is defined on the given element. - /// - public static bool HasAttribute(MemberInfo element, Type attributeType, bool shouldCache) { - return element.IsDefined(attributeType, true); - } - - /// - /// Fetches the given attribute from the given MemberInfo. This method applies caching - /// and is allocation free (after caching has been performed). - /// - /// The MemberInfo the get the attribute from. - /// The type of attribute to fetch. - /// The attribute or null. - public static Attribute GetAttribute(MemberInfo element, Type attributeType, bool shouldCache) { - var query = new AttributeQuery { - MemberInfo = element, - AttributeType = attributeType - }; - - Attribute attribute; - if (_cachedAttributeQueries.TryGetValue(query, out attribute) == false) { - var attributes = element.GetCustomAttributes(attributeType, /*inherit:*/ true); - if (attributes.Length > 0) - attribute = (Attribute)attributes[0]; - if (shouldCache) - _cachedAttributeQueries[query] = attribute; - } - - return attribute; - } - - /// - /// Fetches the given attribute from the given MemberInfo. - /// - /// The type of attribute to fetch. - /// The MemberInfo to get the attribute from. - /// Should this computation be cached? If this is the only time it will ever be done, don't bother caching. - /// The attribute or null. - public static TAttribute GetAttribute(MemberInfo element, bool shouldCache) - where TAttribute : Attribute { - - return (TAttribute)GetAttribute(element, typeof(TAttribute), shouldCache); - } - public static TAttribute GetAttribute(MemberInfo element) - where TAttribute : Attribute { - return GetAttribute(element, /*shouldCache:*/true); - } - private struct AttributeQuery { - public MemberInfo MemberInfo; - public Type AttributeType; - } - private static IDictionary _cachedAttributeQueries = - new Dictionary(new AttributeQueryComparator()); - private class AttributeQueryComparator : IEqualityComparer { - public bool Equals(AttributeQuery x, AttributeQuery y) { - return - x.MemberInfo == y.MemberInfo && - x.AttributeType == y.AttributeType; - } - - public int GetHashCode(AttributeQuery obj) { - return - obj.MemberInfo.GetHashCode() + - (17 * obj.AttributeType.GetHashCode()); - } - } -#endregion - -#if !USE_TYPEINFO - private static BindingFlags DeclaredFlags = - BindingFlags.NonPublic | - BindingFlags.Public | - BindingFlags.Instance | - BindingFlags.Static | - BindingFlags.DeclaredOnly; -#endif - - public static PropertyInfo GetDeclaredProperty(this Type type, string propertyName) { - var props = GetDeclaredProperties(type); - - for (int i = 0; i < props.Length; ++i) { - if (props[i].Name == propertyName) { - return props[i]; - } - } - - return null; - } - - public static MethodInfo GetDeclaredMethod(this Type type, string methodName) { - var methods = GetDeclaredMethods(type); - - for (int i = 0; i < methods.Length; ++i) { - if (methods[i].Name == methodName) { - return methods[i]; - } - } - - return null; - } - - - public static ConstructorInfo GetDeclaredConstructor(this Type type, Type[] parameters) { - var ctors = GetDeclaredConstructors(type); - - for (int i = 0; i < ctors.Length; ++i) { - var ctor = ctors[i]; - var ctorParams = ctor.GetParameters(); - - if (parameters.Length != ctorParams.Length) continue; - - for (int j = 0; j < ctorParams.Length; ++j) { - // require an exact match - if (ctorParams[j].ParameterType != parameters[j]) continue; - } - - return ctor; - } - - return null; - } - - public static ConstructorInfo[] GetDeclaredConstructors(this Type type) { -#if USE_TYPEINFO - return type.GetTypeInfo().DeclaredConstructors.ToArray(); -#else - return type.GetConstructors(DeclaredFlags); -#endif - } - - public static MemberInfo[] GetFlattenedMember(this Type type, string memberName) { - var result = new List(); - - while (type != null) { - var members = GetDeclaredMembers(type); - - for (int i = 0; i < members.Length; ++i) { - if (members[i].Name == memberName) { - result.Add(members[i]); - } - } - - type = type.Resolve().BaseType; - } - - return result.ToArray(); - } - - public static MethodInfo GetFlattenedMethod(this Type type, string methodName) { - while (type != null) { - var methods = GetDeclaredMethods(type); - - for (int i = 0; i < methods.Length; ++i) { - if (methods[i].Name == methodName) { - return methods[i]; - } - } - - type = type.Resolve().BaseType; - } - - return null; - } - - public static IEnumerable GetFlattenedMethods(this Type type, string methodName) { - while (type != null) { - var methods = GetDeclaredMethods(type); - - for (int i = 0; i < methods.Length; ++i) { - if (methods[i].Name == methodName) { - yield return methods[i]; - } - } - - type = type.Resolve().BaseType; - } - } - - public static PropertyInfo GetFlattenedProperty(this Type type, string propertyName) { - while (type != null) { - var properties = GetDeclaredProperties(type); - - for (int i = 0; i < properties.Length; ++i) { - if (properties[i].Name == propertyName) { - return properties[i]; - } - } - - type = type.Resolve().BaseType; - } - - return null; - } - - public static MemberInfo GetDeclaredMember(this Type type, string memberName) { - var members = GetDeclaredMembers(type); - - for (int i = 0; i < members.Length; ++i) { - if (members[i].Name == memberName) { - return members[i]; - } - } - - return null; - } - - public static MethodInfo[] GetDeclaredMethods(this Type type) { -#if USE_TYPEINFO - return type.GetTypeInfo().DeclaredMethods.ToArray(); -#else - return type.GetMethods(DeclaredFlags); -#endif - } - - public static PropertyInfo[] GetDeclaredProperties(this Type type) { -#if USE_TYPEINFO - return type.GetTypeInfo().DeclaredProperties.ToArray(); -#else - return type.GetProperties(DeclaredFlags); -#endif - } - - public static FieldInfo[] GetDeclaredFields(this Type type) { -#if USE_TYPEINFO - return type.GetTypeInfo().DeclaredFields.ToArray(); -#else - return type.GetFields(DeclaredFlags); -#endif - } - - public static MemberInfo[] GetDeclaredMembers(this Type type) { -#if USE_TYPEINFO - return type.GetTypeInfo().DeclaredMembers.ToArray(); -#else - return type.GetMembers(DeclaredFlags); -#endif - } - - public static MemberInfo AsMemberInfo(Type type) { -#if USE_TYPEINFO - return type.GetTypeInfo(); -#else - return type; -#endif - } - - public static bool IsType(MemberInfo member) { -#if USE_TYPEINFO - return member is TypeInfo; -#else - return member is Type; -#endif - } - - public static Type AsType(MemberInfo member) { -#if USE_TYPEINFO - return ((TypeInfo)member).AsType(); -#else - return (Type)member; -#endif - } - -#if USE_TYPEINFO - public static TypeInfo Resolve(this Type type) { - return type.GetTypeInfo(); - } -#else - public static Type Resolve(this Type type) { - return type; - } -#endif - - -#region Extensions - -#if USE_TYPEINFO_EXTENSIONS - public static bool IsAssignableFrom(this Type parent, Type child) { - return parent.GetTypeInfo().IsAssignableFrom(child.GetTypeInfo()); - } - - public static Type GetElementType(this Type type) { - return type.GetTypeInfo().GetElementType(); - } - - public static MethodInfo GetSetMethod(this PropertyInfo member, bool nonPublic = false) { - // only public requested but the set method is not public - if (nonPublic == false && member.SetMethod != null && member.SetMethod.IsPublic == false) return null; - - return member.SetMethod; - } - - public static MethodInfo GetGetMethod(this PropertyInfo member, bool nonPublic = false) { - // only public requested but the set method is not public - if (nonPublic == false && member.GetMethod != null && member.GetMethod.IsPublic == false) return null; - - return member.GetMethod; - } - - public static MethodInfo GetBaseDefinition(this MethodInfo method) { - return method.GetRuntimeBaseDefinition(); - } - - public static Type[] GetInterfaces(this Type type) { - return type.GetTypeInfo().ImplementedInterfaces.ToArray(); - } - - public static Type[] GetGenericArguments(this Type type) { - return type.GetTypeInfo().GenericTypeArguments.ToArray(); - } -#endif -#endregion - } -} \ No newline at end of file diff --git a/Assets/Source/Internal/fsPortableReflection.cs.meta b/Assets/Source/Internal/fsPortableReflection.cs.meta deleted file mode 100644 index bebfe60..0000000 --- a/Assets/Source/Internal/fsPortableReflection.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 917955f7b7d77724d8abc90bd462de25 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/Internal/fsTypeExtensions.cs b/Assets/Source/Internal/fsTypeExtensions.cs deleted file mode 100644 index b334121..0000000 --- a/Assets/Source/Internal/fsTypeExtensions.cs +++ /dev/null @@ -1,78 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -#if !UNITY_EDITOR && UNITY_WSA -// For System.Reflection.TypeExtensions -using System.Reflection; -// For Reflection Extensions in non-win10 builds. -using FullSerializer.Internal; -#endif - -namespace FullSerializer { - public static class fsTypeExtensions { - /// - /// Returns a pretty name for the type in the style of one that you'd see in C# without the namespace. - /// - public static string CSharpName(this Type type) { - return CSharpName(type, /*includeNamespace:*/false); - } - - public static string CSharpName(this Type type, bool includeNamespace, bool ensureSafeDeclarationName) { - var name = CSharpName(type, includeNamespace); - if (ensureSafeDeclarationName) name = name.Replace('>', '_').Replace('<', '_').Replace('.', '_'); - return name; - } - - /// - /// Returns a pretty name for the type in the style of one that you'd see in C#. - /// - /// Should the name include namespaces? - public static string CSharpName(this Type type, bool includeNamespace) { - // we special case some of the common type names - if (type == typeof(void)) return "void"; - if (type == typeof(int)) return "int"; - if (type == typeof(float)) return "float"; - if (type == typeof(bool)) return "bool"; - if (type == typeof(double)) return "double"; - if (type == typeof(string)) return "string"; - - // Generic parameter, ie, T in Okay - // We special-case this logic otherwise we will recurse on the T - if (type.IsGenericParameter) { - return type.ToString(); - } - - string name = ""; - - var genericArguments = (IEnumerable)type.GetGenericArguments(); - if (type.IsNested) { - name += type.DeclaringType.CSharpName() + "."; - - // The declaring type generic parameters are considered part of the nested types generic - // parameters so we need to remove them, otherwise it will get included again. - // - // Say we have type `class Parent { class Child {} }` - // If we did not do the removal, then we would output Parent.Child, but we really want - // to output Parent.Child - if (type.DeclaringType.GetGenericArguments().Length > 0) { - genericArguments = genericArguments.Skip(type.DeclaringType.GetGenericArguments().Length); - } - } - - if (genericArguments.Any() == false) { - name += type.Name; - } - else { - name += type.Name.Substring(0, type.Name.IndexOf('`')); - name += "<" + String.Join(",", genericArguments.Select(t => CSharpName(t, includeNamespace)).ToArray()) + ">"; - } - - if (includeNamespace && type.Namespace != null) { - name = type.Namespace + "." + name; - } - - return name; - } - } -} \ No newline at end of file diff --git a/Assets/Source/Internal/fsTypeExtensions.cs.meta b/Assets/Source/Internal/fsTypeExtensions.cs.meta deleted file mode 100644 index 6f6f0b9..0000000 --- a/Assets/Source/Internal/fsTypeExtensions.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 34f8987a390a2ee488a60e2bc91e9614 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/Internal/fsVersionManager.cs b/Assets/Source/Internal/fsVersionManager.cs deleted file mode 100644 index ac2a618..0000000 --- a/Assets/Source/Internal/fsVersionManager.cs +++ /dev/null @@ -1,132 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Reflection; - -namespace FullSerializer.Internal { - public static class fsVersionManager { - private static readonly Dictionary> _cache = new Dictionary>(); - - public static fsResult GetVersionImportPath(string currentVersion, fsVersionedType targetVersion, out List path) { - path = new List(); - - if (GetVersionImportPathRecursive(path, currentVersion, targetVersion) == false) { - return fsResult.Fail("There is no migration path from \"" + currentVersion + "\" to \"" + targetVersion.VersionString + "\""); - } - - path.Add(targetVersion); - return fsResult.Success; - } - - private static bool GetVersionImportPathRecursive(List path, string currentVersion, fsVersionedType current) { - for (int i = 0; i < current.Ancestors.Length; ++i) { - fsVersionedType ancestor = current.Ancestors[i]; - - if (ancestor.VersionString == currentVersion || - GetVersionImportPathRecursive(path, currentVersion, ancestor)) { - - path.Add(ancestor); - return true; - } - } - - return false; - } - - public static fsOption GetVersionedType(Type type) { - fsOption optionalVersionedType; - - if (_cache.TryGetValue(type, out optionalVersionedType) == false) { - var attr = fsPortableReflection.GetAttribute(type); - - if (attr != null) { - if (string.IsNullOrEmpty(attr.VersionString) == false || attr.PreviousModels != null) { - // Version string must be provided - if (attr.PreviousModels != null && string.IsNullOrEmpty(attr.VersionString)) { - throw new Exception("fsObject attribute on " + type + " contains a PreviousModels specifier - it must also include a VersionString modifier"); - } - - // Map the ancestor types into versioned types - fsVersionedType[] ancestors = new fsVersionedType[attr.PreviousModels != null ? attr.PreviousModels.Length : 0]; - for (int i = 0; i < ancestors.Length; ++i) { - fsOption ancestorType = GetVersionedType(attr.PreviousModels[i]); - if (ancestorType.IsEmpty) { - throw new Exception("Unable to create versioned type for ancestor " + ancestorType + "; please add an [fsObject(VersionString=\"...\")] attribute"); - } - ancestors[i] = ancestorType.Value; - } - - // construct the actual versioned type instance - fsVersionedType versionedType = new fsVersionedType { - Ancestors = ancestors, - VersionString = attr.VersionString, - ModelType = type - }; - - // finally, verify that the versioned type passes some sanity checks - VerifyUniqueVersionStrings(versionedType); - VerifyConstructors(versionedType); - - optionalVersionedType = fsOption.Just(versionedType); - } - } - - _cache[type] = optionalVersionedType; - } - - return optionalVersionedType; - } - - /// - /// Verifies that the given type has constructors to migrate from all ancestor types. - /// - private static void VerifyConstructors(fsVersionedType type) { - ConstructorInfo[] publicConstructors = type.ModelType.GetDeclaredConstructors(); - - for (int i = 0; i < type.Ancestors.Length; ++i) { - Type requiredConstructorType = type.Ancestors[i].ModelType; - - bool found = false; - for (int j = 0; j < publicConstructors.Length; ++j) { - var parameters = publicConstructors[j].GetParameters(); - if (parameters.Length == 1 && parameters[0].ParameterType == requiredConstructorType) { - found = true; - break; - } - } - - if (found == false) { - throw new fsMissingVersionConstructorException(type.ModelType, requiredConstructorType); - } - } - } - - /// - /// Verifies that the given version graph contains only unique versions. - /// - private static void VerifyUniqueVersionStrings(fsVersionedType type) { - // simple tree traversal - - var found = new Dictionary(); - - var remaining = new Queue(); - remaining.Enqueue(type); - - while (remaining.Count > 0) { - fsVersionedType item = remaining.Dequeue(); - - // Verify we do not already have the version string. Take into account that we're not just - // comparing the same model twice, since we can have a valid import graph that has the same - // model multiple times. - if (found.ContainsKey(item.VersionString) && found[item.VersionString] != item.ModelType) { - throw new fsDuplicateVersionNameException(found[item.VersionString], item.ModelType, item.VersionString); - } - found[item.VersionString] = item.ModelType; - - // scan the ancestors as well - foreach (var ancestor in item.Ancestors) { - remaining.Enqueue(ancestor); - } - } - } - } -} \ No newline at end of file diff --git a/Assets/Source/Internal/fsVersionManager.cs.meta b/Assets/Source/Internal/fsVersionManager.cs.meta deleted file mode 100644 index 6c69697..0000000 --- a/Assets/Source/Internal/fsVersionManager.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 6e2cbf05d62993b4c900b6f0568b5525 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/Internal/fsVersionedType.cs b/Assets/Source/Internal/fsVersionedType.cs deleted file mode 100644 index 7bda5b7..0000000 --- a/Assets/Source/Internal/fsVersionedType.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System; - -namespace FullSerializer.Internal { - public struct fsVersionedType { - /// - /// The direct ancestors that this type can import. - /// - public fsVersionedType[] Ancestors; - - /// - /// The identifying string that is unique among all ancestors. - /// - public string VersionString; - - /// - /// The modeling type that this versioned type maps back to. - /// - public Type ModelType; - - /// - /// Migrate from an instance of an ancestor. - /// - public object Migrate(object ancestorInstance) { - return Activator.CreateInstance(ModelType, ancestorInstance); - } - - public override string ToString() { - return "fsVersionedType [ModelType=" + ModelType + ", VersionString=" + VersionString + ", Ancestors.Length=" + Ancestors.Length + "]"; - } - - public static bool operator ==(fsVersionedType a, fsVersionedType b) { - return a.ModelType == b.ModelType; - } - - public static bool operator !=(fsVersionedType a, fsVersionedType b) { - return a.ModelType != b.ModelType; - } - - public override bool Equals(object obj) { - return - obj is fsVersionedType && - ModelType == ((fsVersionedType)obj).ModelType; - } - - public override int GetHashCode() { - return ModelType.GetHashCode(); - } - } -} \ No newline at end of file diff --git a/Assets/Source/Internal/fsVersionedType.cs.meta b/Assets/Source/Internal/fsVersionedType.cs.meta deleted file mode 100644 index 34b5ea4..0000000 --- a/Assets/Source/Internal/fsVersionedType.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 98a8b020907c059448da9798c38f201d -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/Reflection.meta b/Assets/Source/Reflection.meta deleted file mode 100644 index 3fbc63d..0000000 --- a/Assets/Source/Reflection.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: e45b6257da83c52429dcde2ab7b7c7e4 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/Reflection/fsMetaProperty.cs b/Assets/Source/Reflection/fsMetaProperty.cs deleted file mode 100644 index 1e7634e..0000000 --- a/Assets/Source/Reflection/fsMetaProperty.cs +++ /dev/null @@ -1,152 +0,0 @@ -using System; -using System.Reflection; - -namespace FullSerializer.Internal { - /// - /// A property or field on a MetaType. This unifies the FieldInfo and PropertyInfo classes. - /// - public class fsMetaProperty { - internal fsMetaProperty(fsConfig config, FieldInfo field) { - _memberInfo = field; - StorageType = field.FieldType; - MemberName = field.Name; - IsPublic = field.IsPublic; - IsReadOnly = field.IsInitOnly; - CanRead = true; - CanWrite = true; - - CommonInitialize(config); - } - - internal fsMetaProperty(fsConfig config, PropertyInfo property) { - _memberInfo = property; - StorageType = property.PropertyType; - MemberName = property.Name; - IsPublic = (property.GetGetMethod() != null && property.GetGetMethod().IsPublic) && - (property.GetSetMethod() != null && property.GetSetMethod().IsPublic); - IsReadOnly = false; - CanRead = property.CanRead; - CanWrite = property.CanWrite; - - CommonInitialize(config); - } - - private void CommonInitialize(fsConfig config) { - var attr = fsPortableReflection.GetAttribute(_memberInfo); - if (attr != null) { - JsonName = attr.Name; - OverrideConverterType = attr.Converter; - } - - if (string.IsNullOrEmpty(JsonName)) { - JsonName = config.GetJsonNameFromMemberName(MemberName, _memberInfo); - } - } - - /// - /// Internal handle to the reflected member. - /// - private MemberInfo _memberInfo; - - /// - /// The type of value that is stored inside of the property. For example, for an int field, - /// StorageType will be typeof(int). - /// - public Type StorageType { - get; - private set; - } - - /// - /// A custom fsBaseConverter instance to use for this field/property, if requested. This will be - /// null if the default converter selection algorithm should be used. This is specified using the - /// [fsObject] annotation with the Converter field. - /// - public Type OverrideConverterType { - get; - private set; - } - - /// - /// Can this property be read? - /// - public bool CanRead { - get; - private set; - } - - /// - /// Can this property be written to? - /// - public bool CanWrite { - get; - private set; - } - - /// - /// The serialized name of the property, as it should appear in JSON. - /// - public string JsonName { - get; - private set; - } - - /// - /// The name of the actual member. - /// - public string MemberName { - get; - private set; - } - - /// - /// Is this member public? - /// - public bool IsPublic { - get; - private set; - } - - /// - /// Is this type readonly? We can modify readonly properties using reflection, but not - /// using generated C#. - /// - public bool IsReadOnly { - get; private set; - } - - /// - /// Writes a value to the property that this MetaProperty represents, using given object - /// instance as the context. - /// - public void Write(object context, object value) { - FieldInfo field = _memberInfo as FieldInfo; - PropertyInfo property = _memberInfo as PropertyInfo; - - if (field != null) { - field.SetValue(context, value); - } - - else if (property != null) { - MethodInfo setMethod = property.GetSetMethod(/*nonPublic:*/ true); - if (setMethod != null) { - setMethod.Invoke(context, new object[] { value }); - } - } - } - - /// - /// Reads a value from the property that this MetaProperty represents, using the given - /// object instance as the context. - /// - public object Read(object context) { - if (_memberInfo is PropertyInfo) { - return ((PropertyInfo)_memberInfo).GetValue(context, new object[] { }); - } - - else { - return ((FieldInfo)_memberInfo).GetValue(context); - } - } - } -} \ No newline at end of file diff --git a/Assets/Source/Reflection/fsMetaProperty.cs.meta b/Assets/Source/Reflection/fsMetaProperty.cs.meta deleted file mode 100644 index 47efe4d..0000000 --- a/Assets/Source/Reflection/fsMetaProperty.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 9bb14b7a131d5a44693d3005bd480781 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/Reflection/fsMetaType.cs b/Assets/Source/Reflection/fsMetaType.cs deleted file mode 100644 index 34c7e58..0000000 --- a/Assets/Source/Reflection/fsMetaType.cs +++ /dev/null @@ -1,336 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Runtime.CompilerServices; -using FullSerializer.Internal; - -namespace FullSerializer { - /// - /// MetaType contains metadata about a type. This is used by the reflection serializer. - /// - public class fsMetaType { - private static Dictionary> _configMetaTypes = - new Dictionary>(); - - public static fsMetaType Get(fsConfig config, Type type) { - Dictionary metaTypes; - if (_configMetaTypes.TryGetValue(config, out metaTypes) == false) - metaTypes = _configMetaTypes[config] = new Dictionary(); - - fsMetaType metaType; - if (metaTypes.TryGetValue(type, out metaType) == false) { - metaType = new fsMetaType(config, type); - metaTypes[type] = metaType; - } - - return metaType; - } - - /// - /// Clears out the cached type results. Useful if some prior assumptions become invalid, ie, the default member - /// serialization mode. - /// - public static void ClearCache() { - _configMetaTypes = new Dictionary>(); - } - - private fsMetaType(fsConfig config, Type reflectedType) { - ReflectedType = reflectedType; - - List properties = new List(); - CollectProperties(config, properties, reflectedType); - Properties = properties.ToArray(); - } - - public Type ReflectedType; - - private static void CollectProperties(fsConfig config, List properties, Type reflectedType) { - // do we require a [SerializeField] or [fsProperty] attribute? - bool requireOptIn = config.DefaultMemberSerialization == fsMemberSerialization.OptIn; - bool requireOptOut = config.DefaultMemberSerialization == fsMemberSerialization.OptOut; - - fsObjectAttribute attr = fsPortableReflection.GetAttribute(reflectedType); - if (attr != null) { - requireOptIn = attr.MemberSerialization == fsMemberSerialization.OptIn; - requireOptOut = attr.MemberSerialization == fsMemberSerialization.OptOut; - } - - MemberInfo[] members = reflectedType.GetDeclaredMembers(); - foreach (var member in members) { - // We don't serialize members annotated with any of the ignore serialize attributes - if (config.IgnoreSerializeAttributes.Any(t => fsPortableReflection.HasAttribute(member, t))) { - continue; - } - - PropertyInfo property = member as PropertyInfo; - FieldInfo field = member as FieldInfo; - - // Early out if it's neither a field or a property, since we don't serialize anything else. - if (property == null && field == null) { - continue; - } - - // Skip properties if we don't want them, to avoid the cost of checking attributes. - if (property != null && !config.EnablePropertySerialization) { - continue; - } - - // If an opt-in annotation is required, then skip the property if it doesn't have one - // of the serialize attributes - if (requireOptIn && - !config.SerializeAttributes.Any(t => fsPortableReflection.HasAttribute(member, t))) { - - continue; - } - - // If an opt-out annotation is required, then skip the property *only if* it has one of - // the not serialize attributes - if (requireOptOut && - config.IgnoreSerializeAttributes.Any(t => fsPortableReflection.HasAttribute(member, t))) { - - continue; - } - - if (property != null) { - if (CanSerializeProperty(config, property, members, requireOptOut)) { - properties.Add(new fsMetaProperty(config, property)); - } - } - else if (field != null) { - if (CanSerializeField(config, field, requireOptOut)) { - properties.Add(new fsMetaProperty(config, field)); - } - } - } - - if (reflectedType.Resolve().BaseType != null) { - CollectProperties(config, properties, reflectedType.Resolve().BaseType); - } - } - - private static bool IsAutoProperty(PropertyInfo property, MemberInfo[] members) { - return - property.CanWrite && property.CanRead && - fsPortableReflection.HasAttribute( - property.GetGetMethod(), typeof(CompilerGeneratedAttribute), /*shouldCache:*/false); - } - - /// - /// Returns if the given property should be serialized. - /// - /// Should a property without any annotations be serialized? - private static bool CanSerializeProperty(fsConfig config, PropertyInfo property, MemberInfo[] members, bool annotationFreeValue) { - // We don't serialize delegates - if (typeof(Delegate).IsAssignableFrom(property.PropertyType)) { - return false; - } - - var publicGetMethod = property.GetGetMethod(/*nonPublic:*/ false); - var publicSetMethod = property.GetSetMethod(/*nonPublic:*/ false); - - // We do not bother to serialize static fields. - if ((publicGetMethod != null && publicGetMethod.IsStatic) || - (publicSetMethod != null && publicSetMethod.IsStatic)) { - return false; - } - - // Never serialize indexers. I can't think of a sane way to serialize/deserialize them, and they're normally wrappers around other fields anyway... - if (property.GetIndexParameters().Length > 0) { - return false; - } - - // If a property is annotated with one of the serializable attributes, then it should - // it should definitely be serialized. - // - // NOTE: We place this override check *after* the static check, because we *never* - // allow statics to be serialized. - if (config.SerializeAttributes.Any(t => fsPortableReflection.HasAttribute(property, t))) { - return true; - } - - // If the property cannot be both read and written to, we are not going to serialize it - // regardless of the default serialization mode - if (property.CanRead == false || property.CanWrite == false) { - return false; - } - - // Depending on the configuration options, check whether the property is automatic - // and if it has a public setter to determine whether it should be serialized - if ((publicGetMethod != null && (config.SerializeNonPublicSetProperties || publicSetMethod != null)) && - (config.SerializeNonAutoProperties || IsAutoProperty(property, members))) { - return true; - } - - - // Otherwise, we don't bother with serialization - return annotationFreeValue; - } - - private static bool CanSerializeField(fsConfig config, FieldInfo field, bool annotationFreeValue) { - // We don't serialize delegates - if (typeof(Delegate).IsAssignableFrom(field.FieldType)) { - return false; - } - - // We don't serialize compiler generated fields. - if (field.IsDefined(typeof(CompilerGeneratedAttribute), false)) { - return false; - } - - // We don't serialize static fields - if (field.IsStatic) { - return false; - } - - // We want to serialize any fields annotated with one of the serialize attributes. - // - // NOTE: This occurs *after* the static check, because we *never* want to serialize - // static fields. - if (config.SerializeAttributes.Any(t => fsPortableReflection.HasAttribute(field, t))) { - return true; - } - - // We use !IsPublic because that also checks for internal, protected, and private. - if (!annotationFreeValue && !field.IsPublic) { - return false; - } - - return true; - } - - /// - /// Attempt to emit an AOT compiled direct converter for this type. - /// - /// True if AOT data was emitted, false otherwise. - public bool EmitAotData() { - if (_hasEmittedAotData == false) { - _hasEmittedAotData = true; - - // NOTE: - // Even if the type has derived types, we can still generate a direct converter for it. - // Direct converters are not used for inherited types, so the reflected converter or something - // similar will be used for the derived type instead of our AOT compiled one. - - for (int i = 0; i < Properties.Length; ++i) { - // Cannot AOT compile since we need to public member access. - if (Properties[i].IsPublic == false) - return false; - // Cannot AOT compile since readonly members can only be modified using reflection. - if (Properties[i].IsReadOnly) - return false; - } - - // Cannot AOT compile since we need a default ctor. - if (HasDefaultConstructor == false) - return false; - - fsAotCompilationManager.AddAotCompilation(ReflectedType, Properties, _isDefaultConstructorPublic); - return true; - } - - return false; - } - private bool _hasEmittedAotData; - - public fsMetaProperty[] Properties { - get; - private set; - } - - /// - /// Returns true if the type represented by this metadata contains a default constructor. - /// - public bool HasDefaultConstructor { - get { - if (_hasDefaultConstructorCache.HasValue == false) { - // arrays are considered to have a default constructor - if (ReflectedType.Resolve().IsArray) { - _hasDefaultConstructorCache = true; - _isDefaultConstructorPublic = true; - } - - // value types (ie, structs) always have a default constructor - else if (ReflectedType.Resolve().IsValueType) { - _hasDefaultConstructorCache = true; - _isDefaultConstructorPublic = true; - } - - else { - // consider private constructors as well - var ctor = ReflectedType.GetDeclaredConstructor(fsPortableReflection.EmptyTypes); - _hasDefaultConstructorCache = ctor != null; - if (ctor != null) { - _isDefaultConstructorPublic = ctor.IsPublic; - } - } - } - - return _hasDefaultConstructorCache.Value; - } - } - private bool? _hasDefaultConstructorCache; - private bool _isDefaultConstructorPublic; - - /// - /// Creates a new instance of the type that this metadata points back to. If this type has a - /// default constructor, then Activator.CreateInstance will be used to construct the type - /// (or Array.CreateInstance if it an array). Otherwise, an uninitialized object created via - /// FormatterServices.GetSafeUninitializedObject is used to construct the instance. - /// - public object CreateInstance() { - if (ReflectedType.Resolve().IsInterface || ReflectedType.Resolve().IsAbstract) { - throw new Exception("Cannot create an instance of an interface or abstract type for " + ReflectedType); - } - -#if !NO_UNITY - // Unity requires special construction logic for types that derive from - // ScriptableObject. - if (typeof(UnityEngine.ScriptableObject).IsAssignableFrom(ReflectedType)) { - return UnityEngine.ScriptableObject.CreateInstance(ReflectedType); - } -#endif - - // Strings don't have default constructors but also fail when run through - // FormatterSerivces.GetSafeUninitializedObject - if (typeof(string) == ReflectedType) { - return string.Empty; - } - - if (HasDefaultConstructor == false) { -#if !UNITY_EDITOR && (UNITY_WEBPLAYER || UNITY_WP8 || UNITY_METRO) - throw new InvalidOperationException("The selected Unity platform requires " + - ReflectedType.FullName + " to have a default constructor. Please add one."); -#else - return System.Runtime.Serialization.FormatterServices.GetSafeUninitializedObject(ReflectedType); -#endif - } - - if (ReflectedType.Resolve().IsArray) { - // we have to start with a size zero array otherwise it will have invalid data - // inside of it - return Array.CreateInstance(ReflectedType.GetElementType(), 0); - } - - try { -#if (!UNITY_EDITOR && (UNITY_METRO)) - // In WinRT/WinStore builds, Activator.CreateInstance(..., true) is broken - return Activator.CreateInstance(ReflectedType); -#else - return Activator.CreateInstance(ReflectedType, /*nonPublic:*/ true); -#endif - } -#if (!UNITY_EDITOR && (UNITY_METRO)) == false - catch (MissingMethodException e) { - throw new InvalidOperationException("Unable to create instance of " + ReflectedType + "; there is no default constructor", e); - } -#endif - catch (TargetInvocationException e) { - throw new InvalidOperationException("Constructor of " + ReflectedType + " threw an exception when creating an instance", e); - } - catch (MemberAccessException e) { - throw new InvalidOperationException("Unable to access constructor of " + ReflectedType, e); - } - } - } -} \ No newline at end of file diff --git a/Assets/Source/Reflection/fsMetaType.cs.meta b/Assets/Source/Reflection/fsMetaType.cs.meta deleted file mode 100644 index 6ef9f54..0000000 --- a/Assets/Source/Reflection/fsMetaType.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: f5bc83526ccd76f4c877c4db426b7e9f -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/Reflection/fsReflectionUtility.cs b/Assets/Source/Reflection/fsReflectionUtility.cs deleted file mode 100644 index 9dc29e3..0000000 --- a/Assets/Source/Reflection/fsReflectionUtility.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System; - -#if !UNITY_EDITOR && UNITY_WSA -// For System.Reflection.TypeExtensions -using System.Reflection; -#endif - -namespace FullSerializer.Internal { - public static class fsReflectionUtility { - /// - /// Searches for a particular implementation of the given interface type inside of the type. - /// This is particularly useful if the interface type is an open type, ie, typeof(IFace{}), - /// because this method will then return IFace{} but with appropriate type parameters - /// inserted. - /// - /// The base type to search for interface - /// The interface type to search for. Can be an open generic - /// type. - /// The actual interface type that the type contains, or null if there is no - /// implementation of the given interfaceType on type. - public static Type GetInterface(Type type, Type interfaceType) { - if (interfaceType.Resolve().IsGenericType && - interfaceType.Resolve().IsGenericTypeDefinition == false) { - - throw new ArgumentException("GetInterface requires that if the interface " + - "type is generic, then it must be the generic type definition, not a " + - "specific generic type instantiation"); - }; - - while (type != null) { - foreach (var iface in type.GetInterfaces()) { - if (iface.Resolve().IsGenericType) { - if (interfaceType == iface.GetGenericTypeDefinition()) { - return iface; - } - } - - else if (interfaceType == iface) { - return iface; - } - } - - type = type.Resolve().BaseType; - } - - return null; - } - } -} \ No newline at end of file diff --git a/Assets/Source/Reflection/fsReflectionUtility.cs.meta b/Assets/Source/Reflection/fsReflectionUtility.cs.meta deleted file mode 100644 index 3e5c90d..0000000 --- a/Assets/Source/Reflection/fsReflectionUtility.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 0b4280b980c130b42a320f8b5fdfeff5 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/Reflection/fsTypeCache.cs b/Assets/Source/Reflection/fsTypeCache.cs deleted file mode 100644 index 79ea835..0000000 --- a/Assets/Source/Reflection/fsTypeCache.cs +++ /dev/null @@ -1,167 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Reflection; - -namespace FullSerializer.Internal { - /// - /// Caches type name to type lookups. Type lookups occur in all loaded assemblies. - /// - public static class fsTypeCache { - /// - /// Cache from fully qualified type name to type instances. - /// - // TODO: verify that type names will be unique - private static Dictionary _cachedTypes = new Dictionary(); - - /// - /// Assemblies indexed by their name. - /// - private static Dictionary _assembliesByName; - - /// - /// A list of assemblies, by index. - /// - private static List _assembliesByIndex; - - static fsTypeCache() { - // Setup assembly references so searching and the like resolves correctly. - _assembliesByName = new Dictionary(); - _assembliesByIndex = new List(); - -#if (!UNITY_EDITOR && UNITY_METRO && !ENABLE_IL2CPP) // no AppDomain on WinRT - var assembly = typeof(object).GetTypeInfo().Assembly; - _assembliesByName[assembly.FullName] = assembly; - _assembliesByIndex.Add(assembly); -#else - foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { - _assembliesByName[assembly.FullName] = assembly; - _assembliesByIndex.Add(assembly); - } -#endif - - _cachedTypes = new Dictionary(); - -#if !(UNITY_WP8 || UNITY_METRO) // AssemblyLoad events are not supported on these platforms - AppDomain.CurrentDomain.AssemblyLoad += OnAssemblyLoaded; -#endif - } - -#if !(UNITY_WP8 || UNITY_METRO) // AssemblyLoad events are not supported on these platforms - private static void OnAssemblyLoaded(object sender, AssemblyLoadEventArgs args) { - _assembliesByName[args.LoadedAssembly.FullName] = args.LoadedAssembly; - _assembliesByIndex.Add(args.LoadedAssembly); - - _cachedTypes = new Dictionary(); - } -#endif - - /// - /// Does a direct lookup for the given type, ie, goes directly to the assembly identified by - /// assembly name and finds it there. - /// - /// The assembly to find the type in. - /// The name of the type. - /// The found type. - /// True if the type was found, false otherwise. - private static bool TryDirectTypeLookup(string assemblyName, string typeName, out Type type) { - if (assemblyName != null) { - Assembly assembly; - if (_assembliesByName.TryGetValue(assemblyName, out assembly)) { - type = assembly.GetType(typeName, /*throwOnError:*/ false); - return type != null; - } - } - - type = null; - return false; - } - - /// - /// Tries to do an indirect type lookup by scanning through every loaded assembly until the - /// type is found in one of them. - /// - /// The name of the type. - /// The found type. - /// True if the type was found, false otherwise. - private static bool TryIndirectTypeLookup(string typeName, out Type type) { - // There used to be a foreach loop through the value keys of the _assembliesByName - // dictionary. However, during that loop assembly loads could occur, causing an - // OutOfSync exception. To resolve that, we just iterate through the assemblies by - // index. - - int i = 0; - while (i < _assembliesByIndex.Count) { - Assembly assembly = _assembliesByIndex[i]; - - // try GetType; should be fast - type = assembly.GetType(typeName); - if (type != null) { - return true; - } - ++i; - } - - i = 0; - // This code here is slow and is just here as a fallback - while (i < _assembliesByIndex.Count) { - Assembly assembly = _assembliesByIndex[i]; - - // private type or similar; go through the slow path and check every type's full - // name - foreach (var foundType in assembly.GetTypes()) { - if (foundType.FullName == typeName) { - type = foundType; - return true; - } - } - ++i; - } - - type = null; - return false; - } - - /// - /// Removes any cached type lookup results. - /// - public static void Reset() { - _cachedTypes = new Dictionary(); - } - - /// - /// Find a type with the given name. An exception is thrown if no type with the given name - /// can be found. This method searches all currently loaded assemblies for the given type. If the type cannot - /// be found, then null will be returned. - /// - /// The fully qualified name of the type. - public static Type GetType(string name) { - return GetType(name, null); - } - - /// - /// Find a type with the given name. An exception is thrown if no type with the given name - /// can be found. This method searches all currently loaded assemblies for the given type. If the type cannot - /// be found, then null will be returned. - /// - /// The fully qualified name of the type. - /// A hint for the assembly to start the search with. Use null if unknown. - public static Type GetType(string name, string assemblyHint) { - if (string.IsNullOrEmpty(name)) { - return null; - } - - Type type; - if (_cachedTypes.TryGetValue(name, out type) == false) { - // if both the direct and indirect type lookups fail, then throw an exception - if (TryDirectTypeLookup(assemblyHint, name, out type) == false && - TryIndirectTypeLookup(name, out type) == false) { - } - - _cachedTypes[name] = type; - } - - return type; - } - } -} - diff --git a/Assets/Source/Reflection/fsTypeCache.cs.meta b/Assets/Source/Reflection/fsTypeCache.cs.meta deleted file mode 100644 index 262db74..0000000 --- a/Assets/Source/Reflection/fsTypeCache.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 233490e64cba5c2408b26b49bd077483 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/fsAotCompilationManager.cs b/Assets/Source/fsAotCompilationManager.cs deleted file mode 100644 index 79c811b..0000000 --- a/Assets/Source/fsAotCompilationManager.cs +++ /dev/null @@ -1,132 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using FullSerializer.Internal; - -namespace FullSerializer { - /// - /// The AOT compilation manager - /// - public class fsAotCompilationManager { - /// - /// Ahead of time compilations that are available. The type maps to the object type the generated converter - /// will serialize/deserialize, and the string is the text content for a converter that will do the serialization. - /// - /// The generated serializer is completely independent and you don't need to do anything. Simply add the file to - /// your project and it'll get used instead of the reflection based one. - /// - public static Dictionary AvailableAotCompilations { - get { - for (int i = 0; i < _uncomputedAotCompilations.Count; ++i) { - var item = _uncomputedAotCompilations[i]; - _computedAotCompilations[item.Type] = GenerateDirectConverterForTypeInCSharp(item.Type, item.Members, item.IsConstructorPublic); - } - _uncomputedAotCompilations.Clear(); - - return _computedAotCompilations; - } - } - private static Dictionary _computedAotCompilations = new Dictionary(); - - private struct AotCompilation { - public Type Type; - public fsMetaProperty[] Members; - public bool IsConstructorPublic; - } - private static List _uncomputedAotCompilations = new List(); - - /// - /// This is a helper method that makes it simple to run an AOT compilation on the given type. - /// - /// The configuration to use when running AOT compilation. - /// The type to perform the AOT compilation on. - /// The AOT class. Add this C# code to your project. - /// True if AOT compilation was successful. - public static bool TryToPerformAotCompilation(fsConfig config, Type type, out string aotCompiledClassInCSharp) { - if (fsMetaType.Get(config, type).EmitAotData()) { - aotCompiledClassInCSharp = AvailableAotCompilations[type]; - return true; - } - - aotCompiledClassInCSharp = default(string); - return false; - } - - /// - /// Adds a new AOT compilation unit. - /// - /// The type of object we are AOT compiling. - /// The members on the object which will be serialized/deserialized. - public static void AddAotCompilation(Type type, fsMetaProperty[] members, bool isConstructorPublic) { - _uncomputedAotCompilations.Add(new AotCompilation { - Type = type, - Members = members, - IsConstructorPublic = isConstructorPublic - }); - } - - private static string GetConverterString(fsMetaProperty member) { - if (member.OverrideConverterType == null) - return "null"; - - return string.Format("typeof({0})", - member.OverrideConverterType.CSharpName(/*includeNamespace:*/ true)); - } - - /// - /// AOT compiles the object (in C#). - /// - private static string GenerateDirectConverterForTypeInCSharp(Type type, fsMetaProperty[] members, bool isConstructorPublic) { - var sb = new StringBuilder(); - string typeName = type.CSharpName(/*includeNamespace:*/ true); - string typeNameSafeDecl = type.CSharpName(true, true); - - sb.AppendLine("using System;"); - sb.AppendLine("using System.Collections.Generic;"); - sb.AppendLine(); - sb.AppendLine("namespace FullSerializer {"); - sb.AppendLine(" partial class fsConverterRegistrar {"); - sb.AppendLine(" public static Speedup." + typeNameSafeDecl + "_DirectConverter " + "Register_" + typeNameSafeDecl + ";"); - sb.AppendLine(" }"); - sb.AppendLine("}"); - sb.AppendLine(); - sb.AppendLine("namespace FullSerializer.Speedup {"); - sb.AppendLine(" public class " + typeNameSafeDecl + "_DirectConverter : fsDirectConverter<" + typeName + "> {"); - sb.AppendLine(" protected override fsResult DoSerialize(" + typeName + " model, Dictionary serialized) {"); - sb.AppendLine(" var result = fsResult.Success;"); - sb.AppendLine(); - foreach (var member in members) { - sb.AppendLine(" result += SerializeMember(serialized, " + GetConverterString(member) + ", \"" + member.JsonName + "\", model." + member.MemberName + ");"); - } - sb.AppendLine(); - sb.AppendLine(" return result;"); - sb.AppendLine(" }"); - sb.AppendLine(); - sb.AppendLine(" protected override fsResult DoDeserialize(Dictionary data, ref " + typeName + " model) {"); - sb.AppendLine(" var result = fsResult.Success;"); - sb.AppendLine(); - for (int i = 0; i < members.Length; ++i) { - var member = members[i]; - sb.AppendLine(" var t" + i + " = model." + member.MemberName + ";"); - sb.AppendLine(" result += DeserializeMember(data, " + GetConverterString(member) + ", \"" + member.JsonName + "\", out t" + i + ");"); - sb.AppendLine(" model." + member.MemberName + " = t" + i + ";"); - sb.AppendLine(); - } - sb.AppendLine(" return result;"); - sb.AppendLine(" }"); - sb.AppendLine(); - sb.AppendLine(" public override object CreateInstance(fsData data, Type storageType) {"); - if (isConstructorPublic) { - sb.AppendLine(" return new " + typeName + "();"); - } - else { - sb.AppendLine(" return Activator.CreateInstance(typeof(" + typeName + "), /*nonPublic:*/true);"); - } - sb.AppendLine(" }"); - sb.AppendLine(" }"); - sb.AppendLine("}"); - - return sb.ToString(); - } - } -} \ No newline at end of file diff --git a/Assets/Source/fsAotCompilationManager.cs.meta b/Assets/Source/fsAotCompilationManager.cs.meta deleted file mode 100644 index 5f09ec1..0000000 --- a/Assets/Source/fsAotCompilationManager.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 38f69a9d341a14246879983c2113fc43 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/fsBaseConverter.cs b/Assets/Source/fsBaseConverter.cs deleted file mode 100644 index 91293a5..0000000 --- a/Assets/Source/fsBaseConverter.cs +++ /dev/null @@ -1,119 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using FullSerializer.Internal; - -namespace FullSerializer { - /// - /// The serialization converter allows for customization of the serialization process. - /// - /// You do not want to derive from this class - there is no way to actually use it within - /// the serializer.. Instead, derive from either fsConverter or fsDirectConverter - public abstract class fsBaseConverter { - /// - /// The serializer that was owns this converter. - /// - public fsSerializer Serializer; - - /// - /// Construct an object instance that will be passed to TryDeserialize. This should **not** - /// deserialize the object. - /// - /// The data the object was serialized with. - /// The field/property type that is storing the instance. - /// An object instance - public virtual object CreateInstance(fsData data, Type storageType) { - if (RequestCycleSupport(storageType)) { - throw new InvalidOperationException("Please override CreateInstance for " + - GetType().FullName + "; the object graph for " + storageType + - " can contain potentially contain cycles, so separated instance creation " + - "is needed"); - } - - return storageType; - } - - /// - /// If true, then the serializer will support cyclic references with the given converted - /// type. - /// - /// The field/property type that is currently storing the object - /// that is being serialized. - public virtual bool RequestCycleSupport(Type storageType) { - if (storageType == typeof(string)) return false; - - return storageType.Resolve().IsClass || storageType.Resolve().IsInterface; - } - - /// - /// If true, then the serializer will include inheritance data for the given converter. - /// - /// The field/property type that is currently storing the object - /// that is being serialized. - public virtual bool RequestInheritanceSupport(Type storageType) { - return storageType.Resolve().IsSealed == false; - } - - /// - /// Serialize the actual object into the given data storage. - /// - /// The object instance to serialize. This will never be null. - /// The serialized state. - /// The field/property type that is storing this instance. - /// If serialization was successful. - public abstract fsResult TrySerialize(object instance, out fsData serialized, Type storageType); - - /// - /// Deserialize data into the object instance. - /// - /// Serialization data to deserialize from. - /// The object instance to deserialize into. - /// The field/property type that is storing the instance. - /// True if serialization was successful, false otherwise. - public abstract fsResult TryDeserialize(fsData data, ref object instance, Type storageType); - - protected fsResult FailExpectedType(fsData data, params fsDataType[] types) { - return fsResult.Fail(GetType().Name + " expected one of " + - string.Join(", ", types.Select(t => t.ToString()).ToArray()) + - " but got " + data.Type + " in " + data); - } - - protected fsResult CheckType(fsData data, fsDataType type) { - if (data.Type != type) { - return fsResult.Fail(GetType().Name + " expected " + type + " but got " + data.Type + " in " + data); - } - return fsResult.Success; - } - - protected fsResult CheckKey(fsData data, string key, out fsData subitem) { - return CheckKey(data.AsDictionary, key, out subitem); - } - - protected fsResult CheckKey(Dictionary data, string key, out fsData subitem) { - if (data.TryGetValue(key, out subitem) == false) { - return fsResult.Fail(GetType().Name + " requires a <" + key + "> key in the data " + data); - } - return fsResult.Success; - } - - protected fsResult SerializeMember(Dictionary data, Type overrideConverterType, string name, T value) { - fsData memberData; - var result = Serializer.TrySerialize(typeof(T), overrideConverterType, value, out memberData); - if (result.Succeeded) data[name] = memberData; - return result; - } - - protected fsResult DeserializeMember(Dictionary data, Type overrideConverterType, string name, out T value) { - fsData memberData; - if (data.TryGetValue(name, out memberData) == false) { - value = default(T); - return fsResult.Fail("Unable to find member \"" + name + "\""); - } - - object storage = null; - var result = Serializer.TryDeserialize(memberData, typeof(T), overrideConverterType, ref storage); - value = (T)storage; - return result; - } - } -} \ No newline at end of file diff --git a/Assets/Source/fsBaseConverter.cs.meta b/Assets/Source/fsBaseConverter.cs.meta deleted file mode 100644 index 429c568..0000000 --- a/Assets/Source/fsBaseConverter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 8a9a1beed27909d48aa194777a3c7181 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/fsConfig.cs b/Assets/Source/fsConfig.cs deleted file mode 100644 index d4068d0..0000000 --- a/Assets/Source/fsConfig.cs +++ /dev/null @@ -1,94 +0,0 @@ -using System; -using System.Reflection; - -namespace FullSerializer { - // Global configuration options. - public static class fsGlobalConfig { - /// - /// Should deserialization be case sensitive? If this is false and the JSON has multiple members with the - /// same keys only separated by case, then this results in undefined behavior. - /// - public static bool IsCaseSensitive = true; - - /// - /// If exceptions are allowed internally, then additional date formats can be deserialized. - /// Note that the Full Serializer public API will *not* throw exceptions with this enabled; - /// errors will still be returned in a fsResult instance. - /// - public static bool AllowInternalExceptions = true; - - /// - /// This string will be used to prefix fields used internally by FullSerializer. - /// - public static string InternalFieldPrefix = "$"; - } - - /// - /// Enables some top-level customization of Full Serializer. - /// - public class fsConfig { - /// - /// The attributes that will force a field or property to be serialized. - /// - public Type[] SerializeAttributes = { -#if !NO_UNITY - typeof(UnityEngine.SerializeField), -#endif - typeof(fsPropertyAttribute) - }; - - /// - /// The attributes that will force a field or property to *not* be serialized. - /// - public Type[] IgnoreSerializeAttributes = { typeof(NonSerializedAttribute), typeof(fsIgnoreAttribute) }; - - /// - /// The default member serialization. - /// - public fsMemberSerialization DefaultMemberSerialization = fsMemberSerialization.Default; - - /// - /// Convert a C# field/property name into the key used for the JSON object. For example, you could - /// force all JSON names to lowercase with: - /// - /// fsConfig.GetJsonNameFromMemberName = (name, info) => name.ToLower(); - /// - /// This will only be used when the name is not explicitly specified with fsProperty. - /// - public Func GetJsonNameFromMemberName = (name, info) => name; - - /// - /// If false, then *all* property serialization support will be disabled - even properties - /// explicitly annotated with fsProperty or any other opt-in annotation. - /// - /// Setting this to false means that SerializeNonAutoProperties and - /// SerializeNonPublicSetProperties will be completely ignored. - /// - public bool EnablePropertySerialization = true; - - /// - /// Should the default serialization behaviour include non-auto properties? - /// - public bool SerializeNonAutoProperties = false; - - /// - /// Should the default serialization behaviour include properties with non-public setters? - /// - public bool SerializeNonPublicSetProperties = true; - - /// - /// If not null, this string format will be used for DateTime instead of the default one. - /// - public string CustomDateTimeFormatString = null; - - /// - /// Int64 and UInt64 will be serialized and deserialized as string for compatibility - /// - public bool Serialize64BitIntegerAsString = false; - - /// - /// Enums are serialized using their names by default. Setting this to true will serialize them as integers instead. - /// - public bool SerializeEnumsAsInteger = false; - } -} diff --git a/Assets/Source/fsConfig.cs.meta b/Assets/Source/fsConfig.cs.meta deleted file mode 100644 index a5a3d91..0000000 --- a/Assets/Source/fsConfig.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 76108d7346331af428d2c9393d9d8027 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/fsContext.cs b/Assets/Source/fsContext.cs deleted file mode 100644 index 1392d0c..0000000 --- a/Assets/Source/fsContext.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace FullSerializer { - /// - /// fsContext stores global metadata that can be used to customize how fsConverters operate - /// during serialization. - /// - public sealed class fsContext { - /// - /// All of the context objects. - /// - private readonly Dictionary _contextObjects = new Dictionary(); - - /// - /// Removes all context objects from the context. - /// - public void Reset() { - _contextObjects.Clear(); - } - - /// - /// Sets the context object for the given type with the given value. - /// - public void Set(T obj) { - _contextObjects[typeof(T)] = obj; - } - - /// - /// Returns true if there is a context object for the given type. - /// - public bool Has() { - return _contextObjects.ContainsKey(typeof(T)); - } - - /// - /// Fetches the context object for the given type. - /// - public T Get() { - object val; - if (_contextObjects.TryGetValue(typeof(T), out val)) { - return (T)val; - } - throw new InvalidOperationException("There is no context object of type " + typeof(T)); - } - } -} \ No newline at end of file diff --git a/Assets/Source/fsContext.cs.meta b/Assets/Source/fsContext.cs.meta deleted file mode 100644 index 59ca2a1..0000000 --- a/Assets/Source/fsContext.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: aa2d584506920bc42a437736d0eac8e9 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/fsConverter.cs b/Assets/Source/fsConverter.cs deleted file mode 100644 index f5ca01e..0000000 --- a/Assets/Source/fsConverter.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; - -namespace FullSerializer { - /// - /// The serialization converter allows for customization of the serialization process. - /// - public abstract class fsConverter : fsBaseConverter { - /// - /// Can this converter serialize and deserialize the given object type? - /// - /// The given object type. - /// True if the converter can serialize it, false otherwise. - public abstract bool CanProcess(Type type); - } -} \ No newline at end of file diff --git a/Assets/Source/fsConverter.cs.meta b/Assets/Source/fsConverter.cs.meta deleted file mode 100644 index dc19c7e..0000000 --- a/Assets/Source/fsConverter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: bba5af2bf7ead1c44b8ae89fc6f30783 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/fsConverterRegistrar.cs b/Assets/Source/fsConverterRegistrar.cs deleted file mode 100644 index d53ef02..0000000 --- a/Assets/Source/fsConverterRegistrar.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using System.Collections.Generic; -using FullSerializer.Internal; - -namespace FullSerializer { - /// - /// This class allows arbitrary code to easily register global converters. To add a converter, - /// simply declare a new field called "Register_*" that stores the type of converter you would - /// like to add. Alternatively, you can do the same with a method called "Register_*"; just add - /// the converter type to the `Converters` list. - /// - public partial class fsConverterRegistrar { - static fsConverterRegistrar() { - Converters = new List(); - - foreach (var field in typeof(fsConverterRegistrar).GetDeclaredFields()) { - if (field.Name.StartsWith("Register_")) Converters.Add(field.FieldType); - } - - foreach (var method in typeof(fsConverterRegistrar).GetDeclaredMethods()) { - if (method.Name.StartsWith("Register_")) method.Invoke(null, null); - } - - } - - public static List Converters; - - // Example field registration: - //public static AnimationCurve_DirectConverter Register_AnimationCurve_DirectConverter; - - // Example method registration: - //public static void Register_AnimationCurve_DirectConverter() { - // Converters.Add(typeof(AnimationCurve_DirectConverter)); - //} - } -} \ No newline at end of file diff --git a/Assets/Source/fsConverterRegistrar.cs.meta b/Assets/Source/fsConverterRegistrar.cs.meta deleted file mode 100644 index 946574d..0000000 --- a/Assets/Source/fsConverterRegistrar.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 2ba7cbc3359b9f5439201a47840eba3a -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/fsData.cs b/Assets/Source/fsData.cs deleted file mode 100644 index de76881..0000000 --- a/Assets/Source/fsData.cs +++ /dev/null @@ -1,394 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; - -namespace FullSerializer { - /// - /// The actual type that a JsonData instance can store. - /// - public enum fsDataType { - Array, - Object, - Double, - Int64, - Boolean, - String, - Null - } - - /// - /// A union type that stores a serialized value. The stored type can be one of six different - /// types: null, boolean, double, Int64, string, Dictionary, or List. - /// - public sealed class fsData { - /// - /// The raw value that this serialized data stores. It can be one of six different types; a - /// boolean, a double, Int64, a string, a Dictionary, or a List. - /// - private object _value; - - #region Constructors - /// - /// Creates a fsData instance that holds null. - /// - public fsData() { - _value = null; - } - - /// - /// Creates a fsData instance that holds a boolean. - /// - public fsData(bool boolean) { - _value = boolean; - } - - /// - /// Creates a fsData instance that holds a double. - /// - public fsData(double f) { - _value = f; - } - - /// - /// Creates a new fsData instance that holds an integer. - /// - public fsData(Int64 i) { - _value = i; - } - - /// - /// Creates a fsData instance that holds a string. - /// - public fsData(string str) { - _value = str; - } - - /// - /// Creates a fsData instance that holds a dictionary of values. - /// - public fsData(Dictionary dict) { - _value = dict; - } - - /// - /// Creates a fsData instance that holds a list of values. - /// - public fsData(List list) { - _value = list; - } - - /// - /// Helper method to create a fsData instance that holds a dictionary. - /// - public static fsData CreateDictionary() { - return new fsData(new Dictionary( - fsGlobalConfig.IsCaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase)); - } - - /// - /// Helper method to create a fsData instance that holds a list. - /// - public static fsData CreateList() { - return new fsData(new List()); - } - - /// - /// Helper method to create a fsData instance that holds a list with the initial capacity. - /// - public static fsData CreateList(int capacity) { - return new fsData(new List(capacity)); - } - - public readonly static fsData True = new fsData(true); - public readonly static fsData False = new fsData(false); - public readonly static fsData Null = new fsData(); - #endregion - - #region Internal Helper Methods - /// - /// Transforms the internal fsData instance into a dictionary. - /// - internal void BecomeDictionary() { - _value = new Dictionary(); - } - - /// - /// Returns a shallow clone of this data instance. - /// - internal fsData Clone() { - var clone = new fsData(); - clone._value = _value; - return clone; - } - #endregion - - #region Casting Predicates - public fsDataType Type { - get { - if (_value == null) return fsDataType.Null; - if (_value is double) return fsDataType.Double; - if (_value is Int64) return fsDataType.Int64; - if (_value is bool) return fsDataType.Boolean; - if (_value is string) return fsDataType.String; - if (_value is Dictionary) return fsDataType.Object; - if (_value is List) return fsDataType.Array; - - throw new InvalidOperationException("unknown JSON data type"); - } - } - - /// - /// Returns true if this fsData instance maps back to null. - /// - public bool IsNull { - get { - return _value == null; - } - } - - /// - /// Returns true if this fsData instance maps back to a double. - /// - public bool IsDouble { - get { - return _value is double; - } - } - - /// - /// Returns true if this fsData instance maps back to an Int64. - /// - public bool IsInt64 { - get { - return _value is Int64; - } - } - - /// - /// Returns true if this fsData instance maps back to a boolean. - /// - public bool IsBool { - get { - return _value is bool; - } - } - - /// - /// Returns true if this fsData instance maps back to a string. - /// - public bool IsString { - get { - return _value is string; - } - } - - /// - /// Returns true if this fsData instance maps back to a Dictionary. - /// - public bool IsDictionary { - get { - return _value is Dictionary; - } - } - - /// - /// Returns true if this fsData instance maps back to a List. - /// - public bool IsList { - get { - return _value is List; - } - } - #endregion - - #region Casts - /// - /// Casts this fsData to a double. Throws an exception if it is not a double. - /// - [DebuggerBrowsable(DebuggerBrowsableState.Never)] - public double AsDouble { - get { - return Cast(); - } - } - - /// - /// Casts this fsData to an Int64. Throws an exception if it is not an Int64. - /// - [DebuggerBrowsable(DebuggerBrowsableState.Never)] - public Int64 AsInt64 { - get { - return Cast(); - } - } - - - /// - /// Casts this fsData to a boolean. Throws an exception if it is not a boolean. - /// - [DebuggerBrowsable(DebuggerBrowsableState.Never)] - public bool AsBool { - get { - return Cast(); - } - } - - /// - /// Casts this fsData to a string. Throws an exception if it is not a string. - /// - [DebuggerBrowsable(DebuggerBrowsableState.Never)] - public string AsString { - get { - return Cast(); - } - } - - /// - /// Casts this fsData to a Dictionary. Throws an exception if it is not a - /// Dictionary. - /// - [DebuggerBrowsable(DebuggerBrowsableState.Never)] - public Dictionary AsDictionary { - get { - return Cast>(); - } - } - - /// - /// Casts this fsData to a List. Throws an exception if it is not a List. - /// - [DebuggerBrowsable(DebuggerBrowsableState.Never)] - public List AsList { - get { - return Cast>(); - } - } - - /// - /// Internal helper method to cast the underlying storage to the given type or throw a - /// pretty printed exception on failure. - /// - private T Cast() { - if (_value is T) { - return (T)_value; - } - - throw new InvalidCastException("Unable to cast <" + this + "> (with type = " + - _value.GetType() + ") to type " + typeof(T)); - } - #endregion - - #region ToString Implementation - public override string ToString() { - return fsJsonPrinter.CompressedJson(this); - } - #endregion - - #region Equality Comparisons - /// - /// Determines whether the specified object is equal to the current object. - /// - public override bool Equals(object obj) { - return Equals(obj as fsData); - } - - /// - /// Determines whether the specified object is equal to the current object. - /// - public bool Equals(fsData other) { - if (other == null || Type != other.Type) { - return false; - } - - switch (Type) { - case fsDataType.Null: - return true; - - case fsDataType.Double: - return AsDouble == other.AsDouble || Math.Abs(AsDouble - other.AsDouble) < double.Epsilon; - - case fsDataType.Int64: - return AsInt64 == other.AsInt64; - - case fsDataType.Boolean: - return AsBool == other.AsBool; - - case fsDataType.String: - return AsString == other.AsString; - - case fsDataType.Array: - var thisList = AsList; - var otherList = other.AsList; - - if (thisList.Count != otherList.Count) return false; - - for (int i = 0; i < thisList.Count; ++i) { - if (thisList[i].Equals(otherList[i]) == false) { - return false; - } - } - - return true; - - case fsDataType.Object: - var thisDict = AsDictionary; - var otherDict = other.AsDictionary; - - if (thisDict.Count != otherDict.Count) return false; - - foreach (string key in thisDict.Keys) { - if (otherDict.ContainsKey(key) == false) { - return false; - } - - if (thisDict[key].Equals(otherDict[key]) == false) { - return false; - } - } - - return true; - } - - throw new Exception("Unknown data type"); - } - - /// - /// Returns true iff a == b. - /// - public static bool operator ==(fsData a, fsData b) { - // If both are null, or both are same instance, return true. - if (ReferenceEquals(a, b)) { - return true; - } - - // If one is null, but not both, return false. - if (((object)a == null) || ((object)b == null)) { - return false; - } - - if (a.IsDouble && b.IsDouble) { - return Math.Abs(a.AsDouble - b.AsDouble) < double.Epsilon; - } - - return a.Equals(b); - } - - /// - /// Returns true iff a != b. - /// - public static bool operator !=(fsData a, fsData b) { - return !(a == b); - } - - /// - /// Returns a hash code for this instance. - /// - /// A hash code for this instance, suitable for use in hashing algorithms and data - /// structures like a hash table. - public override int GetHashCode() { - return _value.GetHashCode(); - } - #endregion - } - -} \ No newline at end of file diff --git a/Assets/Source/fsData.cs.meta b/Assets/Source/fsData.cs.meta deleted file mode 100644 index 2a60dde..0000000 --- a/Assets/Source/fsData.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: f91f03a8b5894984aa6dcd1b7e60534e -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/fsDirectConverter.cs b/Assets/Source/fsDirectConverter.cs deleted file mode 100644 index 679611b..0000000 --- a/Assets/Source/fsDirectConverter.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace FullSerializer { - /// - /// The direct converter is similar to a regular converter, except that it targets specifically only one type. - /// This means that it can be used without performance impact when discovering converters. It is strongly - /// recommended that you derive from fsDirectConverter{TModel}. - /// - /// Due to the way that direct converters operate, inheritance is *not* supported. Direct converters - /// will only be used with the exact ModelType object. - public abstract class fsDirectConverter : fsBaseConverter { - public abstract Type ModelType { get; } - } - - public abstract class fsDirectConverter : fsDirectConverter { - public override Type ModelType { get { return typeof(TModel); } } - - public sealed override fsResult TrySerialize(object instance, out fsData serialized, Type storageType) { - var serializedDictionary = new Dictionary(); - var result = DoSerialize((TModel)instance, serializedDictionary); - serialized = new fsData(serializedDictionary); - return result; - } - - public sealed override fsResult TryDeserialize(fsData data, ref object instance, Type storageType) { - var result = fsResult.Success; - if ((result += CheckType(data, fsDataType.Object)).Failed) return result; - - var obj = (TModel)instance; - result += DoDeserialize(data.AsDictionary, ref obj); - instance = obj; - return result; - } - - protected abstract fsResult DoSerialize(TModel model, Dictionary serialized); - protected abstract fsResult DoDeserialize(Dictionary data, ref TModel model); - } -} diff --git a/Assets/Source/fsDirectConverter.cs.meta b/Assets/Source/fsDirectConverter.cs.meta deleted file mode 100644 index 113383c..0000000 --- a/Assets/Source/fsDirectConverter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: f7796db4e1a6f0f4b890a0db01cfc258 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/fsExceptions.cs b/Assets/Source/fsExceptions.cs deleted file mode 100644 index 705b834..0000000 --- a/Assets/Source/fsExceptions.cs +++ /dev/null @@ -1,16 +0,0 @@ -// note: This file contains exceptions used by FullSerializer. Exceptions are never used at runtime -// in FullSerializer; they are only used when validating annotations and code-based models. - -using System; - -namespace FullSerializer { - public sealed class fsMissingVersionConstructorException : Exception { - public fsMissingVersionConstructorException(Type versionedType, Type constructorType) : - base(versionedType + " is missing a constructor for previous model type " + constructorType) { } - } - - public sealed class fsDuplicateVersionNameException : Exception { - public fsDuplicateVersionNameException(Type typeA, Type typeB, string version) : - base(typeA + " and " + typeB + " have the same version string (" + version + "); please change one of them.") { } - } -} \ No newline at end of file diff --git a/Assets/Source/fsExceptions.cs.meta b/Assets/Source/fsExceptions.cs.meta deleted file mode 100644 index 163bfa3..0000000 --- a/Assets/Source/fsExceptions.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 3425b211a44d09c48a09b46e76c3146a -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/fsISerializationCallbacks.cs b/Assets/Source/fsISerializationCallbacks.cs deleted file mode 100644 index 15154be..0000000 --- a/Assets/Source/fsISerializationCallbacks.cs +++ /dev/null @@ -1,97 +0,0 @@ -using System; -#if !NO_UNITY -using UnityEngine; -#endif - -#if !UNITY_EDITOR && UNITY_WSA -// For System.Reflection.TypeExtensions -using System.Reflection; -#endif - -namespace FullSerializer { - /// - /// Extend this interface on your type to receive notifications about serialization/deserialization events. If you don't - /// have access to the type itself, then you can write an fsObjectProcessor instead. - /// - public interface fsISerializationCallbacks { - /// - /// Called before serialization. - /// - void OnBeforeSerialize(Type storageType); - - /// - /// Called after serialization. - /// - /// The field/property type that is storing the instance. - /// The data that was serialized. - void OnAfterSerialize(Type storageType, ref fsData data); - - /// - /// Called before deserialization. - /// - /// The field/property type that is storing the instance. - /// The data that will be used for deserialization. - void OnBeforeDeserialize(Type storageType, ref fsData data); - - /// - /// Called after deserialization. - /// - /// The field/property type that is storing the instance. - /// The type of the instance. - void OnAfterDeserialize(Type storageType); - } -} - -namespace FullSerializer.Internal { - public class fsSerializationCallbackProcessor : fsObjectProcessor { - public override bool CanProcess(Type type) { - return typeof(fsISerializationCallbacks).IsAssignableFrom(type); - } - - public override void OnBeforeSerialize(Type storageType, object instance) { - // Don't call the callback on null instances. - if(instance == null) return; - ((fsISerializationCallbacks)instance).OnBeforeSerialize(storageType); - } - - public override void OnAfterSerialize(Type storageType, object instance, ref fsData data) { - // Don't call the callback on null instances. - if(instance == null) return; - ((fsISerializationCallbacks)instance).OnAfterSerialize(storageType, ref data); - } - - public override void OnBeforeDeserializeAfterInstanceCreation(Type storageType, object instance, ref fsData data) { - if (instance is fsISerializationCallbacks == false) { - throw new InvalidCastException("Please ensure the converter for " + storageType + " actually returns an instance of it, not an instance of " + instance.GetType()); - } - - ((fsISerializationCallbacks)instance).OnBeforeDeserialize(storageType, ref data); - } - - public override void OnAfterDeserialize(Type storageType, object instance) { - // Don't call the callback on null instances. - if(instance == null) return; - ((fsISerializationCallbacks)instance).OnAfterDeserialize(storageType); - } - } - -#if !NO_UNITY - public class fsSerializationCallbackReceiverProcessor : fsObjectProcessor { - public override bool CanProcess(Type type) { - return typeof(ISerializationCallbackReceiver).IsAssignableFrom(type); - } - - public override void OnBeforeSerialize(Type storageType, object instance) { - // Don't call the callback on null instances. - if(instance == null) return; - ((ISerializationCallbackReceiver)instance).OnBeforeSerialize(); - } - - public override void OnAfterDeserialize(Type storageType, object instance) { - // Don't call the callback on null instances. - if(instance == null) return; - ((ISerializationCallbackReceiver)instance).OnAfterDeserialize(); - } - } -#endif -} diff --git a/Assets/Source/fsISerializationCallbacks.cs.meta b/Assets/Source/fsISerializationCallbacks.cs.meta deleted file mode 100644 index 2efab28..0000000 --- a/Assets/Source/fsISerializationCallbacks.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 3d8d502851fa3a1468d7a69bef2536cb -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/fsIgnoreAttribute.cs b/Assets/Source/fsIgnoreAttribute.cs deleted file mode 100644 index 3eaea48..0000000 --- a/Assets/Source/fsIgnoreAttribute.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System; - -namespace FullSerializer { - /// - /// The given property or field annotated with [JsonIgnore] will not be serialized. - /// - [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] - public sealed class fsIgnoreAttribute : Attribute { - } -} \ No newline at end of file diff --git a/Assets/Source/fsIgnoreAttribute.cs.meta b/Assets/Source/fsIgnoreAttribute.cs.meta deleted file mode 100644 index 910de28..0000000 --- a/Assets/Source/fsIgnoreAttribute.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 52525c31751c2a54d8e3fca6e7c0caa6 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/fsJsonParser.cs b/Assets/Source/fsJsonParser.cs deleted file mode 100644 index 4ca1af8..0000000 --- a/Assets/Source/fsJsonParser.cs +++ /dev/null @@ -1,505 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text; - -namespace FullSerializer { - // TODO: properly propagate warnings/etc for fsResult states - - /// - /// A simple recursive descent parser for JSON. - /// - public class fsJsonParser { - private int _start; - private string _input; - - private fsResult MakeFailure(string message) { - int start = Math.Max(0, _start - 20); - int length = Math.Min(50, _input.Length - start); - - string error = "Error while parsing: " + message + "; context = <" + - _input.Substring(start, length) + ">"; - return fsResult.Fail(error); - } - - private bool TryMoveNext() { - if (_start < _input.Length) { - ++_start; - return true; - } - - return false; - } - - private bool HasValue() { - return HasValue(0); - } - - private bool HasValue(int offset) { - return (_start + offset) >= 0 && (_start + offset) < _input.Length; - } - - private char Character() { - return Character(0); - } - - private char Character(int offset) { - return _input[_start + offset]; - } - - /// - /// Skips input such that Character() will return a non-whitespace character - /// - private void SkipSpace() { - while (HasValue()) { - char c = Character(); - - // whitespace; fine to skip - if (char.IsWhiteSpace(c)) { - TryMoveNext(); - continue; - } - - // comment? - if (HasValue(1) && Character(0) == '/') { - if (Character(1) == '/') { - // skip the rest of the line - while (HasValue() && Environment.NewLine.Contains("" + Character()) == false) { - TryMoveNext(); - } - continue; - } else if (Character(1) == '*') { - // skip to comment close - TryMoveNext(); - TryMoveNext(); - while (HasValue(1)) { - if (Character(0) == '*' && Character(1) == '/') { - TryMoveNext(); - TryMoveNext(); - TryMoveNext(); - break; - } else { - TryMoveNext(); - } - } - } - // let other checks to check fail - continue; - } - - break; - } - } - - #region Escaping - private bool IsHex(char c) { - return ((c >= '0' && c <= '9') || - (c >= 'a' && c <= 'f') || - (c >= 'A' && c <= 'F')); - } - - private uint ParseSingleChar(char c1, uint multipliyer) { - uint p1 = 0; - if (c1 >= '0' && c1 <= '9') - p1 = (uint)(c1 - '0') * multipliyer; - else if (c1 >= 'A' && c1 <= 'F') - p1 = (uint)((c1 - 'A') + 10) * multipliyer; - else if (c1 >= 'a' && c1 <= 'f') - p1 = (uint)((c1 - 'a') + 10) * multipliyer; - return p1; - } - - private uint ParseUnicode(char c1, char c2, char c3, char c4) { - uint p1 = ParseSingleChar(c1, 0x1000); - uint p2 = ParseSingleChar(c2, 0x100); - uint p3 = ParseSingleChar(c3, 0x10); - uint p4 = ParseSingleChar(c4, 0x1); - - return p1 + p2 + p3 + p4; - } - - private fsResult TryUnescapeChar(out char escaped) { - // skip leading backslash '\' - TryMoveNext(); - if (HasValue() == false) { - escaped = ' '; - return MakeFailure("Unexpected end of input after \\"); - } - - switch (Character()) { - case '\\': TryMoveNext(); escaped = '\\'; return fsResult.Success; - case '/': TryMoveNext(); escaped = '/'; return fsResult.Success; - case '"': TryMoveNext(); escaped = '\"'; return fsResult.Success; - case 'a': TryMoveNext(); escaped = '\a'; return fsResult.Success; - case 'b': TryMoveNext(); escaped = '\b'; return fsResult.Success; - case 'f': TryMoveNext(); escaped = '\f'; return fsResult.Success; - case 'n': TryMoveNext(); escaped = '\n'; return fsResult.Success; - case 'r': TryMoveNext(); escaped = '\r'; return fsResult.Success; - case 't': TryMoveNext(); escaped = '\t'; return fsResult.Success; - case '0': TryMoveNext(); escaped = '\0'; return fsResult.Success; - case 'u': - TryMoveNext(); - if (IsHex(Character(0)) - && IsHex(Character(1)) - && IsHex(Character(2)) - && IsHex(Character(3))) { - - uint codePoint = ParseUnicode(Character(0), Character(1), Character(2), Character(3)); - - TryMoveNext(); - TryMoveNext(); - TryMoveNext(); - TryMoveNext(); - - escaped = (char)codePoint; - return fsResult.Success; - } - - // invalid escape sequence - escaped = (char)0; - return MakeFailure( - string.Format("invalid escape sequence '\\u{0}{1}{2}{3}'\n", - Character(0), - Character(1), - Character(2), - Character(3))); - default: - escaped = (char)0; - return MakeFailure(string.Format("Invalid escape sequence \\{0}", Character())); - } - } - #endregion - - private fsResult TryParseExact(string content) { - for (int i = 0; i < content.Length; ++i) { - if (Character() != content[i]) { - return MakeFailure("Expected " + content[i]); - } - - if (TryMoveNext() == false) { - return MakeFailure("Unexpected end of content when parsing " + content); - } - } - - return fsResult.Success; - } - - private fsResult TryParseTrue(out fsData data) { - var fail = TryParseExact("true"); - - if (fail.Succeeded) { - data = new fsData(true); - return fsResult.Success; - } - - data = null; - return fail; - } - - private fsResult TryParseFalse(out fsData data) { - var fail = TryParseExact("false"); - - if (fail.Succeeded) { - data = new fsData(false); - return fsResult.Success; - } - - data = null; - return fail; - } - - private fsResult TryParseNull(out fsData data) { - var fail = TryParseExact("null"); - - if (fail.Succeeded) { - data = new fsData(); - return fsResult.Success; - } - - data = null; - return fail; - } - - - private bool IsSeparator(char c) { - return char.IsWhiteSpace(c) || c == ',' || c == '}' || c == ']'; - } - - /// - /// Parses numbers that follow the regular expression [-+](\d+|\d*\.\d*) - /// - private fsResult TryParseNumber(out fsData data) { - int start = _start; - - // read until we get to a separator - while ( - TryMoveNext() && - (HasValue() && IsSeparator(Character()) == false)) { - } - - // try to parse the value - string numberString = _input.Substring(start, _start - start); - - // double -- includes a . - if (numberString.Contains(".") || numberString.Contains("e") || numberString.Contains("E") || - numberString == "Infinity" || numberString == "-Infinity" || numberString == "NaN") { - double doubleValue; - if (double.TryParse(numberString, NumberStyles.Any, CultureInfo.InvariantCulture, out doubleValue) == false) { - data = null; - return MakeFailure("Bad double format with " + numberString); - } - - data = new fsData(doubleValue); - return fsResult.Success; - } - else { - Int64 intValue; - if (Int64.TryParse(numberString, NumberStyles.Any, CultureInfo.InvariantCulture, out intValue) == false) { - data = null; - return MakeFailure("Bad Int64 format with " + numberString); - } - - data = new fsData(intValue); - return fsResult.Success; - } - } - - private readonly StringBuilder _cachedStringBuilder = new StringBuilder(256); - /// - /// Parses a string - /// - private fsResult TryParseString(out string str) { - _cachedStringBuilder.Length = 0; - - // skip the first " - if (Character() != '"' || TryMoveNext() == false) { - str = string.Empty; - return MakeFailure("Expected initial \" when parsing a string"); - } - - // read until the next " - while (HasValue() && Character() != '\"') { - char c = Character(); - - // escape if necessary - if (c == '\\') { - char unescaped; - var fail = TryUnescapeChar(out unescaped); - if (fail.Failed) { - str = string.Empty; - return fail; - } - - _cachedStringBuilder.Append(unescaped); - } - - // no escaping necessary - else { - _cachedStringBuilder.Append(c); - - // get the next character - if (TryMoveNext() == false) { - str = string.Empty; - return MakeFailure("Unexpected end of input when reading a string"); - } - } - } - - // skip the first " - if (HasValue() == false || Character() != '"' || TryMoveNext() == false) { - str = string.Empty; - return MakeFailure("No closing \" when parsing a string"); - } - - str = _cachedStringBuilder.ToString(); - return fsResult.Success; - } - - /// - /// Parses an array - /// - private fsResult TryParseArray(out fsData arr) { - if (Character() != '[') { - arr = null; - return MakeFailure("Expected initial [ when parsing an array"); - } - - // skip '[' - if (TryMoveNext() == false) { - arr = null; - return MakeFailure("Unexpected end of input when parsing an array"); - } - SkipSpace(); - - var result = new List(); - - while (HasValue() && Character() != ']') { - // parse the element - fsData element; - var fail = RunParse(out element); - if (fail.Failed) { - arr = null; - return fail; - } - - result.Add(element); - - // parse the comma - SkipSpace(); - if (HasValue() && Character() == ',') { - if (TryMoveNext() == false) break; - SkipSpace(); - } - } - - // skip the final ] - if (HasValue() == false || Character() != ']' || TryMoveNext() == false) { - arr = null; - return MakeFailure("No closing ] for array"); - } - - arr = new fsData(result); - return fsResult.Success; - } - - private fsResult TryParseObject(out fsData obj) { - if (Character() != '{') { - obj = null; - return MakeFailure("Expected initial { when parsing an object"); - } - - // skip '{' - if (TryMoveNext() == false) { - obj = null; - return MakeFailure("Unexpected end of input when parsing an object"); - } - SkipSpace(); - - var result = new Dictionary( - fsGlobalConfig.IsCaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase); - - while (HasValue() && Character() != '}') { - fsResult failure; - - // parse the key - SkipSpace(); - string key; - failure = TryParseString(out key); - if (failure.Failed) { - obj = null; - return failure; - } - SkipSpace(); - - // parse the ':' after the key - if (HasValue() == false || Character() != ':' || TryMoveNext() == false) { - obj = null; - return MakeFailure("Expected : after key \"" + key + "\""); - } - SkipSpace(); - - // parse the value - fsData value; - failure = RunParse(out value); - if (failure.Failed) { - obj = null; - return failure; - } - - result.Add(key, value); - - // parse the comma - SkipSpace(); - if (HasValue() && Character() == ',') { - if (TryMoveNext() == false) break; - SkipSpace(); - } - } - - // skip the final } - if (HasValue() == false || Character() != '}' || TryMoveNext() == false) { - obj = null; - return MakeFailure("No closing } for object"); - } - - obj = new fsData(result); - return fsResult.Success; - } - - private fsResult RunParse(out fsData data) { - SkipSpace(); - - if (HasValue() == false) { - data = default(fsData); - return MakeFailure("Unexpected end of input"); - } - - switch (Character()) { - case 'I': // Infinity - case 'N': // NaN - case '.': - case '+': - case '-': - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': return TryParseNumber(out data); - case '"': { - string str; - fsResult fail = TryParseString(out str); - if (fail.Failed) { - data = null; - return fail; - } - data = new fsData(str); - return fsResult.Success; - } - case '[': return TryParseArray(out data); - case '{': return TryParseObject(out data); - case 't': return TryParseTrue(out data); - case 'f': return TryParseFalse(out data); - case 'n': return TryParseNull(out data); - default: - data = null; - return MakeFailure("unable to parse; invalid token \"" + Character() + "\""); - } - } - - /// - /// Parses the specified input. Returns a failure state if parsing failed. - /// - /// The input to parse. - /// The parsed data. This is undefined if parsing fails. - /// The parsed input. - public static fsResult Parse(string input, out fsData data) { - if (string.IsNullOrEmpty(input)) { - data = default(fsData); - return fsResult.Fail("No input"); - } - - var context = new fsJsonParser(input); - return context.RunParse(out data); - } - - /// - /// Helper method for Parse that does not allow the error information - /// to be recovered. - /// - public static fsData Parse(string input) { - fsData data; - Parse(input, out data).AssertSuccess(); - return data; - } - - private fsJsonParser(string input) { - _input = input; - _start = 0; - } - } -} \ No newline at end of file diff --git a/Assets/Source/fsJsonParser.cs.meta b/Assets/Source/fsJsonParser.cs.meta deleted file mode 100644 index e263708..0000000 --- a/Assets/Source/fsJsonParser.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 4c3e5a8da8796c84798679d00813622a -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/fsJsonPrinter.cs b/Assets/Source/fsJsonPrinter.cs deleted file mode 100644 index 1239161..0000000 --- a/Assets/Source/fsJsonPrinter.cs +++ /dev/null @@ -1,287 +0,0 @@ -using System; -using System.Globalization; -using System.IO; -using System.Text; - -namespace FullSerializer { - public static class fsJsonPrinter { - /// - /// Inserts the given number of indents into the builder. - /// - private static void InsertSpacing(TextWriter stream, int count) { - for (int i = 0; i < count; ++i) { - stream.Write(" "); - } - } - - /// - /// Escapes a string. - /// - private static string EscapeString(string str) { - // Escaping a string is pretty allocation heavy, so we try hard to not do it. - - bool needsEscape = false; - for (int i = 0; i < str.Length; ++i) { - char c = str[i]; - - // unicode code point - int intChar = Convert.ToInt32(c); - if (intChar < 0 || intChar > 127) { - needsEscape = true; - break; - } - - // standard escape character - switch (c) { - case '"': - case '\\': - case '\a': - case '\b': - case '\f': - case '\n': - case '\r': - case '\t': - case '\0': - needsEscape = true; - break; - } - - if (needsEscape) { - break; - } - } - - if (needsEscape == false) { - return str; - } - - - StringBuilder result = new StringBuilder(); - - for (int i = 0; i < str.Length; ++i) { - char c = str[i]; - - // unicode code point - int intChar = Convert.ToInt32(c); - if (intChar < 0 || intChar > 127) { - result.Append(string.Format("\\u{0:x4} ", intChar).Trim()); - continue; - } - - // standard escape character - switch (c) { - case '"': result.Append("\\\""); continue; - case '\\': result.Append(@"\\"); continue; - case '\a': result.Append(@"\a"); continue; - case '\b': result.Append(@"\b"); continue; - case '\f': result.Append(@"\f"); continue; - case '\n': result.Append(@"\n"); continue; - case '\r': result.Append(@"\r"); continue; - case '\t': result.Append(@"\t"); continue; - case '\0': result.Append(@"\0"); continue; - } - - // no escaping needed - result.Append(c); - } - return result.ToString(); - } - - private static void BuildCompressedString(fsData data, TextWriter stream) { - switch (data.Type) { - case fsDataType.Null: - stream.Write("null"); - break; - - case fsDataType.Boolean: - if (data.AsBool) stream.Write("true"); - else stream.Write("false"); - break; - - case fsDataType.Double: - // doubles must *always* include a decimal - stream.Write(ConvertDoubleToString(data.AsDouble)); - break; - - case fsDataType.Int64: - stream.Write(data.AsInt64); - break; - - case fsDataType.String: - stream.Write('"'); - stream.Write(EscapeString(data.AsString)); - stream.Write('"'); - break; - - case fsDataType.Object: { - stream.Write('{'); - bool comma = false; - foreach (var entry in data.AsDictionary) { - if (comma) stream.Write(','); - comma = true; - stream.Write('"'); - stream.Write(entry.Key); - stream.Write('"'); - stream.Write(":"); - BuildCompressedString(entry.Value, stream); - } - stream.Write('}'); - break; - } - - case fsDataType.Array: { - stream.Write('['); - bool comma = false; - foreach (var entry in data.AsList) { - if (comma) stream.Write(','); - comma = true; - BuildCompressedString(entry, stream); - } - stream.Write(']'); - break; - } - } - } - - /// - /// Formats this data into the given builder. - /// - private static void BuildPrettyString(fsData data, TextWriter stream, int depth) { - switch (data.Type) { - case fsDataType.Null: - stream.Write("null"); - break; - - case fsDataType.Boolean: - if (data.AsBool) stream.Write("true"); - else stream.Write("false"); - break; - - case fsDataType.Double: - stream.Write(ConvertDoubleToString(data.AsDouble)); - break; - - case fsDataType.Int64: - stream.Write(data.AsInt64); - break; - - - case fsDataType.String: - stream.Write('"'); - stream.Write(EscapeString(data.AsString)); - stream.Write('"'); - break; - - case fsDataType.Object: { - stream.Write('{'); - stream.WriteLine(); - bool comma = false; - foreach (var entry in data.AsDictionary) { - if (comma) { - stream.Write(','); - stream.WriteLine(); - } - comma = true; - InsertSpacing(stream, depth + 1); - stream.Write('"'); - stream.Write(entry.Key); - stream.Write('"'); - stream.Write(": "); - BuildPrettyString(entry.Value, stream, depth + 1); - } - stream.WriteLine(); - InsertSpacing(stream, depth); - stream.Write('}'); - break; - } - - case fsDataType.Array: - // special case for empty lists; we don't put an empty line between the brackets - if (data.AsList.Count == 0) { - stream.Write("[]"); - } - - else { - bool comma = false; - - stream.Write('['); - stream.WriteLine(); - foreach (var entry in data.AsList) { - if (comma) { - stream.Write(','); - stream.WriteLine(); - } - comma = true; - InsertSpacing(stream, depth + 1); - BuildPrettyString(entry, stream, depth + 1); - } - stream.WriteLine(); - InsertSpacing(stream, depth); - stream.Write(']'); - } - break; - } - } - - /// - /// Writes the pretty JSON output data to the given stream. - /// - /// The data to print. - /// Where to write the printed data. - public static void PrettyJson(fsData data, TextWriter outputStream) { - BuildPrettyString(data, outputStream, 0); - } - - /// - /// Returns the data in a pretty printed JSON format. - /// - public static string PrettyJson(fsData data) { - var sb = new StringBuilder(); - using (var writer = new StringWriter(sb)) { - BuildPrettyString(data, writer, 0); - return sb.ToString(); - } - } - - /// - /// Writes the compressed JSON output data to the given stream. - /// - /// The data to print. - /// Where to write the printed data. - public static void CompressedJson(fsData data, StreamWriter outputStream) { - BuildCompressedString(data, outputStream); - } - - /// - /// Returns the data in a relatively compressed JSON format. - /// - public static string CompressedJson(fsData data) { - var sb = new StringBuilder(); - using (var writer = new StringWriter(sb)) { - BuildCompressedString(data, writer); - return sb.ToString(); - } - } - - /// - /// Utility method that converts a double to a string. - /// - private static string ConvertDoubleToString(double d) { - if (Double.IsInfinity(d) || Double.IsNaN(d)) - return d.ToString(CultureInfo.InvariantCulture); - - string doubledString = d.ToString(CultureInfo.InvariantCulture); - - // NOTE/HACK: If we don't serialize with a period or an exponent, - // then the number will be deserialized as an Int64, not a double. - if (doubledString.Contains(".") == false && - doubledString.Contains("e") == false && - doubledString.Contains("E") == false) { - doubledString += ".0"; - } - - return doubledString; - } - - } -} \ No newline at end of file diff --git a/Assets/Source/fsJsonPrinter.cs.meta b/Assets/Source/fsJsonPrinter.cs.meta deleted file mode 100644 index 2cc1c2a..0000000 --- a/Assets/Source/fsJsonPrinter.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 4e795bc949226ef4d8a63c2f4bd3bdf9 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/fsMemberSerialization.cs b/Assets/Source/fsMemberSerialization.cs deleted file mode 100644 index de7767b..0000000 --- a/Assets/Source/fsMemberSerialization.cs +++ /dev/null @@ -1,21 +0,0 @@ -namespace FullSerializer { - /// - /// Controls how the reflected converter handles member serialization. - /// - public enum fsMemberSerialization { - /// - /// Only members with [SerializeField] or [fsProperty] attributes are serialized. - /// - OptIn, - - /// - /// Only members with [NotSerialized] or [fsIgnore] will not be serialized. - /// - OptOut, - - /// - /// The default member serialization behavior is applied. - /// - Default - } -} \ No newline at end of file diff --git a/Assets/Source/fsMemberSerialization.cs.meta b/Assets/Source/fsMemberSerialization.cs.meta deleted file mode 100644 index 0b48230..0000000 --- a/Assets/Source/fsMemberSerialization.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 3191f05f033e23947b48c7694d12e76c -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/fsObjectAttribute.cs b/Assets/Source/fsObjectAttribute.cs deleted file mode 100644 index bda5579..0000000 --- a/Assets/Source/fsObjectAttribute.cs +++ /dev/null @@ -1,52 +0,0 @@ -using System; - -namespace FullSerializer { - /// - /// This attribute controls some serialization behavior for a type. See the comments - /// on each of the fields for more information. - /// - [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)] - public sealed class fsObjectAttribute : Attribute { - /// - /// The previous model that should be used if an old version of this - /// object is encountered. Using this attribute also requires that the - /// type have a public constructor that takes only one parameter, an object - /// instance of the given type. Use of this parameter *requires* that - /// the VersionString parameter is also set. - /// - public Type[] PreviousModels; - - /// - /// The version string to use for this model. This should be unique among all - /// prior versions of this model that is supported for importation. If PreviousModel - /// is set, then this attribute must also be set. A good valid example for this - /// is "v1", "v2", "v3", ... - /// - public string VersionString; - - /// - /// This controls the behavior for member serialization. - /// The default behavior is fsMemberSerialization.Default. - /// - public fsMemberSerialization MemberSerialization = fsMemberSerialization.Default; - - /// - /// Specify a custom converter to use for serialization. The converter type needs - /// to derive from fsBaseConverter. This defaults to null. - /// - public Type Converter; - - /// - /// Specify a custom processor to use during serialization. The processor type needs - /// to derive from fsObjectProcessor and the call to CanProcess is not invoked. This - /// defaults to null. - /// - public Type Processor; - - public fsObjectAttribute() { } - public fsObjectAttribute(string versionString, params Type[] previousModels) { - VersionString = versionString; - PreviousModels = previousModels; - } - } -} \ No newline at end of file diff --git a/Assets/Source/fsObjectAttribute.cs.meta b/Assets/Source/fsObjectAttribute.cs.meta deleted file mode 100644 index cc3e574..0000000 --- a/Assets/Source/fsObjectAttribute.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ccb6d168f2ca6b34da57030c4d6edfcd -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/fsObjectProcessor.cs b/Assets/Source/fsObjectProcessor.cs deleted file mode 100644 index 1fc7f7a..0000000 --- a/Assets/Source/fsObjectProcessor.cs +++ /dev/null @@ -1,68 +0,0 @@ -using System; - -namespace FullSerializer { - /// - /// - /// Enables injecting code before/after an object has been serialized. This is most - /// useful if you want to run the default serialization process but apply a pre/post - /// processing step. - /// - /// - /// Multiple object processors can be active at the same time. When running they are - /// called in a "nested" fashion - if we have processor1 and process2 added to the - /// serializer in that order (p1 then p2), then the execution order will be - /// p1#Before p2#Before /serialization/ p2#After p1#After. - /// - /// - public abstract class fsObjectProcessor { - /// - /// Is the processor interested in objects of the given type? - /// - /// The given type. - /// True if the processor should be applied, false otherwise. - public virtual bool CanProcess(Type type) { throw new NotImplementedException(); } - - /// - /// Called before serialization. - /// - /// The field/property type that is storing the instance. - /// The type of the instance. - public virtual void OnBeforeSerialize(Type storageType, object instance) { } - - /// - /// Called after serialization. - /// - /// The field/property type that is storing the instance. - /// The type of the instance. - /// The data that was serialized. - public virtual void OnAfterSerialize(Type storageType, object instance, ref fsData data) { } - - /// - /// Called before deserialization. - /// - /// The field/property type that is storing the instance. - /// The data that will be used for deserialization. - public virtual void OnBeforeDeserialize(Type storageType, ref fsData data) { } - - /// - /// Called before deserialization has begun but *after* the object instance has been created. This will get - /// invoked even if the user passed in an existing instance. - /// - /// - /// **IMPORTANT**: The actual instance that gets passed here is *not* guaranteed to be an a subtype of storageType, since - /// the value for instance is whatever the active converter returned for CreateInstance() - ie, some converters will return - /// dummy types in CreateInstance() if instance creation cannot be separated from deserialization (ie, KeyValuePair). - /// - /// The field/property type that is storing the instance. - /// The created object instance. No deserialization has been applied to it. - /// The data that will be used for deserialization. - public virtual void OnBeforeDeserializeAfterInstanceCreation(Type storageType, object instance, ref fsData data) { } - - /// - /// Called after deserialization. - /// - /// The field/property type that is storing the instance. - /// The type of the instance. - public virtual void OnAfterDeserialize(Type storageType, object instance) { } - } -} diff --git a/Assets/Source/fsObjectProcessor.cs.meta b/Assets/Source/fsObjectProcessor.cs.meta deleted file mode 100644 index cfb8133..0000000 --- a/Assets/Source/fsObjectProcessor.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: b4f80a540fed3e14884d52cbbb7527e7 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/fsPropertyAttribute.cs b/Assets/Source/fsPropertyAttribute.cs deleted file mode 100644 index 3772c43..0000000 --- a/Assets/Source/fsPropertyAttribute.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; - -namespace FullSerializer { - /// - /// Explicitly mark a property to be serialized. This can also be used to give the name that the - /// property should use during serialization. - /// - [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] - public sealed class fsPropertyAttribute : Attribute { - /// - /// The name of that the property will use in JSON serialization. - /// - public string Name; - - /// - /// Use a custom converter for the given type. Specify the converter to use using typeof. - /// - public Type Converter; - - public fsPropertyAttribute() - : this(string.Empty) { - } - - public fsPropertyAttribute(string name) { - Name = name; - } - } -} \ No newline at end of file diff --git a/Assets/Source/fsPropertyAttribute.cs.meta b/Assets/Source/fsPropertyAttribute.cs.meta deleted file mode 100644 index 7c56fd4..0000000 --- a/Assets/Source/fsPropertyAttribute.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 1cc3d11ad86bde44d99e301b15937685 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/fsResult.cs b/Assets/Source/fsResult.cs deleted file mode 100644 index 86320b9..0000000 --- a/Assets/Source/fsResult.cs +++ /dev/null @@ -1,187 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace FullSerializer { - /// - /// The result of some sort of operation. A result is either successful or not, but if it - /// is successful then there may be a set of warnings/messages associated with it. These - /// warnings describe the performed error recovery operations. - /// - public struct fsResult { - // We cache the empty string array so we can unify some collections processing code. - private static readonly string[] EmptyStringArray = { }; - - /// - /// Is this result successful? - /// - /// This is intentionally a `success` state so that when the object - /// is default constructed it defaults to a failure state. - private bool _success; - - /// - /// The warning or error messages associated with the result. This may be null if - /// there are no messages. - /// - private List _messages; - - /// - /// Adds a new message to this result. - /// - /// - public void AddMessage(string message) { - if (_messages == null) { - _messages = new List(); - } - - _messages.Add(message); - } - - /// - /// Adds only the messages from the other result into this result, ignoring - /// the success/failure status of the other result. - /// - public void AddMessages(fsResult result) { - if (result._messages == null) { - return; - } - - if (_messages == null) { - _messages = new List(); - } - - _messages.AddRange(result._messages); - } - - /// - /// Merges the other result into this one. If the other result failed, then - /// this one too will have failed. - /// - /// - /// Note that you can use += instead of this method so that you don't bury - /// the actual method call that is generating the other fsResult. - /// - public fsResult Merge(fsResult other) { - // Copy success over - _success = _success && other._success; - - // Copy messages over - if (other._messages != null) { - if (_messages == null) _messages = new List(other._messages); - else _messages.AddRange(other._messages); - } - - return this; - } - - /// - /// A successful result. - /// - public static fsResult Success = new fsResult { - _success = true - }; - - /// - /// Create a result that is successful but contains the given warning message. - /// - public static fsResult Warn(string warning) { - return new fsResult { - _success = true, - _messages = new List { warning } - }; - } - - /// - /// Create a result that failed. - /// - public static fsResult Fail(string warning) { - return new fsResult { - _success = false, - _messages = new List { warning } - }; - } - - // TODO: how to make sure this is only used as +=? - - /// - /// Only use this as +=! - /// - public static fsResult operator +(fsResult a, fsResult b) { - return a.Merge(b); - } - - /// - /// Did this result fail? If so, you can see the reasons why in `RawMessages`. - /// - public bool Failed { - get { - return _success == false; - } - } - - /// - /// Was the result a success? Note that even successful operations may have - /// warning messages (`RawMessages`) associated with them. - /// - public bool Succeeded { - get { - return _success; - } - } - - /// - /// Does this result have any warnings? This says nothing about if it failed - /// or succeeded, just if it has warning messages associated with it. - /// - public bool HasWarnings { - get { - return _messages != null && _messages.Any(); - } - } - - /// - /// A simply utility method that will assert that this result is successful. If it - /// is not, then an exception is thrown. - /// - public fsResult AssertSuccess() { - if (Failed) throw AsException; - return this; - } - - /// - /// A simple utility method that will assert that this result is successful and that - /// there are no warning messages. This throws an exception if either of those - /// asserts are false. - /// - public fsResult AssertSuccessWithoutWarnings() { - if (Failed || RawMessages.Any()) throw AsException; - return this; - } - - /// - /// Utility method to convert the result to an exception. This method is only defined - /// is `Failed` returns true. - /// - public Exception AsException { - get { - if (!Failed && !RawMessages.Any()) throw new Exception("Only a failed result can be converted to an exception"); - return new Exception(FormattedMessages); - } - } - - public IEnumerable RawMessages { - get { - if (_messages != null) { - return _messages; - } - return EmptyStringArray; - } - } - - public string FormattedMessages { - get { - return string.Join(",\n", RawMessages.ToArray()); - } - } - } -} \ No newline at end of file diff --git a/Assets/Source/fsResult.cs.meta b/Assets/Source/fsResult.cs.meta deleted file mode 100644 index d3f3f1b..0000000 --- a/Assets/Source/fsResult.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 87a1962de4655664eb55d9570c0a3b2d -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Source/fsSerializer.cs b/Assets/Source/fsSerializer.cs deleted file mode 100644 index c4a7d93..0000000 --- a/Assets/Source/fsSerializer.cs +++ /dev/null @@ -1,843 +0,0 @@ -using System; -using System.Collections.Generic; -using FullSerializer.Internal; - -#if !UNITY_EDITOR && UNITY_WSA -// For System.Reflection.TypeExtensions -using System.Reflection; -#endif - -namespace FullSerializer { - public class fsSerializer { - #region Keys - private static HashSet _reservedKeywords; - static fsSerializer() { - _reservedKeywords = new HashSet { - Key_ObjectReference, - Key_ObjectDefinition, - Key_InstanceType, - Key_Version, - Key_Content - }; - } - /// - /// Returns true if the given key is a special keyword that full serializer uses to - /// add additional metadata on top of the emitted JSON. - /// - public static bool IsReservedKeyword(string key) { - return _reservedKeywords.Contains(key); - } - - /// - /// This is an object reference in part of a cyclic graph. - /// - private static readonly string Key_ObjectReference = string.Format("{0}ref", fsGlobalConfig.InternalFieldPrefix); - - /// - /// This is an object definition, as part of a cyclic graph. - /// - private static readonly string Key_ObjectDefinition = string.Format("{0}id", fsGlobalConfig.InternalFieldPrefix); - - /// - /// This specifies the actual type of an object (the instance type was different from - /// the field type). - /// - private static readonly string Key_InstanceType = string.Format("{0}type", fsGlobalConfig.InternalFieldPrefix); - - /// - /// The version string for the serialized data. - /// - private static readonly string Key_Version = string.Format("{0}version", fsGlobalConfig.InternalFieldPrefix); - - /// - /// If we have to add metadata but the original serialized state was not a dictionary, - /// then this will contain the original data. - /// - private static readonly string Key_Content = string.Format("{0}content", fsGlobalConfig.InternalFieldPrefix); - - private static bool IsObjectReference(fsData data) { - if (data.IsDictionary == false) return false; - return data.AsDictionary.ContainsKey(Key_ObjectReference); - } - private static bool IsObjectDefinition(fsData data) { - if (data.IsDictionary == false) return false; - return data.AsDictionary.ContainsKey(Key_ObjectDefinition); - } - private static bool IsVersioned(fsData data) { - if (data.IsDictionary == false) return false; - return data.AsDictionary.ContainsKey(Key_Version); - } - private static bool IsTypeSpecified(fsData data) { - if (data.IsDictionary == false) return false; - return data.AsDictionary.ContainsKey(Key_InstanceType); - } - private static bool IsWrappedData(fsData data) { - if (data.IsDictionary == false) return false; - return data.AsDictionary.ContainsKey(Key_Content); - } - - /// - /// Strips all deserialization metadata from the object, like $type and $content fields. - /// - /// After making this call, you will *not* be able to deserialize the same object instance. The metadata is - /// strictly necessary for deserialization! - public static void StripDeserializationMetadata(ref fsData data) { - if (data.IsDictionary && data.AsDictionary.ContainsKey(Key_Content)) { - data = data.AsDictionary[Key_Content]; - } - - if (data.IsDictionary) { - var dict = data.AsDictionary; - dict.Remove(Key_ObjectReference); - dict.Remove(Key_ObjectDefinition); - dict.Remove(Key_InstanceType); - dict.Remove(Key_Version); - } - } - - /// - /// This function converts legacy serialization data into the new format, so that - /// the import process can be unified and ignore the old format. - /// - private static void ConvertLegacyData(ref fsData data) { - if (data.IsDictionary == false) return; - - var dict = data.AsDictionary; - - // fast-exit: metadata never had more than two items - if (dict.Count > 2) return; - - // Key strings used in the legacy system - string referenceIdString = "ReferenceId"; - string sourceIdString = "SourceId"; - string sourceDataString = "Data"; - string typeString = "Type"; - string typeDataString = "Data"; - - // type specifier - if (dict.Count == 2 && dict.ContainsKey(typeString) && dict.ContainsKey(typeDataString)) { - data = dict[typeDataString]; - EnsureDictionary(data); - ConvertLegacyData(ref data); - - data.AsDictionary[Key_InstanceType] = dict[typeString]; - } - - // object definition - else if (dict.Count == 2 && dict.ContainsKey(sourceIdString) && dict.ContainsKey(sourceDataString)) { - data = dict[sourceDataString]; - EnsureDictionary(data); - ConvertLegacyData(ref data); - - data.AsDictionary[Key_ObjectDefinition] = dict[sourceIdString]; - } - - // object reference - else if (dict.Count == 1 && dict.ContainsKey(referenceIdString)) { - data = fsData.CreateDictionary(); - data.AsDictionary[Key_ObjectReference] = dict[referenceIdString]; - } - } - #endregion - - #region Utility Methods - private static void Invoke_OnBeforeSerialize(List processors, Type storageType, object instance) { - for (int i = 0; i < processors.Count; ++i) { - processors[i].OnBeforeSerialize(storageType, instance); - } - } - private static void Invoke_OnAfterSerialize(List processors, Type storageType, object instance, ref fsData data) { - // We run the after calls in reverse order; this significantly reduces the interaction burden between - // multiple processors - it makes each one much more independent and ignorant of the other ones. - - for (int i = processors.Count - 1; i >= 0; --i) { - processors[i].OnAfterSerialize(storageType, instance, ref data); - } - } - private static void Invoke_OnBeforeDeserialize(List processors, Type storageType, ref fsData data) { - for (int i = 0; i < processors.Count; ++i) { - processors[i].OnBeforeDeserialize(storageType, ref data); - } - } - private static void Invoke_OnBeforeDeserializeAfterInstanceCreation(List processors, Type storageType, object instance, ref fsData data) { - for (int i = 0; i < processors.Count; ++i) { - processors[i].OnBeforeDeserializeAfterInstanceCreation(storageType, instance, ref data); - } - } - private static void Invoke_OnAfterDeserialize(List processors, Type storageType, object instance) { - for (int i = processors.Count - 1; i >= 0; --i) { - processors[i].OnAfterDeserialize(storageType, instance); - } - } - #endregion - - /// - /// Ensures that the data is a dictionary. If it is not, then it is wrapped inside of one. - /// - private static void EnsureDictionary(fsData data) { - if (data.IsDictionary == false) { - var existingData = data.Clone(); - data.BecomeDictionary(); - data.AsDictionary[Key_Content] = existingData; - } - } - - /// - /// This manages instance writing so that we do not write unnecessary $id fields. We - /// only need to write out an $id field when there is a corresponding $ref field. This is able - /// to write $id references lazily because the fsData instance is not actually written out to text - /// until we have entirely finished serializing it. - /// - internal class fsLazyCycleDefinitionWriter { - private Dictionary _pendingDefinitions = new Dictionary(); - private HashSet _references = new HashSet(); - - public void WriteDefinition(int id, fsData data) { - if (_references.Contains(id)) { - EnsureDictionary(data); - data.AsDictionary[Key_ObjectDefinition] = new fsData(id.ToString()); - } - - else { - _pendingDefinitions[id] = data; - } - } - - public void WriteReference(int id, Dictionary dict) { - // Write the actual definition if necessary - if (_pendingDefinitions.ContainsKey(id)) { - var data = _pendingDefinitions[id]; - EnsureDictionary(data); - data.AsDictionary[Key_ObjectDefinition] = new fsData(id.ToString()); - _pendingDefinitions.Remove(id); - } - else { - _references.Add(id); - } - - // Write the reference - dict[Key_ObjectReference] = new fsData(id.ToString()); - } - - public void Clear() { - _pendingDefinitions.Clear(); - _references.Clear(); - } - } - - /// - /// Converter type to converter instance lookup table. This could likely be stored inside - // of _cachedConverters, but there is a semantic difference because _cachedConverters goes - /// from serialized type to converter. - /// - private Dictionary _cachedConverterTypeInstances; - - /// - /// A cache from type to it's converter. - /// - private Dictionary _cachedConverters; - - /// - /// A cache from type to the set of processors that are interested in it. - /// - private Dictionary> _cachedProcessors; - - /// - /// Converters that can be used for type registration. - /// - private readonly List _availableConverters; - - /// - /// Direct converters (optimized _converters). We use these so we don't have to - /// perform a scan through every item in _converters and can instead just do an O(1) - /// lookup. This is potentially important to perf when there are a ton of direct - /// converters. - /// - private readonly Dictionary _availableDirectConverters; - - /// - /// Processors that are available. - /// - private readonly List _processors; - - /// - /// Reference manager for cycle detection. - /// - private readonly fsCyclicReferenceManager _references; - private readonly fsLazyCycleDefinitionWriter _lazyReferenceWriter; - - public fsSerializer() { - _cachedConverterTypeInstances = new Dictionary(); - _cachedConverters = new Dictionary(); - _cachedProcessors = new Dictionary>(); - - _references = new fsCyclicReferenceManager(); - _lazyReferenceWriter = new fsLazyCycleDefinitionWriter(); - - // note: The order here is important. Items at the beginning of this - // list will be used before converters at the end. Converters - // added via AddConverter() are added to the front of the list. - _availableConverters = new List { - new fsNullableConverter { Serializer = this }, - new fsGuidConverter { Serializer = this }, - new fsTypeConverter { Serializer = this }, - new fsDateConverter { Serializer = this }, - new fsEnumConverter { Serializer = this }, - new fsPrimitiveConverter { Serializer = this }, - new fsArrayConverter { Serializer = this }, - new fsDictionaryConverter { Serializer = this }, - new fsIEnumerableConverter { Serializer = this }, - new fsKeyValuePairConverter { Serializer = this }, - new fsWeakReferenceConverter { Serializer = this }, - new fsReflectedConverter { Serializer = this } - }; - _availableDirectConverters = new Dictionary(); - - _processors = new List() { - new fsSerializationCallbackProcessor() - }; - -#if !NO_UNITY - _processors.Add(new fsSerializationCallbackReceiverProcessor()); -#endif - - Context = new fsContext(); - Config = new fsConfig(); - - // Register the converters from the registrar - foreach (var converterType in fsConverterRegistrar.Converters) { - AddConverter((fsBaseConverter)Activator.CreateInstance(converterType)); - } - } - - /// - /// A context object that fsConverters can use to customize how they operate. - /// - public fsContext Context; - - /// - /// Configuration options. Also see fsGlobalConfig. - /// - public fsConfig Config; - - /// - /// Add a new processor to the serializer. Multiple processors can run at the same time in the - /// same order they were added in. - /// - /// The processor to add. - public void AddProcessor(fsObjectProcessor processor) { - _processors.Add(processor); - - // We need to reset our cached processor set, as it could be invalid with the new - // processor. Ideally, _cachedProcessors should be empty (as the user should fully setup - // the serializer before actually using it), but there is no guarantee. - _cachedProcessors = new Dictionary>(); - } - - /// - /// Remove all processors which derive from TProcessor. - /// - public void RemoveProcessor() { - int i = 0; - while (i < _processors.Count) { - if (_processors[i] is TProcessor) { - _processors.RemoveAt(i); - } - else { - ++i; - } - } - - // We need to reset our cached processor set, as it could be invalid with the new - // processor. Ideally, _cachedProcessors should be empty (as the user should fully setup - // the serializer before actually using it), but there is no guarantee. - _cachedProcessors = new Dictionary>(); - } - - /// - /// Fetches all of the processors for the given type. - /// - private List GetProcessors(Type type) { - List processors; - - // Check to see if the user has defined a custom processor for the type. If they - // have, then we don't need to scan through all of the processor to check which - // one can process the type; instead, we directly use the specified processor. - var attr = fsPortableReflection.GetAttribute(type); - if (attr != null && attr.Processor != null) { - var processor = (fsObjectProcessor)Activator.CreateInstance(attr.Processor); - processors = new List(); - processors.Add(processor); - _cachedProcessors[type] = processors; - } - - else if (_cachedProcessors.TryGetValue(type, out processors) == false) { - processors = new List(); - - for (int i = 0; i < _processors.Count; ++i) { - var processor = _processors[i]; - if (processor.CanProcess(type)) { - processors.Add(processor); - } - } - - _cachedProcessors[type] = processors; - } - - return processors; - } - - - /// - /// Adds a new converter that can be used to customize how an object is serialized and - /// deserialized. - /// - public void AddConverter(fsBaseConverter converter) { - if (converter.Serializer != null) { - throw new InvalidOperationException("Cannot add a single converter instance to " + - "multiple fsConverters -- please construct a new instance for " + converter); - } - - // TODO: wrap inside of a ConverterManager so we can control _converters and _cachedConverters lifetime - if (converter is fsDirectConverter) { - var directConverter = (fsDirectConverter)converter; - _availableDirectConverters[directConverter.ModelType] = directConverter; - } - else if (converter is fsConverter) { - _availableConverters.Insert(0, (fsConverter)converter); - } - else { - throw new InvalidOperationException("Unable to add converter " + converter + - "; the type association strategy is unknown. Please use either " + - "fsDirectConverter or fsConverter as your base type."); - } - - converter.Serializer = this; - - // We need to reset our cached converter set, as it could be invalid with the new - // converter. Ideally, _cachedConverters should be empty (as the user should fully setup - // the serializer before actually using it), but there is no guarantee. - _cachedConverters = new Dictionary(); - } - - /// - /// Fetches a converter that can serialize/deserialize the given type. - /// - private fsBaseConverter GetConverter(Type type, Type overrideConverterType) { - // Use an override converter type instead if that's what the user has requested. - if (overrideConverterType != null) { - fsBaseConverter overrideConverter; - if (_cachedConverterTypeInstances.TryGetValue(overrideConverterType, out overrideConverter) == false) { - overrideConverter = (fsBaseConverter)Activator.CreateInstance(overrideConverterType); - overrideConverter.Serializer = this; - _cachedConverterTypeInstances[overrideConverterType] = overrideConverter; - } - - return overrideConverter; - } - - // Try to lookup an existing converter. - fsBaseConverter converter; - if (_cachedConverters.TryGetValue(type, out converter)) { - return converter; - } - - // Check to see if the user has defined a custom converter for the type. If they - // have, then we don't need to scan through all of the converters to check which - // one can process the type; instead, we directly use the specified converter. - { - var attr = fsPortableReflection.GetAttribute(type); - if (attr != null && attr.Converter != null) { - converter = (fsBaseConverter)Activator.CreateInstance(attr.Converter); - converter.Serializer = this; - return _cachedConverters[type] = converter; - } - } - - // Check for a [fsForward] attribute. - { - var attr = fsPortableReflection.GetAttribute(type); - if (attr != null) { - converter = new fsForwardConverter(attr); - converter.Serializer = this; - return _cachedConverters[type] = converter; - } - } - - - // There is no specific converter specified; try all of the general ones to see - // which ones matches. - if (_cachedConverters.TryGetValue(type, out converter) == false) { - if (_availableDirectConverters.ContainsKey(type)) { - converter = _availableDirectConverters[type]; - return _cachedConverters[type] = converter; - } - else { - for (int i = 0; i < _availableConverters.Count; ++i) { - if (_availableConverters[i].CanProcess(type)) { - converter = _availableConverters[i]; - return _cachedConverters[type] = converter; - } - } - } - } - - throw new InvalidOperationException("Internal error -- could not find a converter for " + type); - } - - /// - /// Helper method that simply forwards the call to TrySerialize(typeof(T), instance, out data); - /// - public fsResult TrySerialize(T instance, out fsData data) { - return TrySerialize(typeof(T), instance, out data); - } - - /// - /// Generic wrapper around TryDeserialize that simply forwards the call. - /// - public fsResult TryDeserialize(fsData data, ref T instance) { - object boxed = instance; - var fail = TryDeserialize(data, typeof(T), ref boxed); - if (fail.Succeeded) { - instance = (T)boxed; - } - return fail; - } - - /// - /// Serialize the given value. - /// - /// The type of field/property that stores the object instance. This is - /// important particularly for inheritance, as a field storing an IInterface instance - /// should have type information included. - /// The actual object instance to serialize. - /// The serialized state of the object. - /// If serialization was successful. - public fsResult TrySerialize(Type storageType, object instance, out fsData data) { - return TrySerialize(storageType, null, instance, out data); - } - - /// - /// Serialize the given value. - /// - /// The type of field/property that stores the object instance. This is - /// important particularly for inheritance, as a field storing an IInterface instance - /// should have type information included. - /// An fsBaseConverter derived type that will be used to serialize - /// the object instead of the converter found via the normal discovery mechanisms. - /// The actual object instance to serialize. - /// The serialized state of the object. - /// If serialization was successful. - public fsResult TrySerialize(Type storageType, Type overrideConverterType, object instance, out fsData data) { - var processors = GetProcessors(instance == null ? storageType : instance.GetType()); - - Invoke_OnBeforeSerialize(processors, storageType, instance); - - // We always serialize null directly as null - if (ReferenceEquals(instance, null)) { - data = new fsData(); - Invoke_OnAfterSerialize(processors, storageType, instance, ref data); - return fsResult.Success; - } - - var result = InternalSerialize_1_ProcessCycles(storageType, overrideConverterType, instance, out data); - Invoke_OnAfterSerialize(processors, storageType, instance, ref data); - return result; - } - - private fsResult InternalSerialize_1_ProcessCycles(Type storageType, Type overrideConverterType, object instance, out fsData data) { - // We have an object definition to serialize. - try { - // Note that we enter the reference group at the beginning of serialization so that we support - // references that are at equal serialization levels, not just nested serialization levels, within - // the given subobject. A prime example is serialization a list of references. - _references.Enter(); - - // This type does not need cycle support. - var converter = GetConverter(instance.GetType(), overrideConverterType); - if (converter.RequestCycleSupport(instance.GetType()) == false) { - return InternalSerialize_2_Inheritance(storageType, overrideConverterType, instance, out data); - } - - // We've already serialized this object instance (or it is pending higher up on the call stack). - // Just serialize a reference to it to escape the cycle. - // - // note: We serialize the int as a string to so that we don't lose any information - // in a conversion to/from double. - if (_references.IsReference(instance)) { - data = fsData.CreateDictionary(); - _lazyReferenceWriter.WriteReference(_references.GetReferenceId(instance), data.AsDictionary); - return fsResult.Success; - } - - // Mark inside the object graph that we've serialized the instance. We do this *before* - // serialization so that if we get back into this function recursively, it'll already - // be marked and we can handle the cycle properly without going into an infinite loop. - _references.MarkSerialized(instance); - - // We've created the cycle metadata, so we can now serialize the actual object. - // InternalSerialize will handle inheritance correctly for us. - var result = InternalSerialize_2_Inheritance(storageType, overrideConverterType, instance, out data); - if (result.Failed) return result; - - _lazyReferenceWriter.WriteDefinition(_references.GetReferenceId(instance), data); - - return result; - } - finally { - if (_references.Exit()) { - _lazyReferenceWriter.Clear(); - } - } - } - private fsResult InternalSerialize_2_Inheritance(Type storageType, Type overrideConverterType, object instance, out fsData data) { - // Serialize the actual object with the field type being the same as the object - // type so that we won't go into an infinite loop. - var serializeResult = InternalSerialize_3_ProcessVersioning(overrideConverterType, instance, out data); - if (serializeResult.Failed) return serializeResult; - - // Do we need to add type information? If the field type and the instance type are different - // then we will not be able to recover the correct instance type from the field type when - // we deserialize the object. - // - // Note: We allow converters to request that we do *not* add type information. - if (storageType != instance.GetType() && - GetConverter(storageType, overrideConverterType).RequestInheritanceSupport(storageType)) { - - // Add the inheritance metadata - EnsureDictionary(data); - data.AsDictionary[Key_InstanceType] = new fsData(instance.GetType().FullName); - } - - return serializeResult; - } - - private fsResult InternalSerialize_3_ProcessVersioning(Type overrideConverterType, object instance, out fsData data) { - // note: We do not have to take a Type parameter here, since at this point in the serialization - // algorithm inheritance has *always* been handled. If we took a type parameter, it will - // *always* be equal to instance.GetType(), so why bother taking the parameter? - - // Check to see if there is versioning information for this type. If so, then we need to serialize it. - fsOption optionalVersionedType = fsVersionManager.GetVersionedType(instance.GetType()); - if (optionalVersionedType.HasValue) { - fsVersionedType versionedType = optionalVersionedType.Value; - - // Serialize the actual object content; we'll just wrap it with versioning metadata here. - var result = InternalSerialize_4_Converter(overrideConverterType, instance, out data); - if (result.Failed) return result; - - // Add the versioning information - EnsureDictionary(data); - data.AsDictionary[Key_Version] = new fsData(versionedType.VersionString); - - return result; - } - - // This type has no versioning information -- directly serialize it using the selected converter. - return InternalSerialize_4_Converter(overrideConverterType, instance, out data); - } - private fsResult InternalSerialize_4_Converter(Type overrideConverterType, object instance, out fsData data) { - var instanceType = instance.GetType(); - return GetConverter(instanceType, overrideConverterType).TrySerialize(instance, out data, instanceType); - } - - /// - /// Attempts to deserialize a value from a serialized state. - /// - public fsResult TryDeserialize(fsData data, Type storageType, ref object result) { - return TryDeserialize(data, storageType, null, ref result); - } - - /// - /// Attempts to deserialize a value from a serialized state. - /// - public fsResult TryDeserialize(fsData data, Type storageType, Type overrideConverterType, ref object result) { - if (data.IsNull) { - result = null; - var processors = GetProcessors(storageType); - Invoke_OnBeforeDeserialize(processors, storageType, ref data); - Invoke_OnAfterDeserialize(processors, storageType, null); - return fsResult.Success; - } - - // Convert legacy data into modern style data - ConvertLegacyData(ref data); - - try { - // We wrap the entire deserialize call in a reference group so that we can properly - // deserialize a "parallel" set of references, ie, a list of objects that are cyclic - // w.r.t. the list - _references.Enter(); - - List processors; - var r = InternalDeserialize_1_CycleReference(overrideConverterType, data, storageType, ref result, out processors); - if (r.Succeeded) { - Invoke_OnAfterDeserialize(processors, storageType, result); - } - return r; - } - finally { - _references.Exit(); - } - } - - private fsResult InternalDeserialize_1_CycleReference(Type overrideConverterType, fsData data, Type storageType, ref object result, out List processors) { - // We handle object references first because we could be deserializing a cyclic type that is - // inherited. If that is the case, then if we handle references after inheritances we will try - // to create an object instance for an abstract/interface type. - - // While object construction should technically be two-pass, we can do it in - // one pass because of how serialization happens. We traverse the serialization - // graph in the same order during serialization and deserialization, so the first - // time we encounter an object it'll always be the definition. Any times after that - // it will be a reference. Because of this, if we encounter a reference then we - // will have *always* already encountered the definition for it. - if (IsObjectReference(data)) { - int refId = int.Parse(data.AsDictionary[Key_ObjectReference].AsString); - result = _references.GetReferenceObject(refId); - processors = GetProcessors(result.GetType()); - return fsResult.Success; - } - - return InternalDeserialize_2_Version(overrideConverterType, data, storageType, ref result, out processors); - } - - private fsResult InternalDeserialize_2_Version(Type overrideConverterType, fsData data, Type storageType, ref object result, out List processors) { - if (IsVersioned(data)) { - // data is versioned, but we might not need to do a migration - string version = data.AsDictionary[Key_Version].AsString; - - fsOption versionedType = fsVersionManager.GetVersionedType(storageType); - if (versionedType.HasValue && - versionedType.Value.VersionString != version) { - - // we have to do a migration - var deserializeResult = fsResult.Success; - - List path; - deserializeResult += fsVersionManager.GetVersionImportPath(version, versionedType.Value, out path); - if (deserializeResult.Failed) { - processors = GetProcessors(storageType); - return deserializeResult; - } - - // deserialize as the original type - deserializeResult += InternalDeserialize_3_Inheritance(overrideConverterType, data, path[0].ModelType, ref result, out processors); - if (deserializeResult.Failed) return deserializeResult; - - // TODO: we probably should be invoking object processors all along this pipeline - for (int i = 1; i < path.Count; ++i) { - result = path[i].Migrate(result); - } - - // Our data contained an object definition ($id) that was added to _references in step 4. - // However, in case we are doing versioning, it will contain the old version. - // To make sure future references to this object end up referencing the migrated version, - // we must update the reference. - if (IsObjectDefinition(data)) { - int sourceId = int.Parse(data.AsDictionary[Key_ObjectDefinition].AsString); - _references.AddReferenceWithId(sourceId, result); - } - - processors = GetProcessors(deserializeResult.GetType()); - return deserializeResult; - } - } - - return InternalDeserialize_3_Inheritance(overrideConverterType, data, storageType, ref result, out processors); - } - - private fsResult InternalDeserialize_3_Inheritance(Type overrideConverterType, fsData data, Type storageType, ref object result, out List processors) { - var deserializeResult = fsResult.Success; - - Type objectType = storageType; - - // If the serialized state contains type information, then we need to make sure to update our - // objectType and data to the proper values so that when we construct an object instance later - // and run deserialization we run it on the proper type. - if (IsTypeSpecified(data)) { - fsData typeNameData = data.AsDictionary[Key_InstanceType]; - - // we wrap everything in a do while false loop so we can break out it - do { - if (typeNameData.IsString == false) { - deserializeResult.AddMessage(Key_InstanceType + " value must be a string (in " + data + ")"); - break; - } - - string typeName = typeNameData.AsString; - Type type = fsTypeCache.GetType(typeName); - if (type == null) { - deserializeResult += fsResult.Fail("Unable to locate specified type \"" + typeName + "\""); - break; - } - - if (storageType.IsAssignableFrom(type) == false) { - deserializeResult.AddMessage("Ignoring type specifier; a field/property of type " + storageType + " cannot hold an instance of " + type); - break; - } - - objectType = type; - } while (false); - } - - // We wait until here to actually Invoke_OnBeforeDeserialize because we do not - // have the correct set of processors to invoke until *after* we have resolved - // the proper type to use for deserialization. - processors = GetProcessors(objectType); - - if (deserializeResult.Failed) - return deserializeResult; - - Invoke_OnBeforeDeserialize(processors, storageType, ref data); - - // Construct an object instance if we don't have one already. We also need to construct - // an instance if the result type is of the wrong type, which may be the case when we - // have a versioned import graph. - if (ReferenceEquals(result, null) || result.GetType() != objectType) { - result = GetConverter(objectType, overrideConverterType).CreateInstance(data, objectType); - } - - // We call OnBeforeDeserializeAfterInstanceCreation here because we still want to invoke the - // method even if the user passed in an existing instance. - Invoke_OnBeforeDeserializeAfterInstanceCreation(processors, storageType, result, ref data); - - // NOTE: It is critically important that we pass the actual objectType down instead of - // using result.GetType() because it is not guaranteed that result.GetType() - // will equal objectType, especially because some converters are known to - // return dummy values for CreateInstance() (for example, the default behavior - // for structs is to just return the type of the struct). - - return deserializeResult += InternalDeserialize_4_Cycles(overrideConverterType, data, objectType, ref result); - } - - private fsResult InternalDeserialize_4_Cycles(Type overrideConverterType, fsData data, Type resultType, ref object result) { - if (IsObjectDefinition(data)) { - // NOTE: object references are handled at stage 1 - - // If this is a definition, then we have a serialization invariant that this is the - // first time we have encountered the object (TODO: verify in the deserialization logic) - - // Since at this stage in the deserialization process we already have access to the - // object instance, so we just need to sync the object id to the references database - // so that when we encounter the instance we lookup this same object. We want to do - // this before actually deserializing the object because when deserializing the object - // there may be references to itself. - - int sourceId = int.Parse(data.AsDictionary[Key_ObjectDefinition].AsString); - _references.AddReferenceWithId(sourceId, result); - } - - // Nothing special, go through the standard deserialization logic. - return InternalDeserialize_5_Converter(overrideConverterType, data, resultType, ref result); - } - - private fsResult InternalDeserialize_5_Converter(Type overrideConverterType, fsData data, Type resultType, ref object result) { - if (IsWrappedData(data)) { - data = data.AsDictionary[Key_Content]; - } - - return GetConverter(resultType, overrideConverterType).TryDeserialize(data, ref result, resultType); - } - } -} diff --git a/Assets/Source/fsSerializer.cs.meta b/Assets/Source/fsSerializer.cs.meta deleted file mode 100644 index fc91881..0000000 --- a/Assets/Source/fsSerializer.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 81d68ae97272ffe4da1f76ed884c2257 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: