1 | using System;
|
---|
2 | using System.Linq;
|
---|
3 | using System.Collections.Generic;
|
---|
4 | using HeuristicLab.Persistence.Auxiliary;
|
---|
5 | using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
|
---|
6 | using HeuristicLab.Persistence.Interfaces;
|
---|
7 |
|
---|
8 | namespace 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 | }
|
---|