Free cookie consent management tool by TermsFeed Policy Generator

source: branches/New Persistence Exploration/Persistence/Persistence/Core/DeSerializer.cs @ 1437

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

Cleanup DeSerializer code. (#506)

File size: 5.5 KB
Line 
1using System.Collections.Generic;
2using System;
3using HeuristicLab.Persistence.Interfaces;
4
5namespace HeuristicLab.Persistence.Core { 
6
7  public struct ParentReference {} 
8
9  class CompositeObject {
10
11    public object Obj { get; private set; }
12    public List<Tag> customValues;
13
14    public CompositeObject(object obj) {
15      Obj = obj;
16      customValues = new List<Tag>();
17    }
18
19    public void AddValue(string name, object value, List<Thunk> finalFixes) {
20      Tag t = new Tag(name, value);
21      t.finalFixes = finalFixes;
22      customValues.Add(t);
23    }
24
25    public Setter GetSetterForLastAddedValue(string name) {           
26      Tag t = customValues[customValues.Count - 1];     
27      return value => t.Value = value;
28    }
29  }
30
31  public delegate void Thunk();
32
33  public class DeSerializer {
34   
35    private readonly Dictionary<int, object> id2obj;
36    private readonly Dictionary<Type, object> serializerMapping;   
37    private readonly Stack<CompositeObject> parentStack;   
38    private readonly Dictionary<int, Type> typeIds;   
39    private List<Thunk> finalFixes;
40
41    public DeSerializer(
42      IEnumerable<TypeMapping> typeCache) {     
43      id2obj = new Dictionary<int, object>();
44      parentStack = new Stack<CompositeObject>();
45      typeIds = new Dictionary<int, Type>();
46      serializerMapping = createSerializers(typeCache);
47    }
48
49    private Dictionary<Type, object> createSerializers(IEnumerable<TypeMapping> typeCache) {
50      var serializerMapping = new Dictionary<Type, object>();
51      foreach (var typeMapping in typeCache) {
52        Type type = Type.GetType(typeMapping.TypeName);
53        typeIds.Add(typeMapping.Id, type);
54        if (typeMapping.Serializer != null) {
55          Type serializerType = Type.GetType(typeMapping.Serializer);
56          serializerMapping.Add(type, Activator.CreateInstance(serializerType, true));
57        }
58      }
59      return serializerMapping;
60    }
61
62    public object DeSerialize(IEnumerable<ISerializationToken> tokens) {
63      finalFixes = new List<Thunk>();     
64      foreach (ISerializationToken token in tokens) {
65        Type t = token.GetType();
66        if ( t == typeof(BeginToken) ) {
67          CompositeStartHandler((BeginToken)token);
68        } else if ( t == typeof(EndToken) ) {
69          CompositeEndHandler((EndToken) token);
70        } else if ( t == typeof(PrimitiveToken) ) {
71          PrimitiveHandler((PrimitiveToken) token);
72        } else if ( t == typeof(ReferenceToken) ) {
73          ReferenceHandler((ReferenceToken) token);
74        } else if (t == typeof(NullReferenceToken)) {
75          NullHandler((NullReferenceToken)token);
76        } else {
77          throw new ApplicationException("invalid token type");
78        }
79      }
80      foreach (Thunk fix in finalFixes) {
81        fix();
82      }
83      return parentStack.Pop().Obj;
84    }
85
86    private void CompositeStartHandler(BeginToken token) {     
87      Type type = typeIds[(int)token.TypeId];
88      IDecomposer decomposer = null;
89      if ( serializerMapping.ContainsKey(type) )
90        decomposer = serializerMapping[type] as IDecomposer;     
91      if (decomposer == null)
92        throw new ApplicationException(String.Format(
93          "No suitable method for deserialization of type \"{0}\" found.",
94          type.VersionInvariantName()));
95      object instance = decomposer.CreateInstance(type);
96      if (instance == null)
97        instance = new ParentReference();
98      parentStack.Push(new CompositeObject(instance));             
99      if ( token.Id != null )
100        id2obj.Add((int)token.Id, instance);
101    }
102
103    private void CompositeEndHandler(EndToken token) {     
104      Type type = typeIds[(int)token.TypeId];
105      IDecomposer decomposer = null;
106      if (serializerMapping.ContainsKey(type))
107        decomposer = serializerMapping[type] as IDecomposer;           
108      if (decomposer == null)
109        throw new ApplicationException(String.Format(
110          "No suitable method for deserialization of type \"{0}\" found.",
111          type.VersionInvariantName()));
112      CompositeObject customComposite = (CompositeObject)parentStack.Pop();
113      object deserializedObject =         
114        decomposer.Populate(customComposite.Obj, customComposite.customValues, type);
115      if ( token.Id != null )
116        id2obj[(int)token.Id] = deserializedObject;       
117      SetValue(token.Name, deserializedObject);         
118    }
119
120    private void PrimitiveHandler(PrimitiveToken token) {     
121      Type type = typeIds[(int)token.TypeId];
122      object value = ((IFormatter) serializerMapping[type]).Parse(token.SerialData);
123      if ( token.Id != null )     
124        id2obj[(int)token.Id] = value;
125      SetValue(token.Name, value);
126    }
127
128    private void ReferenceHandler(ReferenceToken token) {     
129      object referredObject = id2obj[token.Id];
130      SetValue(token.Name, referredObject);     
131      if (referredObject is ParentReference) {
132        Setter set = parentStack.Peek().GetSetterForLastAddedValue(token.Name);               
133        finalFixes.Add(() => set(id2obj[token.Id]));
134      }
135    }
136
137    private void NullHandler(NullReferenceToken token) {     
138      SetValue(token.Name, null);
139    }   
140
141    private void SetValue(string name, object value) {
142      if (parentStack.Count == 0) {       
143        parentStack.Push(new CompositeObject(value));
144      } else {       
145        parentStack.Peek().AddValue(name, value, finalFixes);       
146      }
147    }
148  }
149}
Note: See TracBrowser for help on using the repository browser.