-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathSerializerSession.cs
More file actions
101 lines (86 loc) · 2.68 KB
/
Copy pathSerializerSession.cs
File metadata and controls
101 lines (86 loc) · 2.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// -----------------------------------------------------------------------
// <copyright file="SerializerSession.cs" company="Asynkron HB">
// Copyright (C) 2015-2017 Asynkron HB All rights reserved
// </copyright>
// -----------------------------------------------------------------------
using System;
using System.Collections.Generic;
namespace Wire
{
public class SerializerSession
{
public const int MinBufferSize = 9;
private readonly ushort _nextTypeId;
private readonly Dictionary<object, int> _objects;
public readonly Serializer Serializer;
private byte[] _buffer = new byte[MinBufferSize];
private int _nextObjectId;
private LinkedList<Type> _trackedTypes;
public SerializerSession(Serializer serializer)
{
Serializer = serializer;
if (serializer.Options.PreserveObjectReferences)
{
_objects = new Dictionary<object, int>();
}
_nextTypeId = (ushort) serializer.Options.KnownTypes.Length;
}
public void TrackSerializedObject(object obj)
{
try
{
_objects.Add(obj, _nextObjectId++);
}
catch (Exception x)
{
throw new Exception("Error tracking object ", x);
}
}
public bool TryGetObjectId(object obj, out int objectId)
{
return _objects.TryGetValue(obj, out objectId);
}
public bool ShouldWriteTypeManifest(Type type, out ushort index)
{
return !TryGetValue(type, out index);
}
public byte[] GetBuffer(int length)
{
if (length <= _buffer.Length)
{
return _buffer;
}
length = Math.Max(length, _buffer.Length*2);
_buffer = new byte[length];
return _buffer;
}
public bool TryGetValue(Type key, out ushort value)
{
if (_trackedTypes == null || _trackedTypes.Count == 0)
{
value = 0;
return false;
}
var j = _nextTypeId;
foreach (var t in _trackedTypes)
{
if (key == t)
{
value = j;
return true;
}
j++;
}
value = 0;
return false;
}
public void TrackSerializedType(Type type)
{
if (_trackedTypes == null)
{
_trackedTypes = new LinkedList<Type>();
}
_trackedTypes.AddLast(type);
}
}
}