/
MsgPackSerializer.cs
421 lines (363 loc) · 10.1 KB
/
MsgPackSerializer.cs
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using MsgPack;
using MsgPack.Serialization;
using System.Security;
using System.Runtime.InteropServices;
namespace CitizenFX.Core
{
[SecuritySafeCritical]
internal static class MsgPackSerializer
{
internal readonly static ByteArray nullResult;
[ThreadStatic]
private static bool ts_remote;
[SecuritySafeCritical]
static unsafe MsgPackSerializer()
{
byte* nullData = (byte*)Marshal.AllocCoTaskMem(1);
*nullData = 0xC0;
nullResult = new ByteArray(nullData, 1);
}
internal static byte[] Serialize(object obj, bool remote = false)
{
if (obj is object) // not null
{
ts_remote = remote;
var stream = new MemoryStream(256);
using (var packer = Packer.Create(stream, PackerCompatibilityOptions.None))
{
Serialize(obj, packer);
return stream.ToArray(); // other runtimes read the full length we give them, so shrink the buffer (copy)
//return stream.GetBuffer();
}
}
return new byte[] { 0xC0 }; // null
}
/// <summary>
/// Experimental, uses the CoTask memory instead of a managed byte[]
/// </summary>
/// <param name="obj"></param>
/// <param name="remote"></param>
/// <returns></returns>
internal static ByteArray SerializeCoTaskMemory(object obj, bool remote = false)
{
if (obj is object) // not null
{
ts_remote = remote;
var stream = new CoTaskMemoryStream(256);
using (var packer = Packer.Create(stream, PackerCompatibilityOptions.None))
{
Serialize(obj, packer);
//return stream.ToArray();
return stream.TakeBuffer();
}
}
return nullResult;
}
[SecuritySafeCritical]
private static void Serialize(object obj, Packer packer)
{
// This msgpack packer is heaven if you love checking all arguments *multiple* times and throwing exceptions all over the place (hence the checking it multiple times), lol
// SerializationContext.Default.GetSerializer<T>().PackTo(packer, obj) == packer.Pack<T>(obj) without all the hoops and checks
void Pack<T>(Packer p, T o) => SerializationContext.Default.GetSerializer<T>().PackTo(p, o);
if (obj is null)
{
packer.PackNull();
return;
}
var type = obj.GetType();
if (type.IsPrimitive
|| type == typeof(string) || type == typeof(decimal)
|| type == typeof(DateTime) || type == typeof(Guid))
{
Pack(packer, obj);
return;
}
else if (type.IsEnum)
{
// enums in C# may only be of an integer types
Pack(packer, Convert.ToUInt64(obj));
return;
}
else if (type.IsValueType) // structs in C#
{
switch (obj)
{
case Vector2 vec2:
unsafe
{
byte[] data = new byte[2 * sizeof(float)];
fixed (byte* ptr = data)
{
*((float*)ptr) = vec2.X;
*((float*)ptr + 1) = vec2.Y;
}
packer.PackExtendedTypeValue(20, data);
}
return;
case Vector3 vec3:
unsafe
{
byte[] data = new byte[3 * sizeof(float)];
fixed (byte* ptr = data)
{
*((float*)ptr) = vec3.X;
*((float*)ptr + 1) = vec3.Y;
*((float*)ptr + 2) = vec3.Z;
}
packer.PackExtendedTypeValue(21, data);
}
return;
case Vector4 vec4:
unsafe
{
byte[] data = new byte[4 * sizeof(float)];
fixed (byte* ptr = data)
{
*((float*)ptr) = vec4.X;
*((float*)ptr + 1) = vec4.Y;
*((float*)ptr + 2) = vec4.Z;
*((float*)ptr + 3) = vec4.W;
}
packer.PackExtendedTypeValue(22, data);
}
return;
case Quaternion quat:
unsafe
{
byte[] data = new byte[4 * sizeof(float)];
fixed (byte* ptr = data)
{
*((float*)ptr) = quat.X;
*((float*)ptr + 1) = quat.Y;
*((float*)ptr + 2) = quat.Z;
*((float*)ptr + 3) = quat.W;
}
packer.PackExtendedTypeValue(23, data);
}
return;
}
}
else if(obj is IEnumerable enumerable) // this includes any container like, arrays and generic ones (ICollection)
{
switch (enumerable)
{
case byte[] bytes:
Pack(packer, bytes);
return;
case IDictionary<string, object> dictStringObject: // more common than below, also faster iteration
{
packer.PackMapHeader(dictStringObject.Count);
foreach (var kvp in dictStringObject)
{
Serialize(kvp.Key, packer);
Serialize(kvp.Value, packer);
}
}
return;
case IDictionary dict: // less common than above, will handle all types of dictionaries. 1.3 (30%) times slower than above
{
packer.PackMapHeader(dict.Count);
foreach (DictionaryEntry kvp in dict)
{
Serialize(kvp.Key, packer);
Serialize(kvp.Value, packer);
}
}
return;
case IList array: // any array like, including T[] and List<T>
{
packer.PackArrayHeader(array.Count);
for (int i = 0; i < array.Count; ++i)
{
Serialize(array[i], packer);
}
}
return;
default: // unknown/undefined size, so go through them
{
var list = new List<object>();
foreach (var item in enumerable)
{
list.Add(item);
}
packer.PackArrayHeader(list.Count);
for (int i = 0; i < list.Count; ++i)
{
Serialize(list[i], packer);
}
}
return;
}
}
switch (obj)
{
case IPackable packable:
packable.PackToMessage(packer, null);
return;
case Delegate deleg:
PackDelegate(packer, deleg);
return;
}
// no suitable conversion found, serialize all public properties into a dictionary
// TODO: check if this is really what we want
var dictionary = new Dictionary<string, object>();
var properties = type.GetProperties();
for (int i = 0; i < properties.Length; ++i)
{
var property = properties[i];
dictionary[property.Name] = property.GetValue(obj, null);
}
/*
// fields as well?
var fields = type.GetFields();
for (int i = 0; i < fields.Length; ++i)
{
var field = fields[i];
dictionary[field.Name] = field.GetValue(obj);
}*/
Serialize(dictionary, packer);
}
[SecuritySafeCritical]
private static void PackDelegate(Packer packer, in Delegate deleg)
{
/*if (deleg is Callback)
{
var funcRef = deleg.Method.DeclaringType?.GetFields(
BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static
).FirstOrDefault(a => a.FieldType == typeof(RemoteFunction));
if (funcRef != null)
{
var remoteFunction = (RemoteFunction)funcRef.GetValue(deleg.Target);
DevDebug.WriteLine($"MsgPackSerializer:WriteDelegate({deleg}) {deleg.Method} {deleg.GetHashCode()} as ?");
packer.PackExtendedTypeValue(10, remoteFunction.Duplicate());
}
else
{
throw new ArgumentException("The CallbackDelegate does not contain a RemoteFunction capture.");
}
return;
}*/
var dynFunc = deleg as DynFunc ?? Func.Create(deleg);
if (!ts_remote)
{
var refType = ReferenceFunctionManager.Create(dynFunc);
packer.PackExtendedTypeValue(11, refType.Value);
}
else
{
#if REMOTE_FUNCTION_ENABLED
ulong callbackId;
if (deleg.Target is _RemoteHandler _pf)
{
callbackId = _pf.m_id;
}
else
{
callbackId = ExternalsManager.RegisterRemoteFunction(deleg.Method.ReturnType, new DynFunc(args =>
args.Length == 1 || args[1] == null ? dynFunc(args[0]) : null));
}
packer.PackExtendedTypeValue(10, Encoding.UTF8.GetBytes(callbackId.ToString()));
#endif
packer.PackNull();
}
}
}
/// <summary>
/// Experimental memory stream
/// </summary>
[SecuritySafeCritical]
internal class CoTaskMemoryStream : Stream
{
private unsafe IntPtr buffer;
private int capacity;
private int position;
private int length;
private bool canRead;
private bool canWrite;
public override bool CanRead => canRead;
public override bool CanSeek => false;
public override bool CanWrite => canWrite;
public override long Length => length;
public override long Position
{
get => position;
set
{
if (value < Length)
position = (int)value & int.MaxValue; // makes sure it's always >= 0
else
throw new NotSupportedException();
}
}
public unsafe CoTaskMemoryStream(byte* ptr, int size)
{
buffer = (IntPtr)ptr;
capacity = length = size;
position = 0;
canRead = true;
canWrite = false;
}
public unsafe CoTaskMemoryStream(int initialSize = 64)
{
buffer = Marshal.AllocCoTaskMem(initialSize);
capacity = initialSize;
position = length = 0;
canRead = false;
canWrite = true;
}
[SecurityCritical]
public unsafe ByteArray TakeBuffer()
{
var result = new ByteArray((byte*)buffer, (ulong)length);
buffer = IntPtr.Zero;
canRead = canWrite = false;
capacity = length = position = 0;
return result;
}
[SecuritySafeCritical]
public unsafe override void SetLength(long value)
{
int size = (int)value;
if (size < capacity)
length = size;
else if (value > capacity)
EnsureCapacity(size);
}
private void EnsureCapacity(int newCapacity)
{
// same setup as MemoryStream
int num = newCapacity;
if (num < 256)
num = 256;
if (num < capacity * 2)
num = capacity * 2;
if ((uint)(capacity * 2) > 2147483591u)
num = ((newCapacity > 2147483591) ? newCapacity : 2147483591);
buffer = Marshal.ReAllocCoTaskMem(buffer, num);
capacity = newCapacity;
}
[SecuritySafeCritical]
public unsafe override void Write(byte[] buffer, int offset, int count)
{
if (position + count > capacity)
EnsureCapacity(position + count);
Marshal.Copy(buffer, offset, this.buffer + position, count);
}
public override void Flush() { }
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotImplementedException();
}
[SecuritySafeCritical]
public override int Read(byte[] buffer, int offset, int count)
{
int length = Math.Min(count, this.length - position);
Marshal.Copy(this.buffer + position, buffer, offset, length);
return length;
}
}
}