forked from ch-robinson/dotnet-avro
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinarySerializer.cs
85 lines (78 loc) · 2.34 KB
/
BinarySerializer.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
using System;
using System.IO;
namespace Chr.Avro.Serialization
{
/// <summary>
/// Creates a binary Avro representation of an object.
/// </summary>
/// <typeparam name="T">
/// The type of object to serialize.
/// </typeparam>
public interface IBinarySerializer<T> : ISerializer<T>
{
/// <summary>
/// Serializes an object.
/// </summary>
/// <param name="value">
/// The object to serialize.
/// </param>
/// <returns>
/// The binary representation as an array of bytes.
/// </returns>
byte[] Serialize(T value);
}
/// <summary>
/// Creates a binary Avro representation of an object.
/// </summary>
/// <typeparam name="T">
/// The type of object to serialize.
/// </typeparam>
public class BinarySerializer<T> : IBinarySerializer<T>
{
/// <summary>
/// A serializer delegate.
/// </summary>
protected readonly Action<T, Stream> Delegate;
/// <summary>
/// Creates a new binary serializer.
/// </summary>
/// <param name="delegate">
/// A serializer delegate.
/// </param>
public BinarySerializer(Action<T, Stream> @delegate)
{
Delegate = @delegate ?? throw new ArgumentNullException(nameof(@delegate), "The encoder implementation cannot be null.");
}
/// <summary>
/// Serializes an object.
/// </summary>
/// <param name="value">
/// The object to serialize.
/// </param>
/// <returns>
/// The binary representation as an array of bytes.
/// </returns>
public virtual byte[] Serialize(T value)
{
var stream = new MemoryStream();
using (stream)
{
Delegate(value, stream);
}
return stream.ToArray();
}
/// <summary>
/// Serializes an object.
/// </summary>
/// <param name="value">
/// The object to serialize.
/// </param>
/// <param name="stream">
/// The stream to write the serialized object to. (The stream will not be disposed.)
/// </param>
public virtual void Serialize(T value, Stream stream)
{
Delegate(value, stream);
}
}
}