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

Last change on this file since 1361 was 1361, checked in by epitzer, 12 years ago

Split all classes into their own file (#506)

File size: 6.4 KB
Line 
1using System.Collections.Generic;
2using System;
3using HeuristicLab.Persistence.Interfaces;
4
5namespace HeuristicLab.Persistence.Core {
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 CustomComposite : IAccessibleObject {
19
20    public object Obj { get; private set; }
21    public readonly List<object> customValues;
22
23    public CustomComposite(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 StorableComposite : IAccessibleObject {
40
41    public object Obj { get; private set; }
42    public readonly Dictionary<string, DataMemberAccessor> accessorDict;
43
44    public StorableComposite(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> parentStack;
79    private readonly Configuration configuration;
80    private readonly Dictionary<int, Type> typeIds;   
81    private List<Thunk> finalFixes;
82
83    public DeSerializer(
84      IEnumerable<KeyValuePair<string, int>> typeCache,
85      Configuration configuration) {
86      this.configuration = configuration;
87      id2obj = new Dictionary<int, object>();
88      parentStack = 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 parentStack.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 (configuration.GetDecomposer(type) != null) {
119        instance = new ParentReference();
120        parentStack.Push(new CustomComposite(instance));       
121      } else {       
122        instance = Activator.CreateInstance(type, true);
123        Dictionary<string, DataMemberAccessor> accessorDict =
124          StorableAttribute.GetAutostorableAccessors(instance);
125        parentStack.Push(new StorableComposite(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 = configuration.GetDecomposer(type);
135      if (decomposer != null) {
136        CustomComposite customComposite = (CustomComposite)parentStack.Pop();
137        object deserializedObject =
138          decomposer.Compose(customComposite.customValues, type);
139        if ( end.Id != null )
140          id2obj[(int)end.Id] = deserializedObject;       
141        SetValue(end.Name, deserializedObject);         
142      } else {
143        StorableComposite storableComposite = (StorableComposite)parentStack.Pop();
144        storableComposite.PopulateDefaultValues();
145        SetValue(end.Name, storableComposite.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 = configuration
153        .GetFormatter(type)
154        .Parse(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 = parentStack.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 (parentStack.Count == 0) {
178        parentStack.Push(new StorableComposite(value, new Dictionary<string, DataMemberAccessor>()));
179      } else {
180        object accessibleObject = parentStack.Peek();
181        if (accessibleObject is StorableComposite) {
182          ((StorableComposite)accessibleObject).SetValue(name, value);
183        } else if (accessibleObject is CustomComposite) {
184          ((CustomComposite)accessibleObject).AddValue(value);
185        }
186      }
187    }
188  }
189}
Note: See TracBrowser for help on using the repository browser.