Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Persistence/3.3/Core/DeSerializer.cs @ 1848

Last change on this file since 1848 was 1823, checked in by epitzer, 15 years ago

Namespace refactoring: rename formatters & decomposers -> primitive and composite serializers. (#603)

File size: 5.9 KB
Line 
1using System.Collections.Generic;
2using System;
3using HeuristicLab.Persistence.Interfaces;
4using HeuristicLab.Persistence.Core.Tokens;
5using HeuristicLab.Persistence.Auxiliary;
6using HeuristicLab.Tracing;
7using System.Reflection;
8
9namespace HeuristicLab.Persistence.Core {
10
11  public class Deserializer {
12
13    class Midwife {
14
15      public int? Id { get; private set; }
16      public bool MetaMode { get; set; }
17      public object Obj { get; private set; }
18
19      private List<Tag> metaInfo;
20      private List<Tag> customValues;
21      private Type type;
22      private ICompositeSerializer compositeSerializer;
23
24      public Midwife(object value) {
25        this.Obj = value;
26      }
27
28      public Midwife(Type type, ICompositeSerializer compositeSerializer, int? id) {
29        this.type = type;
30        this.compositeSerializer = compositeSerializer;
31        this.Id = id;
32        MetaMode = false;
33        metaInfo = new List<Tag>();
34        customValues = new List<Tag>();
35      }
36
37      public void CreateInstance() {
38        if (Obj != null)
39          throw new PersistenceException("object already instantiated");
40        Obj = compositeSerializer.CreateInstance(type, metaInfo);
41      }
42
43      public void AddValue(string name, object value) {
44        if (MetaMode) {
45          metaInfo.Add(new Tag(name, value));
46        } else {
47          customValues.Add(new Tag(name, value));
48        }
49      }
50
51      public void Populate() {
52        compositeSerializer.Populate(Obj, customValues, type);
53      }
54    }
55
56    private readonly Dictionary<int, object> id2obj;
57    private readonly Dictionary<Type, object> serializerMapping;
58    private readonly Stack<Midwife> parentStack;
59    private readonly Dictionary<int, Type> typeIds;
60
61    public Deserializer(
62      IEnumerable<TypeMapping> typeCache) {
63      id2obj = new Dictionary<int, object>();
64      parentStack = new Stack<Midwife>();
65      typeIds = new Dictionary<int, Type>();
66      serializerMapping = CreateSerializers(typeCache);
67    }
68
69    private Dictionary<Type, object> CreateSerializers(IEnumerable<TypeMapping> typeCache) {
70      try {
71        var map = new Dictionary<Type, object>();
72        foreach (var typeMapping in typeCache) {
73          Type type = TypeLoader.Load(typeMapping.TypeName);
74          typeIds.Add(typeMapping.Id, type);
75          Type serializerType = TypeLoader.Load(typeMapping.Serializer);
76          map.Add(type, Activator.CreateInstance(serializerType, true));
77        }
78        return map;
79      } catch (PersistenceException) {
80        throw;
81      } catch (Exception e) {
82        throw new PersistenceException(
83          "The serialization type cache could not be loaded.\r\n" +
84          "This usualy happens when you are missing an Assembly/Plugin.", e);
85      }
86    }
87
88
89    public object Deserialize(IEnumerable<ISerializationToken> tokens) {
90      foreach (ISerializationToken token in tokens) {
91        Type t = token.GetType();
92        if (t == typeof(BeginToken)) {
93          CompositeStartHandler((BeginToken)token);
94        } else if (t == typeof(EndToken)) {
95          CompositeEndHandler((EndToken)token);
96        } else if (t == typeof(PrimitiveToken)) {
97          PrimitiveHandler((PrimitiveToken)token);
98        } else if (t == typeof(ReferenceToken)) {
99          ReferenceHandler((ReferenceToken)token);
100        } else if (t == typeof(NullReferenceToken)) {
101          NullHandler((NullReferenceToken)token);
102        } else if (t == typeof(MetaInfoBeginToken)) {
103          MetaInfoBegin((MetaInfoBeginToken)token);
104        } else if (t == typeof(MetaInfoEndToken)) {
105          MetaInfoEnd((MetaInfoEndToken)token);
106        } else {
107          throw new PersistenceException("invalid token type");
108        }
109      }
110      return parentStack.Pop().Obj;
111    }
112
113    private void CompositeStartHandler(BeginToken token) {
114      Type type = typeIds[(int)token.TypeId];
115      ICompositeSerializer compositeSerializer = null;
116      if (serializerMapping.ContainsKey(type))
117        compositeSerializer = serializerMapping[type] as ICompositeSerializer;
118      if (compositeSerializer == null)
119        throw new PersistenceException(String.Format(
120          "No suitable method for deserialization of type \"{0}\" found.",
121          type.VersionInvariantName()));
122      parentStack.Push(new Midwife(type, compositeSerializer, token.Id));
123    }
124
125    private void CompositeEndHandler(EndToken token) {
126      Type type = typeIds[(int)token.TypeId];
127      Midwife midwife = parentStack.Pop();
128      if (midwife.Obj == null)
129        CreateInstance(midwife);
130      midwife.Populate();
131      SetValue(token.Name, midwife.Obj);
132    }
133
134    private void PrimitiveHandler(PrimitiveToken token) {
135      Type type = typeIds[(int)token.TypeId];
136      object value = ((IPrimitiveSerializer)serializerMapping[type]).Parse(token.SerialData);
137      if (token.Id != null)
138        id2obj[(int)token.Id] = value;
139      SetValue(token.Name, value);
140    }
141
142    private void ReferenceHandler(ReferenceToken token) {
143      object referredObject = id2obj[token.Id];
144      SetValue(token.Name, referredObject);
145    }
146
147    private void NullHandler(NullReferenceToken token) {
148      SetValue(token.Name, null);
149    }
150
151    private void MetaInfoBegin(MetaInfoBeginToken token) {
152      parentStack.Peek().MetaMode = true;
153    }
154
155    private void MetaInfoEnd(MetaInfoEndToken token) {
156      Midwife m = parentStack.Peek();
157      m.MetaMode = false;
158      CreateInstance(m);
159    }
160
161    private void CreateInstance(Midwife m) {
162      m.CreateInstance();
163      if (m.Id != null)
164        id2obj.Add((int)m.Id, m.Obj);
165    }
166
167    private void SetValue(string name, object value) {
168      if (parentStack.Count == 0) {
169        parentStack.Push(new Midwife(value));
170      } else {
171        Midwife m = parentStack.Peek();
172        if (m.MetaMode == false && m.Obj == null)
173          CreateInstance(m);
174        m.AddValue(name, value);
175      }
176    }
177  }
178}
Note: See TracBrowser for help on using the repository browser.