Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 15020 was 15020, checked in by gkronber, 7 years ago

#2520: fixed unit tests checking for exceptions

File size: 5.7 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.ProtocolBuffers;
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 = null;
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    private Index<string> strings;
59    private Dictionary<uint, Box> boxId2Box;
60    private Dictionary<object, uint> object2BoxId;
61    private Dictionary<uint, object> boxId2object;
62
63    public uint BoxCount { get; private set; }
64
65    public Mapper() {
66      transformers = new Index<ITransformer>();
67      types = new Index<Type>();
68      strings = new Index<string>();
69      boxId2Box = new Dictionary<uint, Box>();
70      object2BoxId = new Dictionary<object, uint>(new MappingEqualityComparer());
71      boxId2object = new Dictionary<uint, object>();
72
73      BoxCount = 0;
74    }
75
76    public uint GetTransformerId(ITransformer transformer) {
77      return transformers.GetIndex(transformer);
78    }
79    public ITransformer GetTransformer(uint transformerId) {
80      return transformers.GetValue(transformerId);
81    }
82
83    public uint GetTypeId(Type type) {
84      return types.GetIndex(type);
85    }
86    public Type GetType(uint typeId) {
87      return types.GetValue(typeId);
88    }
89
90    public uint GetStringId(string str) {
91      return strings.GetIndex(str);
92    }
93    public string GetString(uint stringId) {
94      return strings.GetValue(stringId);
95    }
96
97    public Box GetBox(uint boxId) {
98      return boxId2Box[boxId];
99    }
100    public uint GetBoxId(object o) {
101      uint boxId;
102
103      if (o == null)
104        boxId = 0;
105      else {
106        if (object2BoxId.TryGetValue(o, out boxId)) return boxId;
107        var type = o.GetType();
108        var typeInfo = StaticCache.GetTypeInfo(type);
109        if (typeInfo.Transformer == null) throw new ArgumentException("Cannot serialize object of type " + o.GetType());
110        boxId = ++BoxCount;
111        typeInfo.Used++;
112        object2BoxId.Add(o, boxId);
113        boxId2Box.Add(boxId, typeInfo.Transformer.ToBox(o, this));
114      }
115      return boxId;
116    }
117    public object GetObject(uint boxId) {
118      object o;
119      if (boxId2object.TryGetValue(boxId, out o)) return o;
120
121      Box box;
122      boxId2Box.TryGetValue(boxId, out box);
123
124      if (box == null)
125        o = null;
126      else {
127        var transformer = transformers.GetValue(box.TransformerId);
128        o = transformer.ToObject(box, this);
129        boxId2object.Add(boxId, o);
130        transformer.FillFromBox(o, box, this);
131      }
132      return o;
133    }
134
135    public object CreateInstance(Type type) {
136      try {
137        return StaticCache.GetTypeInfo(type).GetConstructor()();
138      } catch (Exception e) {
139        throw new PersistenceException("Deserialization failed.", e);
140      }
141    }
142
143    public static Bundle ToBundle(object o) {
144      var mapper = new Mapper();
145      var bundle = Bundle.CreateBuilder();
146      bundle.RootBoxId = mapper.GetBoxId(o);
147      bundle.AddRangeTransformerGuids(mapper.transformers.GetValues().Select(x => x.Guid).Select(x => ByteString.CopyFrom(x.ToByteArray())));
148      bundle.AddRangeTypeGuids(mapper.types.GetValues().Select(x => ByteString.CopyFrom(StaticCache.GetGuid(x).ToByteArray())));
149      bundle.AddRangeStrings(mapper.strings.GetValues());
150      bundle.AddRangeBoxes(mapper.boxId2Box.OrderBy(x => x.Key).Select(x => x.Value));
151      return bundle.Build();
152    }
153    public static object ToObject(Bundle bundle) {
154      var mapper = new Mapper();
155      mapper.types = new Index<Type>(bundle.TypeGuidsList.Select(x => StaticCache.GetType(new Guid(x.ToByteArray()))));
156      mapper.strings = new Index<string>(bundle.StringsList);
157      mapper.boxId2Box = bundle.BoxesList.Select((b, i) => new { Box = b, Index = i }).ToDictionary(k => (uint)k.Index + 1, v => v.Box);
158      mapper.transformers = new Index<ITransformer>(bundle.TransformerGuidsList.Select(x => new Guid(x.ToByteArray())).Select(x => StaticCache.GetTransformer(x)));
159      return mapper.GetObject(bundle.RootBoxId);
160    }
161  }
162}
Note: See TracBrowser for help on using the repository browser.