-
Notifications
You must be signed in to change notification settings - Fork 52
/
BinaryStringSerializerBuilderCase.cs
48 lines (46 loc) · 2.13 KB
/
BinaryStringSerializerBuilderCase.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
namespace Chr.Avro.Serialization
{
using System;
using System.Linq.Expressions;
using Chr.Avro.Abstract;
/// <summary>
/// Implements a <see cref="BinarySerializerBuilder" /> case that matches <see cref="StringSchema" />
/// and attempts to map it to any provided type.
/// </summary>
public class BinaryStringSerializerBuilderCase : StringSerializerBuilderCase, IBinarySerializerBuilderCase
{
/// <summary>
/// Builds a <see cref="BinarySerializer{T}" /> for a <see cref="StringSchema" />.
/// </summary>
/// <returns>
/// A successful <see cref="BinarySerializerBuilderCaseResult" /> if <paramref name="schema" />
/// is a <see cref="StringSchema" />; an unsuccessful <see cref="BinarySerializerBuilderCaseResult" />
/// otherwise.
/// </returns>
/// <exception cref="UnsupportedTypeException">
/// Thrown when <paramref name="type" /> cannot be converted to <see cref="string" />.
/// </exception>
/// <inheritdoc />
public virtual BinarySerializerBuilderCaseResult BuildExpression(Expression value, Type type, Schema schema, BinarySerializerBuilderContext context)
{
if (schema is StringSchema stringSchema)
{
var writeString = typeof(BinaryWriter)
.GetMethod(nameof(BinaryWriter.WriteString), new[] { typeof(string) });
try
{
return BinarySerializerBuilderCaseResult.FromExpression(
Expression.Call(context.Writer, writeString, BuildConversion(value, typeof(string))));
}
catch (InvalidOperationException exception)
{
throw new UnsupportedTypeException(type, $"Failed to map {stringSchema} to {type}.", exception);
}
}
else
{
return BinarySerializerBuilderCaseResult.FromException(new UnsupportedSchemaException(schema, $"{nameof(BinaryStringSerializerBuilderCase)} can only be applied to {nameof(StringSchema)}s."));
}
}
}
}