Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceSpeedUp/HeuristicLab.Persistence/3.3/Core/CachedTypeSerializer.cs @ 6737

Last change on this file since 6737 was 6737, checked in by epitzer, 13 years ago

#1530 Split type and serializer tokens and include special handling for CachedTypeSerializer (this should also fix #1527)

File size: 2.2 KB
Line 
1using System;
2using System.Linq;
3using System.Collections.Generic;
4using HeuristicLab.Persistence.Auxiliary;
5using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
6using HeuristicLab.Persistence.Interfaces;
7
8namespace HeuristicLab.Persistence.Core {
9
10  [StorableClass]
11  internal sealed class CachedTypeSerializer : ICompositeSerializer {
12
13    [StorableConstructor]
14    private CachedTypeSerializer(bool deserializing) { }
15
16    private TypeCache typeCache;
17    private Dictionary<int, Type> deserializationTypeCache;
18
19    internal CachedTypeSerializer(TypeCache typeCache) {
20      this.typeCache = typeCache;
21    }
22
23    internal CachedTypeSerializer(Dictionary<int, Type> deserializationTypeCache) {
24      this.deserializationTypeCache = deserializationTypeCache;
25    }
26
27    public int Priority {
28      get { return 1000; }
29    }
30
31    public bool CanSerialize(Type type) {
32      return type == typeof(Type) || type.VersionInvariantName() == "System.RuntimeType, mscorlib";
33    }
34
35    public string JustifyRejection(Type type) {
36      return "not System.Type nor System.RuntimeType";
37    }
38
39    public IEnumerable<Tag> CreateMetaInfo(object o) {
40      yield return new Tag("TypeId", typeCache.GetOrCreateId((Type)o));
41    }
42
43    public IEnumerable<Tag> Decompose(object obj) {
44      return new Tag[] { };
45    }
46
47    public object CreateInstance(Type type, IEnumerable<Tag> metaInfo) {
48      int typeId = -1;
49      try {
50        typeId = (int)metaInfo.First().Value;
51        return deserializationTypeCache[typeId];
52      } catch (InvalidOperationException e) {
53        throw new PersistenceException("Insufficient meta information to instantiate Type object", e);
54      } catch (InvalidCastException e) {
55        throw new PersistenceException("Invalid meta information during reconstruction of Type object", e);
56      } catch (KeyNotFoundException e) {
57        throw new PersistenceException(String.Format(
58          "TypeCache has not been loaded with type id {0}, make sure all required assemblies are available.",
59          typeId), e);
60      }
61    }
62
63    public void Populate(object instance, IEnumerable<Tag> objects, Type type) {
64      // Type ojects are populated during instance creation.
65    }
66  }
67}
Note: See TracBrowser for help on using the repository browser.