Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP - linq deserializers #55

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions Fauna/Serialization/LinqElementDeserializer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
namespace Fauna.Serialization;

public class LinqProjectionDeserializer<T> : BaseDeserializer<T>
{
private IDeserializer[] _fieldDeserializers;
private Delegate _mapper;

public LinqProjectionDeserializer(IDeserializer[] fields, Delegate mapper)
{
_fieldDeserializers = fields;
_mapper = mapper;
}

public override T Deserialize(SerializationContext context, ref Utf8FaunaReader reader)
{
if (reader.CurrentTokenType != TokenType.StartArray)
throw UnexpectedToken(reader.CurrentTokenType);

var fields = new object?[_fieldDeserializers.Length];

for (var i = 0; i < _fieldDeserializers.Length; i++)
{
if (!reader.Read()) throw new SerializationException("Unexpected end of stream");
if (reader.CurrentTokenType == TokenType.EndArray) throw UnexpectedToken(reader.CurrentTokenType);

fields[i] = _fieldDeserializers[i].Deserialize(context, ref reader);
}

if (!reader.Read()) throw new SerializationException("Unexpected end of stream");
if (reader.CurrentTokenType != TokenType.EndArray) throw UnexpectedToken(reader.CurrentTokenType);

return (T)_mapper.DynamicInvoke(fields)!;
}

private SerializationException UnexpectedToken(TokenType tokenType) =>
new SerializationException($"Unexpected token while deserializing LINQ element: {tokenType}");
}

public class LinqDocumentDeserializer<T> : BaseDeserializer<T>
{
private IDeserializer _docDeserializer;
private Delegate _mapper;

public LinqDocumentDeserializer(IDeserializer doc, Delegate mapper)
{
_docDeserializer = doc;
_mapper = mapper;
}

public override T Deserialize(SerializationContext context, ref Utf8FaunaReader reader)
{
var doc = _docDeserializer.Deserialize(context, ref reader);
return (T)_mapper.DynamicInvoke(new[] { doc })!;
}
}
Loading