-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObjectSerializer.cs
More file actions
304 lines (249 loc) · 11.4 KB
/
ObjectSerializer.cs
File metadata and controls
304 lines (249 loc) · 11.4 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
/*
BSD 3-Clause License
Copyright (c) 2024, Jooty
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
*/
using Imcodec.IO;
using Imcodec.ObjectProperty.TypeCache;
namespace Imcodec.ObjectProperty;
[Flags]
public enum SerializerFlags {
/// <summary>
/// States the serializer should use no flags.
/// </summary>
None,
/// <summary>
/// States the serializer should use these flags for deserialization.
/// </summary>
UseFlags = 1 << 0,
/// <summary>
/// States the serializer should use compact length prefixes.
/// </summary>
CompactLength = 1 << 1,
/// <summary>
/// States the serializer should use string enums.
/// </summary>
StringEnums = 1 << 2,
/// <summary>
/// States the serializer should use ZLib compression.
/// </summary>
Compress = 1 << 3,
/// <summary>
/// Properties are dirty encoded.
/// </summary>
DirtyEncode = 1 << 4,
}
/// <summary>
/// An object serializer that serializes and deserializes
/// <see cref="PropertyClass"/> objects.
/// <remarks>
/// Initializes a new instance of the <see cref="ObjectSerializer"/> class.
/// </remarks>
/// <param name="Versionable">States whether the object is versionable.</param>
/// <param name="Behaviors">States the behaviors of the serializer.</param>
/// <param name="typeRegistry">The type registry to use for serialization.</param>
public partial class ObjectSerializer(bool Versionable = true,
SerializerFlags Behaviors = SerializerFlags.None,
TypeRegistry? typeRegistry = null) {
/// <summary>
/// States whether the object is versionable. If true, <see cref="Property"/>
/// data is prefixed with a hash of the <see cref="PropertyClass"/> type as
/// well as the size of the data in bits.
/// </summary>
public bool Versionable { get; set; } = Versionable;
/// <summary>
/// States the behaviors of the serializer.
/// </summary>
public SerializerFlags SerializerFlags { get; set; } = Behaviors;
/// <summary>
/// The property flags to use for serialization.
/// </summary>
public PropertyFlags PropertyMask { get; set; }
= PropertyFlags.Prop_Transmit | PropertyFlags.Prop_AuthorityTransmit;
/// <summary>
/// The type registry to dispatch types from.
/// </summary>
public TypeRegistry TypeRegistry { get; set; } = typeRegistry ?? s_defaultTypeRegistry;
private static readonly ClientGeneratedTypeRegistry s_defaultTypeRegistry = new();
/// <summary>
/// Serializes the specified <see cref="PropertyClass"/> object using
/// the provided property mask.
/// </summary>
/// <param name="input">The <see cref="PropertyClass"/> object to serialize.</param>
/// <param name="propertyMask">The property mask to use for serialization.</param>
/// <param name="output">The serialized byte array output.</param>
/// <returns><c>true</c> if the serialization is successful; otherwise, <c>false</c>.</returns>
public virtual bool Serialize(PropertyClass input,
uint propertyMask,
out byte[]? output) {
var castedFlags = (PropertyFlags) propertyMask;
return Serialize(input, castedFlags, out output);
}
/// <summary>
/// Serializes the specified <see cref="PropertyClass"/> object using
/// the provided <see cref="PropertyFlags"/> mask.
/// </summary>
/// <param name="input">The <see cref="PropertyClass"/> object to serialize.</param>
/// <param name="propertyMask">The <see cref="PropertyFlags"/> mask to
/// apply during serialization.</param>
/// <param name="output">The serialized byte array output.</param>
public virtual bool Serialize(PropertyClass input,
PropertyFlags propertyMask,
out byte[]? output) {
output = default;
this.PropertyMask = propertyMask;
var writer = new BitWriter();
// If the flags request it, ensure our BitWriter is writing with compact lengths.
if (SerializerFlags.HasFlag(SerializerFlags.CompactLength)) {
writer.WithCompactLengths();
}
if (!PreWriteObject(writer, input)) {
return false;
}
// Tell the property class to encode its properties.
if (!input.Encode(writer, this)) {
return false;
}
// If the behaviors flag is set to use compression,
// compress the output buffer.
if (SerializerFlags.HasFlag(SerializerFlags.Compress)) {
writer = Compress(writer);
}
output = writer.GetData();
return true;
}
/// <summary>
/// Deserializes the input buffer into an instance of the specified type.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize.</typeparam>
/// <param name="inputBuffer">The input buffer containing the serialized data.</param>
/// <param name="propertyMask">The property mask to use for serialization.</param>
/// <param name="output">When this method returns, contains the deserialized
/// object of type <typeparamref name="T"/>.</param>
/// <returns><c>true</c> if the deserialization is successful; otherwise,
public virtual bool Deserialize<T>(byte[] inputBuffer,
uint propertyMask,
out T? output) where T : PropertyClass {
var castedFlags = (PropertyFlags) propertyMask;
return Deserialize(inputBuffer, castedFlags, out output);
}
/// <summary>
/// Deserializes the input buffer into an instance of the specified type.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize.</typeparam>
/// <param name="inputBuffer">The input buffer containing the serialized data.</param>
/// <param name=""propertyMask"">The property flags to use for serialization.</param>
/// <param name="output">When this method returns, contains the deserialized
/// object of type <typeparamref name="T"/>.</param>
/// <returns><c>true</c> if the deserialization is successful; otherwise,
/// <c>false</c>.</returns>
public virtual bool Deserialize<T>(byte[] inputBuffer,
PropertyFlags propertyMask,
out T? output) where T : PropertyClass {
output = default;
this.PropertyMask = propertyMask;
var reader = new BitReader(inputBuffer);
// If the behaviors flag is set to use compression, decompress the input buffer.
if (SerializerFlags.HasFlag(SerializerFlags.Compress)) {
reader = Decompress(reader);
if (reader == null) {
return false;
}
}
// If the flags request it, ensure our BitReader is reading with compact lengths.
if (SerializerFlags.HasFlag(SerializerFlags.CompactLength)) {
reader.WithCompactLengths();
}
if (!PreloadObject(reader, out var propertyClass)) {
return false;
}
propertyClass?.Decode(reader, this);
output = (T) propertyClass!;
return true;
}
/// <summary>
/// Preloads an object from the input buffer based on the provided hash value.
/// </summary>
/// <param name="inputBuffer">The input buffer containing the serialized data.</param>
/// <param name="propertyClass">The loaded property class, if found.</param>
/// <returns><c>true</c> if the object was preloaded successfully; otherwise, <c>false</c>.</returns>
public virtual bool PreloadObject(BitReader inputBuffer,
out PropertyClass? propertyClass) {
var hash = inputBuffer.ReadUInt32();
if (hash == 0) {
propertyClass = null;
return false;
}
propertyClass = DispatchType(hash);
return propertyClass != null;
}
/// <summary>
/// Writes the object identifier to the specified <see cref="BitWriter"/>.
/// </summary>
/// <param name="writer">The <see cref="BitWriter"/> to write to.</param>
/// <param name="propertyClass">The <see cref="PropertyClass"/> to write.</param>
/// <returns><c>true</c> if the object identifier was written successfully; otherwise, <c>false</c>.</returns>
public virtual bool PreWriteObject(BitWriter writer,
PropertyClass propertyClass) {
if (propertyClass == null) {
writer.WriteUInt32(0);
return false;
}
writer.WriteUInt32(propertyClass.GetHash());
return true;
}
/// <summary>
/// Compresses the data using the specified <see cref="BitWriter"/>.
/// </summary>
/// <param name="writer">The <see cref="BitWriter"/> containing the data
/// to compress.</param>
/// <returns>A <see cref="BitWriter"/> containing the compressed data.</returns>
protected virtual BitWriter Compress(BitWriter writer) {
var uncompressedSize = writer.GetData().Length;
var compressedData = Compression.Compress(writer.GetData());
var bufferSize = compressedData.Length + 4;
var tempBuffer = new byte[bufferSize];
using var memoryStream = new MemoryStream(tempBuffer);
using var binaryWriter = new BinaryWriter(memoryStream);
binaryWriter.Write(uncompressedSize);
binaryWriter.Write(compressedData);
return new BitWriter(tempBuffer);
}
/// <summary>
/// Decompresses the data using the specified <see cref="BitReader"/>.
/// </summary>
/// <param name="inputBuffer">The cref="BitReader"/> containing
/// the compressed data.</param>
/// <returns>A <see cref="BitReader"/> containing the decompressed data.</returns>
protected virtual BitReader? Decompress(BitReader inputBuffer) {
var uncompressedLength = inputBuffer.ReadInt32();
var decompressedData = Compression.Decompress(inputBuffer.GetData()[4..]);
// If the decompressed data length does not match the recorded length,
// log it and return null.
if (decompressedData.Length != uncompressedLength) {
throw new Exception("Decompressed data length does not match the recorded length.");
}
return new BitReader(decompressedData);
}
/// <summary>
/// Dispatches the type based on the provided hash value.
/// </summary>
/// <param name="hash">The hash value to dispatch.</param>
/// <returns>The dispatched <see cref="PropertyClass"/> type, if found; otherwise, <c>null</c>.</returns>
protected PropertyClass? DispatchType(uint hash) {
var lookupType = TypeRegistry.LookupType(hash);
if (lookupType == null) {
return null;
}
return (PropertyClass) Activator.CreateInstance(lookupType)!;
}
}