-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStructBinarySerializer.cs
More file actions
37 lines (34 loc) · 1.3 KB
/
StructBinarySerializer.cs
File metadata and controls
37 lines (34 loc) · 1.3 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
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine;
namespace Gilzoide.KeyValueStore.ObjectSerializers
{
public class StructBinarySerializer : IBinarySerializer
{
unsafe public byte[] SerializeObject<T>(T obj)
{
Debug.AssertFormat(UnsafeUtility.IsUnmanaged(typeof(T)), "Expected an unmanaged type, got {0}", typeof(T));
int sizeOfT = UnsafeUtility.SizeOf(typeof(T));
var buffer = new byte[sizeOfT];
fixed (void* bufferPtr = buffer)
{
UnsafeUtility.MemCpy(bufferPtr, UnsafeUtility.AddressOf(ref UnsafeUtility.As<T, int>(ref obj)), sizeOfT);
}
return buffer;
}
unsafe public bool TryDeserializeObject<T>(byte[] bytes, out T value)
{
Debug.AssertFormat(UnsafeUtility.IsUnmanaged(typeof(T)), "Expected an unmanaged type, got {0}", typeof(T));
value = default;
int sizeOfT = UnsafeUtility.SizeOf(typeof(T));
if (bytes.Length < sizeOfT)
{
return false;
}
fixed (void* bufferPtr = bytes)
{
UnsafeUtility.MemCpy(UnsafeUtility.AddressOf(ref UnsafeUtility.As<T, int>(ref value)), bufferPtr, sizeOfT);
}
return true;
}
}
}