forked from sh-akira/VirtualMotionCapture
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySerializer.cs
More file actions
50 lines (47 loc) · 1.75 KB
/
Copy pathBinarySerializer.cs
File metadata and controls
50 lines (47 loc) · 1.75 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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace UnityMemoryMappedFile
{
public class BinarySerializer
{
private static Dictionary<Type, DataContractSerializer> serializerCache = new Dictionary<Type, DataContractSerializer>();
public static object Deserialize(byte[] data, Type type)
{
using (var ms = new MemoryStream(data))
using (var reader = XmlDictionaryReader.CreateBinaryReader(ms, null, new XmlDictionaryReaderQuotas() { MaxArrayLength = int.MaxValue }))
{
DataContractSerializer serializer;
if (serializerCache.TryGetValue(type, out serializer) == false)
{
serializer = new DataContractSerializer(type);
serializerCache[type] = serializer;
}
return serializer.ReadObject(reader);
}
}
public static byte[] Serialize(object target)
{
using (var ms = new MemoryStream())
using (var writer = XmlDictionaryWriter.CreateBinaryWriter(ms))
{
var type = target.GetType();
DataContractSerializer serializer;
if (serializerCache.TryGetValue(type, out serializer) == false)
{
serializer = new DataContractSerializer(type);
serializerCache[type] = serializer;
}
serializer.WriteObject(writer, target);
writer.Flush();
return ms.ToArray();
}
}
}
}