forked from ch-robinson/dotnet-avro
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryDeserializer.cs
79 lines (74 loc) · 2.27 KB
/
BinaryDeserializer.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
using System;
using System.IO;
namespace Chr.Avro.Serialization
{
/// <summary>
/// Creates an object from a binary Avro representation.
/// </summary>
/// <typeparam name="T">
/// The type of object to deserialize.
/// </typeparam>
public interface IBinaryDeserializer<T> : IDeserializer<T>
{
/// <summary>
/// Deserializes an object.
/// </summary>
/// <param name="blob">
/// The binary representation as an array of bytes.</param>
/// <returns>
/// The deserialized object.
/// </returns>
T Deserialize(byte[] blob);
}
/// <summary>
/// Creates an object from a binary Avro representation.
/// </summary>
/// <typeparam name="T">
/// The type of object to deserialize.
/// </typeparam>
public class BinaryDeserializer<T> : IBinaryDeserializer<T>
{
/// <summary>
/// A deserializer delegate.
/// </summary>
protected readonly Func<Stream, T> Delegate;
/// <summary>
/// Creates a new binary deserializer.
/// </summary>
/// <param name="delegate">
/// A deserializer delegate.
/// </param>
public BinaryDeserializer(Func<Stream, T> @delegate)
{
Delegate = @delegate ?? throw new ArgumentNullException(nameof(@delegate), "The decoder implementation cannot be null.");
}
/// <summary>
/// Deserializes an object.
/// </summary>
/// <param name="blob">
/// The binary representation as an array of bytes.</param>
/// <returns>
/// The deserialized object.
/// </returns>
public virtual T Deserialize(byte[] blob)
{
using (var stream = new MemoryStream(blob))
{
return Delegate(stream);
}
}
/// <summary>
/// Deserializes an object.
/// </summary>
/// <param name="stream">
/// The stream to read the serialized object from. (The stream will not be disposed.)
/// </param>
/// <returns>
/// The deserialized object.
/// </returns>
public virtual T Deserialize(Stream stream)
{
return Delegate(stream);
}
}
}