source: trunk/sources/HeuristicLab.Persistence/3.3/Default/CompositeSerializers/Storable/StorableSerializer.cs @ 3553

Last change on this file since 3553 was 3553, checked in by epitzer, 12 years ago

replace repeated calls through reflection with generated code for a twofold speedup (#548)

File size: 8.7 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using HeuristicLab.Persistence.Interfaces;
5using HeuristicLab.Persistence.Core;
6using System.Reflection;
7using HeuristicLab.Persistence.Auxiliary;
8using System.Text;
9using System.Reflection.Emit;
10
11namespace HeuristicLab.Persistence.Default.CompositeSerializers.Storable {
12
13  /// <summary>
14  /// Intended for serialization of all custom classes. Classes should have the
15  /// <c>[StorableClass]</c> attribute set. The default mode is to serialize
16  /// members with the <c>[Storable]</c> attribute set. Alternatively the
17  /// storable mode can be set to <c>AllFields</c>, <c>AllProperties</c>
18  /// or <c>AllFieldsAndAllProperties</c>.
19  /// </summary>
20  [StorableClass]
21  public sealed class StorableSerializer : ICompositeSerializer {
22
23    #region ICompositeSerializer implementation
24
25    /// <summary>
26    /// Priority 200, one of the first default composite serializers to try.
27    /// </summary>
28    /// <value></value>
29    public int Priority {
30      get { return 200; }
31    }
32
33    /// <summary>
34    /// Determines for every type whether the composite serializer is applicable.
35    /// </summary>
36    /// <param name="type">The type.</param>
37    /// <returns>
38    ///   <c>true</c> if this instance can serialize the specified type; otherwise, <c>false</c>.
39    /// </returns>
40    public bool CanSerialize(Type type) {
41      if (GetConstructor(type) == null)
42        return false;
43      return StorableReflection.IsEmptyOrStorableType(type, true);
44    }
45
46    /// <summary>
47    /// Give a reason if possibly why the given type cannot be serialized by this
48    /// ICompositeSerializer.
49    /// </summary>
50    /// <param name="type">The type.</param>
51    /// <returns>
52    /// A string justifying why type cannot be serialized.
53    /// </returns>
54    public string JustifyRejection(Type type) {
55      if (GetConstructor(type) == null)
56        return "no default constructor and no storable constructor";
57      if (!StorableReflection.IsEmptyOrStorableType(type, true))
58        return "class is not marked with the storable class attribute";
59      return "no reason";
60    }
61
62    /// <summary>
63    /// Creates the meta info.
64    /// </summary>
65    /// <param name="o">The object.</param>
66    /// <returns>A list of storable components.</returns>
67    public IEnumerable<Tag> CreateMetaInfo(object o) {
68      InvokeHook(HookType.BeforeSerialization, o);
69      return new Tag[] { };
70    }
71
72    /// <summary>
73    /// Decompose an object into <see cref="Tag"/>s, the tag name can be null,
74    /// the order in which elements are generated is guaranteed to be
75    /// the same as they will be supplied to the Populate method.
76    /// </summary>
77    /// <param name="obj">An object.</param>
78    /// <returns>An enumerable of <see cref="Tag"/>s.</returns>
79    public IEnumerable<Tag> Decompose(object obj) {
80      foreach (var accessor in GetStorableAccessors(obj)) {
81        yield return new Tag(accessor.Name, accessor.Get());
82      }
83    }
84
85    /// <summary>
86    /// Create an instance of the object using the provided meta information.
87    /// </summary>
88    /// <param name="type">A type.</param>
89    /// <param name="metaInfo">The meta information.</param>
90    /// <returns>A fresh instance of the provided type.</returns>
91    public object CreateInstance(Type type, IEnumerable<Tag> metaInfo) {
92      try {
93        return GetConstructor(type)();
94      } catch (TargetInvocationException x) {
95        throw new PersistenceException(
96          "Could not instantiate storable object: Encountered exception during constructor call",
97          x.InnerException);
98      }
99    }
100
101    /// <summary>
102    /// Populates the specified instance.
103    /// </summary>
104    /// <param name="instance">The instance.</param>
105    /// <param name="objects">The objects.</param>
106    /// <param name="type">The type.</param>
107    public void Populate(object instance, IEnumerable<Tag> objects, Type type) {
108      var memberDict = new Dictionary<string, Tag>();
109      IEnumerator<Tag> iter = objects.GetEnumerator();
110      while (iter.MoveNext()) {
111        memberDict.Add(iter.Current.Name, iter.Current);
112      }
113      foreach (var accessor in GetStorableAccessors(instance)) {
114        if (memberDict.ContainsKey(accessor.Name)) {
115          accessor.Set(memberDict[accessor.Name].Value);
116        } else if (accessor.DefaultValue != null) {
117          accessor.Set(accessor.DefaultValue);
118        }
119      }
120      InvokeHook(HookType.AfterDeserialization, instance);
121    }
122
123    #endregion
124
125    #region constants & private data types
126
127    private const BindingFlags ALL_CONSTRUCTORS =
128      BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
129
130    private static readonly object[] emptyArgs = new object[] { };
131
132    private sealed class HookDesignator {
133      public Type Type { get; private set; }
134      public HookType HookType { get; private set; }
135      public HookDesignator() { }
136      public HookDesignator(Type type, HookType hookType) {
137        Type = type;
138        HookType = HookType;
139      }
140    }
141
142    private sealed class MemberCache : Dictionary<Type, IEnumerable<StorableMemberInfo>> { }
143
144    #endregion
145
146    #region caches
147
148    private MemberCache storableMemberCache = new MemberCache();
149
150    private delegate object Constructor();
151
152    private Dictionary<Type, Constructor> constructorCache =
153      new Dictionary<Type, Constructor>();
154
155    private Dictionary<HookDesignator, List<StorableReflection.Hook>> hookCache =
156      new Dictionary<HookDesignator, List<StorableReflection.Hook>>();
157
158    #endregion
159
160    #region attribute access
161
162    private IEnumerable<StorableMemberInfo> GetStorableMembers(Type type) {
163      lock (storableMemberCache) {
164        if (storableMemberCache.ContainsKey(type))
165          return storableMemberCache[type];
166        var storablesMembers = StorableReflection.GenerateStorableMembers(type);
167        storableMemberCache[type] = storablesMembers;
168        return storablesMembers;
169      }
170    }
171
172    private Constructor GetConstructor(Type type) {
173      lock (constructorCache) {
174        if (constructorCache.ContainsKey(type))
175          return constructorCache[type];
176        Constructor c = FindStorableConstructor(type) ?? GetDefaultConstructor(type);
177        constructorCache.Add(type, c);
178        return c;
179      }
180    }
181
182    private Constructor GetDefaultConstructor(Type type) {
183      ConstructorInfo ci = type.GetConstructor(ALL_CONSTRUCTORS, null, Type.EmptyTypes, null);
184      if (ci == null)
185        return null;
186      DynamicMethod dm = new DynamicMethod("", typeof(object), null, type);
187      ILGenerator ilgen = dm.GetILGenerator();
188      ilgen.Emit(OpCodes.Newobj, ci);
189      ilgen.Emit(OpCodes.Ret);
190      return (Constructor)dm.CreateDelegate(typeof(Constructor));
191    }
192
193    private Constructor FindStorableConstructor(Type type) {
194      foreach (ConstructorInfo ci in type.GetConstructors(ALL_CONSTRUCTORS)) {
195        if (ci.GetCustomAttributes(typeof(StorableConstructorAttribute), false).Length > 0) {
196          if (ci.GetParameters().Length != 1 ||
197              ci.GetParameters()[0].ParameterType != typeof(bool))
198            throw new PersistenceException("StorableConstructor must have exactly one argument of type bool");
199          DynamicMethod dm = new DynamicMethod("", typeof(object), null, type);
200          ILGenerator ilgen = dm.GetILGenerator();
201          ilgen.Emit(OpCodes.Ldc_I4_1); // load true
202          ilgen.Emit(OpCodes.Newobj, ci);
203          ilgen.Emit(OpCodes.Ret);
204          return (Constructor)dm.CreateDelegate(typeof(Constructor));
205        }
206      }
207      return null;
208    }
209
210    private IEnumerable<DataMemberAccessor> GetStorableAccessors(object obj) {
211      return GetStorableMembers(obj.GetType())
212        .Select(mi => new DataMemberAccessor(mi.MemberInfo, mi.DisentangledName, mi.DefaultValue, obj));
213    }
214
215    private void InvokeHook(HookType hookType, object obj) {
216      if (obj == null)
217        throw new ArgumentNullException("Cannot invoke hooks on null");
218      foreach (StorableReflection.Hook hook in GetHooks(hookType, obj.GetType())) {
219        hook(obj);
220      }
221    }
222
223    private IEnumerable<StorableReflection.Hook> GetHooks(HookType hookType, Type type) {
224      lock (hookCache) {
225        List<StorableReflection.Hook> hooks;
226        var designator = new HookDesignator(type, hookType);
227        hookCache.TryGetValue(designator, out hooks);
228        if (hooks != null)
229          return hooks;
230        hooks = new List<StorableReflection.Hook>(StorableReflection.CollectHooks(hookType, type));
231        hookCache.Add(designator, hooks);
232        return hooks;
233      }
234    }
235
236    #endregion
237
238
239
240  }
241
242}
Note: See TracBrowser for help on using the repository browser.