Free cookie consent management tool by TermsFeed Policy Generator

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

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

Almost complete solution for correctly handling parent references. (#506)

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