Free cookie consent management tool by TermsFeed Policy Generator

source: branches/New Persistence Exploration/Persistence/Persistence/DeSerializer.cs @ 1357

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

Pluginification and major refactoring. (#506)

File size: 6.5 KB
Line 
1using System.Collections.Generic;
2using System;
3using HeuristicLab.Persistence.Interfaces;
4
5namespace HeuristicLab.Persistence {
6
7
8  struct ParentReference { }
9  delegate void Setter(object value);
10
11
12  interface IAccessibleObject {
13    object Obj { get; }
14    Setter GetSetter(string name);
15  }
16
17
18  class CustomObject : IAccessibleObject {
19
20    public object Obj { get; private set; }
21    public readonly List<object> customValues;
22
23    public CustomObject(object obj) {
24      Obj = obj;
25      customValues = new List<object>();
26    }
27
28    public void AddValue(object value) {
29      customValues.Add(value);
30    }
31
32    public Setter GetSetter(string name) {
33      int index = customValues.Count - 1;
34      return value => customValues[index] = value;
35    }
36  }
37
38
39  class CompositeObject : IAccessibleObject {
40
41    public object Obj { get; private set; }
42    public readonly Dictionary<string, DataMemberAccessor> accessorDict;
43
44    public CompositeObject(object obj, Dictionary<string, DataMemberAccessor> accessorDict) {
45      Obj = obj;
46      this.accessorDict = new Dictionary<string, DataMemberAccessor>();
47      foreach (KeyValuePair<string, DataMemberAccessor> pair in accessorDict) {
48        this.accessorDict.Add(
49          pair.Value.Name,
50          pair.Value);
51      }
52    }
53
54    public void SetValue(string name, object value) {
55      accessorDict[name].Set(value);
56      accessorDict.Remove(name);
57    }
58
59    public Setter GetSetter(string name) {
60      return value => accessorDict[name].Set(value);
61    }
62
63    public void PopulateDefaultValues() {
64      foreach (var pair in accessorDict) {
65        pair.Value.Set(pair.Value.DefaultValue);
66      }
67    }
68  }
69
70
71  public class DeSerializer {
72
73    private delegate void Handler(ISerializationToken token);
74    private delegate void Thunk();
75
76    private readonly Dictionary<int, object> id2obj;
77    private readonly Dictionary<Type, Handler> handlers;
78    private readonly Stack<IAccessibleObject> compositeStack;
79    private readonly PersistenceConfiguration persistenceConfiguration;
80    private readonly Dictionary<int, Type> typeIds;   
81    private List<Thunk> finalFixes;
82
83    public DeSerializer(
84      IEnumerable<KeyValuePair<string, int>> typeCache,
85      PersistenceConfiguration persistenceConfiguration) {
86      this.persistenceConfiguration = persistenceConfiguration;
87      id2obj = new Dictionary<int, object>();
88      compositeStack = new Stack<IAccessibleObject>();
89      handlers = new Dictionary<Type, Handler> {
90                     {typeof (BeginToken), CompositeStartHandler},
91                     {typeof (EndToken), CompositeEndHandler},
92                     {typeof (PrimitiveToken), PrimitiveHandler},
93                     {typeof (ReferenceToken), ReferenceHandler},
94                     {typeof (NullReferenceToken), NullHandler}
95                   };     
96      typeIds = new Dictionary<int, Type>();
97      foreach ( var pair in typeCache ) {
98        Type type = Type.GetType(pair.Key);
99        typeIds.Add(pair.Value, type);
100      }
101    }
102
103    public object DeSerialize(IEnumerable<ISerializationToken> tokens) {
104      finalFixes = new List<Thunk>();
105      foreach (ISerializationToken token in tokens) {
106        handlers[token.GetType()].Invoke(token);
107      }
108      foreach (Thunk fix in finalFixes) {
109        fix();
110      }
111      return compositeStack.Pop().Obj;
112    }
113
114    private void CompositeStartHandler(ISerializationToken token) {
115      BeginToken start = (BeginToken)token;
116      object instance;     
117      Type type = typeIds[(int)start.TypeId];
118      if (persistenceConfiguration.GetDecomposer(type) != null) {
119        instance = new ParentReference();
120        compositeStack.Push(new CustomObject(instance));       
121      } else {       
122        instance = Activator.CreateInstance(type, true);
123        Dictionary<string, DataMemberAccessor> accessorDict =
124          StorableAttribute.GetAutostorableAccessors(instance);
125        compositeStack.Push(new CompositeObject(instance, accessorDict));       
126      }
127      if ( start.Id != null )
128        id2obj.Add((int)start.Id, instance);
129    }
130
131    private void CompositeEndHandler(ISerializationToken token) {
132      EndToken end = (EndToken)token;
133      Type type = typeIds[(int)end.TypeId];
134      IDecomposer decomposer = persistenceConfiguration.GetDecomposer(type);
135      if (decomposer != null) {
136        CustomObject customObject = (CustomObject)compositeStack.Pop();
137        object deserializedObject =
138          decomposer.DeSerialize(customObject.customValues, type);
139        if ( end.Id != null )
140          id2obj[(int)end.Id] = deserializedObject;       
141        SetValue(end.Name, deserializedObject);         
142      } else {
143        CompositeObject compositeObject = (CompositeObject)compositeStack.Pop();
144        compositeObject.PopulateDefaultValues();
145        SetValue(end.Name, compositeObject.Obj);
146      }
147    }
148
149    private void PrimitiveHandler(ISerializationToken token) {
150      PrimitiveToken primitive = (PrimitiveToken)token;
151      Type type = typeIds[(int)primitive.TypeId];
152      object value = persistenceConfiguration
153        .GetFormatter(XmlFormat.Instance, type)
154        .DeSerialize(primitive.SerialData);
155      if ( ! value.GetType().IsValueType )
156        id2obj[(int)primitive.Id] = value;
157      SetValue(primitive.Name, value);
158    }
159
160    private void ReferenceHandler(ISerializationToken token) {
161      ReferenceToken reference = (ReferenceToken)token;
162      object referredObject = id2obj[reference.Id];
163      SetValue(reference.Name, id2obj[reference.Id]);
164      if (referredObject is ParentReference) {
165        Setter set = compositeStack.Peek().GetSetter(reference.Name);       
166        int id = reference.Id;
167        finalFixes.Add(() => set(id2obj[id]));
168      }
169    }
170
171    private void NullHandler(ISerializationToken token) {
172      NullReferenceToken nil = (NullReferenceToken)token;
173      SetValue(nil.Name, null);
174    }
175
176    private void SetValue(string name, object value) {
177      if (compositeStack.Count == 0) {
178        compositeStack.Push(new CompositeObject(value, new Dictionary<string, DataMemberAccessor>()));
179      } else {
180        object accessibleObject = compositeStack.Peek();
181        if (accessibleObject is CompositeObject) {
182          ((CompositeObject)accessibleObject).SetValue(name, value);
183        } else if (accessibleObject is CustomObject) {
184          ((CustomObject)accessibleObject).AddValue(value);
185        }
186      }
187    }
188  }
189}
Note: See TracBrowser for help on using the repository browser.