1 | using System;
|
---|
2 | using System.Collections.Generic;
|
---|
3 | using HeuristicLab.Persistence.Interfaces;
|
---|
4 |
|
---|
5 | namespace HeuristicLab.Persistence.Core {
|
---|
6 |
|
---|
7 | public sealed class ReverseTypeCache {
|
---|
8 |
|
---|
9 | private readonly Dictionary<int, object> typeId2SerializerMapping;
|
---|
10 | private readonly Dictionary<Type, object> serializerInstances;
|
---|
11 | private readonly Dictionary<int, Type> typeIds;
|
---|
12 |
|
---|
13 | public ReverseTypeCache() {
|
---|
14 | typeId2SerializerMapping = new Dictionary<int, object>();
|
---|
15 | serializerInstances = new Dictionary<Type, object>();
|
---|
16 | typeIds = new Dictionary<int, Type>();
|
---|
17 | }
|
---|
18 |
|
---|
19 | public void AddSerializer(int typeId, Type serializerType) {
|
---|
20 | if (typeId2SerializerMapping.ContainsKey(typeId))
|
---|
21 | return;
|
---|
22 | object serializerInstance;
|
---|
23 | if (!serializerInstances.TryGetValue(serializerType, out serializerInstance)) {
|
---|
24 | if (serializerType == typeof(CachedTypeSerializer)) {
|
---|
25 | serializerInstance = new CachedTypeSerializer(typeIds);
|
---|
26 | } else {
|
---|
27 | serializerInstance = serializerType.GetConstructor(System.Type.EmptyTypes).Invoke(new object[0]);
|
---|
28 | }
|
---|
29 | serializerInstances.Add(serializerType, serializerInstance);
|
---|
30 | }
|
---|
31 | typeId2SerializerMapping.Add(typeId, serializerInstance);
|
---|
32 | }
|
---|
33 |
|
---|
34 | public void AddType(int typeId, Type type) {
|
---|
35 | typeIds.Add(typeId, type);
|
---|
36 | }
|
---|
37 |
|
---|
38 | public Type GetType(int id) {
|
---|
39 | return typeIds[id];
|
---|
40 | }
|
---|
41 |
|
---|
42 | public ICompositeSerializer GetCompositeSerializer(int typeId) {
|
---|
43 | return (ICompositeSerializer)typeId2SerializerMapping[typeId];
|
---|
44 | }
|
---|
45 |
|
---|
46 | public IPrimitiveSerializer GetPrimitiveSerializer(int typeId) {
|
---|
47 | return (IPrimitiveSerializer)typeId2SerializerMapping[typeId];
|
---|
48 | }
|
---|
49 | }
|
---|
50 | }
|
---|