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

First iteration of ParseObject #11

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
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
37 changes: 37 additions & 0 deletions Pevac.Tests/ObjectDeserializerTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using Xunit;
using FluentAssertions;
using System.Text;
using System.Text.Json;
using System;

namespace Pevac.Tests
{
public class ObjectDeserializerTests
{
private record Data(string Foo, string Bar);

[Fact]
public void DeserializeObject()
{
var json = @"
{
""foo"": ""foo"",
""bar"": ""bar""
}";

var bytes = Encoding.UTF8.GetBytes(json);
var reader = new Utf8JsonReader(bytes);

Parser<Data> parser = Parser.ParseObject(propertyName => propertyName switch
{
"foo" => from value in Parser.String
select new Func<Data, Data>(data => data with { Foo = value }),
"bar" => from value in Parser.String
select new Func<Data, Data>(data => data with { Bar = value }),
_ => Parser.Failure<Func<Data, Data>>()
}).Select(updater => updater(new Data("", "")));

Parser.Parse(parser, ref reader, default).Should().Be(new Data("foo", "bar"));
}
}
}
35 changes: 35 additions & 0 deletions Pevac/Parser/Parser.Object.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Pevac
{
public static partial class Parser
{
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static Parser<Func<T, T>?> ParseObject<T>(Func<string, Parser<Func<T, T>>> parserSelector)
{
return parserSelector switch
{
null => throw new ArgumentNullException(nameof(parserSelector)),
not null =>
from _ in StartObjectToken
from updaters in (from propertyName in PropertyName
#pragma warning disable CS8619 // Nullability of reference types in value doesn't match target type.
from updater in parserSelector(propertyName)
#pragma warning restore CS8619 // Nullability of reference types in value doesn't match target type.
select updater)
.Many()
from __ in EndObjectToken
select new Func<T, T>(t => updaters.Aggregate(t, (data, updater) => updater(data)))
}
;
}
}
}
7 changes: 7 additions & 0 deletions Pevac/Pevac.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.