-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMessagePackBinarySerializer.cs
More file actions
82 lines (70 loc) · 2.84 KB
/
MessagePackBinarySerializer.cs
File metadata and controls
82 lines (70 loc) · 2.84 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
using System;
using MessagePack;
using MessagePack.Resolvers;
namespace Birko.Serialization.MessagePack
{
/// <summary>
/// MessagePack binary serializer. Provides compact binary serialization for high-performance scenarios.
/// </summary>
/// <remarks>
/// Requires NuGet package: MessagePack.
/// Default: ContractlessStandardResolver (no [MessagePackObject] attributes needed).
/// </remarks>
public class MessagePackBinarySerializer : ISerializer
{
private readonly MessagePackSerializerOptions _options;
public MessagePackBinarySerializer(MessagePackSerializerOptions? options = null)
{
_options = options ?? MessagePackSerializerOptions.Standard
.WithResolver(ContractlessStandardResolver.Instance);
}
public string ContentType => "application/x-msgpack";
public SerializationFormat Format => SerializationFormat.MessagePack;
public string Serialize(object value)
{
ArgumentNullException.ThrowIfNull(value);
var bytes = MessagePackSerializer.Serialize(value.GetType(), value, _options);
return Convert.ToBase64String(bytes);
}
public string Serialize<T>(T value)
{
ArgumentNullException.ThrowIfNull(value);
var bytes = MessagePackSerializer.Serialize(value, _options);
return Convert.ToBase64String(bytes);
}
public object? Deserialize(string data, Type type)
{
ArgumentNullException.ThrowIfNull(data);
ArgumentNullException.ThrowIfNull(type);
var bytes = Convert.FromBase64String(data);
return MessagePackSerializer.Deserialize(type, bytes, _options);
}
public T? Deserialize<T>(string data)
{
ArgumentNullException.ThrowIfNull(data);
var bytes = Convert.FromBase64String(data);
return MessagePackSerializer.Deserialize<T>(bytes, _options);
}
public byte[] SerializeToBytes(object value)
{
ArgumentNullException.ThrowIfNull(value);
return MessagePackSerializer.Serialize(value.GetType(), value, _options);
}
public byte[] SerializeToBytes<T>(T value)
{
ArgumentNullException.ThrowIfNull(value);
return MessagePackSerializer.Serialize(value, _options);
}
public object? DeserializeFromBytes(byte[] data, Type type)
{
ArgumentNullException.ThrowIfNull(data);
ArgumentNullException.ThrowIfNull(type);
return MessagePackSerializer.Deserialize(type, data, _options);
}
public T? DeserializeFromBytes<T>(byte[] data)
{
ArgumentNullException.ThrowIfNull(data);
return MessagePackSerializer.Deserialize<T>(data, _options);
}
}
}