Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceReintegration/HeuristicLab.Persistence/4.0/Core/Mapper.cs @ 15529

Last change on this file since 15529 was 15529, checked in by jkarder, 5 years ago

#2520: worked on new persistence

  • changed message definitions
  • updated transformers
  • worked on conversions
  • cleaned up
File size: 5.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Linq;
25using Google.Protobuf;
26
27namespace HeuristicLab.Persistence {
28  public sealed class Mapper {
29    internal class MappingEqualityComparer : IEqualityComparer<object> {
30      bool IEqualityComparer<object>.Equals(object x, object y) {
31        if (x == null && y == null) return true;
32        if (x == null ^ y == null) return false;
33        if (x.GetType() != y.GetType()) return false;
34
35        var type = x.GetType();
36        if (type.IsValueType || type == typeof(string)) return x.Equals(y);
37        return object.ReferenceEquals(x, y);
38      }
39
40      int IEqualityComparer<object>.GetHashCode(object obj) {
41        return obj == null ? 0 : obj.GetHashCode();
42      }
43    }
44
45    private static StaticCache staticCache;
46    private static object locker = new object();
47    public static StaticCache StaticCache {
48      get {
49        lock (locker) {
50          if (staticCache == null) staticCache = new StaticCache();
51          return staticCache;
52        }
53      }
54    }
55
56    private Index<ITransformer> transformers;
57    private Index<Type> types;
58
59    private Dictionary<uint, Box> boxId2Box;
60    private Dictionary<object, uint> object2BoxId;
61    private Dictionary<uint, object> boxId2Object;
62    private Index<string> strings;
63
64    public uint BoxCount { get; private set; }
65
66    public Mapper() {
67      transformers = new Index<ITransformer>();
68      types = new Index<Type>();
69
70      boxId2Box = new Dictionary<uint, Box>();
71      object2BoxId = new Dictionary<object, uint>(new MappingEqualityComparer());
72      boxId2Object = new Dictionary<uint, object>();
73      strings = new Index<string>();
74
75      BoxCount = 0;
76    }
77
78    #region Transformers
79    public uint GetTransformerId(ITransformer transformer) {
80      return transformers.GetIndex(transformer);
81    }
82
83    public ITransformer GetTransformer(uint transformerId) {
84      return transformers.GetValue(transformerId);
85    }
86    #endregion
87
88    #region Types
89    public uint GetTypeId(Type type) {
90      return types.GetIndex(type);
91    }
92
93    public Type GetType(uint typeId) {
94      return types.GetValue(typeId);
95    }
96    #endregion
97
98    #region Boxes
99    public uint GetBoxId(object o) {
100      uint boxId;
101
102      if (o == null)
103        boxId = 0;
104      else {
105        if (object2BoxId.TryGetValue(o, out boxId)) return boxId;
106        var type = o.GetType();
107        var typeInfo = StaticCache.GetTypeInfo(type);
108        if (typeInfo.Transformer == null) throw new ArgumentException("Cannot serialize object of type " + o.GetType());
109        boxId = ++BoxCount;
110        typeInfo.Used++;
111        object2BoxId.Add(o, boxId);
112        boxId2Box.Add(boxId, typeInfo.Transformer.ToBox(o, this));
113      }
114      return boxId;
115    }
116
117    public Box GetBox(uint boxId) {
118      return boxId2Box[boxId];
119    }
120
121    public object GetObject(uint boxId) {
122      object o;
123      if (boxId2Object.TryGetValue(boxId, out o)) return o;
124
125      Box box;
126      boxId2Box.TryGetValue(boxId, out box);
127
128      if (box == null)
129        o = null;
130      else {
131        var transformer = transformers.GetValue(box.TransformerId);
132        o = transformer.ToObject(box, this);
133        boxId2Object.Add(boxId, o);
134        transformer.FillFromBox(o, box, this);
135      }
136
137      return o;
138    }
139    #endregion
140
141    #region Strings
142    public uint GetStringId(string str) {
143      return strings.GetIndex(str);
144    }
145    public string GetString(uint stringId) {
146      return strings.GetValue(stringId);
147    }
148    #endregion
149
150    public object CreateInstance(Type type) {
151      try {
152        return StaticCache.GetTypeInfo(type).GetConstructor()();
153      } catch (Exception e) {
154        throw new PersistenceException("Deserialization failed.", e);
155      }
156    }
157
158    public static Bundle ToBundle(object o) {
159      var mapper = new Mapper();
160      var bundle = new Bundle();
161
162      bundle.RootBoxId = mapper.GetBoxId(o);
163      bundle.TransformerGuids.AddRange(mapper.transformers.GetValues().Select(x => x.Guid).Select(x => ByteString.CopyFrom(x.ToByteArray())));
164      bundle.TypeGuids.AddRange(mapper.types.GetValues().Select(x => ByteString.CopyFrom(StaticCache.GetGuid(x).ToByteArray())));
165      bundle.Boxes.AddRange(mapper.boxId2Box.OrderBy(x => x.Key).Select(x => x.Value));
166      bundle.Strings.AddRange(mapper.strings.GetValues());
167
168      return bundle;
169    }
170    public static object ToObject(Bundle bundle) {
171      var mapper = new Mapper();
172
173      mapper.transformers = new Index<ITransformer>(bundle.TransformerGuids.Select(x => new Guid(x.ToByteArray())).Select(StaticCache.GetTransformer));
174      mapper.types = new Index<Type>(bundle.TypeGuids.Select(x => StaticCache.GetType(new Guid(x.ToByteArray()))));
175      mapper.boxId2Box = bundle.Boxes.Select((b, i) => new { Box = b, Index = i }).ToDictionary(k => (uint)k.Index + 1, v => v.Box);
176      mapper.strings = new Index<string>(bundle.Strings);
177
178      return mapper.GetObject(bundle.RootBoxId);
179    }
180  }
181}
Note: See TracBrowser for help on using the repository browser.