Skip to main content

polytype by Eirik Tsarpalis

Nuget / site data

Nuget GitHub last commit GitHub Repo stars

Details

Info

info

Name: polytype

Practical Generic Programming for C#

Author: Eirik Tsarpalis

NuGet: https://www.nuget.org/packages/polytype/

You can find more details at https://github.com/eiriktsarpalis/PolyType

Source : https://github.com/eiriktsarpalis/PolyType

Original Readme

note

PolyType Build & Tests NuGet Badge

PolyType is a practical datatype-generic programming library for .NET types. It is a direct adaptation of the TypeShape library for F#, adapted to patterns and idioms available in C#. See the project website for additional background and API documentation.

Quick Start

You can try the library by installing the PolyType NuGet package:

$ dotnet add package PolyType

which includes the core types and source generator for generating type shapes:

using PolyType;

[GenerateShape]
public partial record Person(string name, int age);

Doing this will augment Person with an implementation of the IShapeable<Person> interface. This suffices to make Person usable with any library that targets the PolyType core abstractions. You can try this out by installing the built-in example libraries:

$ dotnet add package PolyType.Examples

Here's how the same value can be serialized to three separate formats.

using PolyType.Examples.JsonSerializer;
using PolyType.Examples.CborSerializer;
using PolyType.Examples.XmlSerializer;

Person person = new("Pete", 70);
JsonSerializerTS.Serialize(person); // {"Name":"Pete","Age":70}
XmlSerializer.Serialize(person); // <value><Name>Pete</Name><Age>70</Age></value>
CborSerializer.EncodeToHex(person); // A2644E616D656450657465634167651846

Since the application uses a source generator to produce the shape for Person, it is fully compatible with Native AOT. See the shape providers article for more details on how to use the library with your types.

Introduction

PolyType is a meta-library that facilitates rapid development of high performance datatype-generic programs. It exposes a simplified model for .NET types that makes it easy for library authors to publish production-ready components in just a few lines of code. The built-in source generator ensures that any library built on top of the PolyType abstractions gets Native AOT support for free.

As a library author, PolyType lets you write high performance, feature complete generic components that target its core abstractions. For example, a parser API using PolyType might look as follows:

public static class MyFancyParser
{
public static T? Parse<T>(string myFancyFormat) where T : IShapeable<T>;
}

As an end user, PolyType lets you generate shape models for your own types that can be used with one or more supported libraries:

Person? person = MyFancyParser.Parse<Person>(format); // Compiles

[GenerateShape] // Generate an IShapeable<TPerson> implementation
partial record Person(string name, int age, List<Person> children);

For more information see:

Case Study: Writing a JSON serializer

The repo includes a JSON serializer built on top of the Utf8JsonWriter/Utf8JsonReader primitives provided by System.Text.Json. At the time of writing, the full implementation is just under 1200 lines of code but exceeds STJ's built-in JsonSerializer both in terms of supported types and performance.

Performance

Here's a benchmark comparing System.Text.Json with the included PolyType implementation:

Serialization

MethodMeanRatioAllocatedAlloc Ratio
Serialize_StjReflection491.9 ns1.00312 B1.00
Serialize_StjSourceGen467.0 ns0.95312 B1.00
Serialize_StjSourceGen_FastPath227.2 ns0.46-0.00
Serialize_PolyTypeReflection277.9 ns0.57-0.00
Serialize_PolyTypeSourceGen273.6 ns0.56-0.00

Deserialization

MethodMeanRatioAllocatedAlloc Ratio
Deserialize_StjReflection1,593.0 ns1.001024 B1.00
Deserialize_StjSourceGen1,530.3 ns0.961000 B0.98
Deserialize_PolyTypeReflection773.1 ns0.49440 B0.43
Deserialize_PolyTypeSourceGen746.7 ns0.47440 B0.43

Even though both serializers target the same underlying reader and writer types, the PolyType implementation is ~75% faster for serialization and ~100% faster for deserialization, when compared with System.Text.Json's metadata serializer. As expected, fast-path serialization is still fastest since its implementation is fully inlined.

Known libraries based on PolyType

The following code bases are based upon PolyType and may be worth checking out.

  • Nerdbank.MessagePack - a MessagePack library with performance to rival MessagePack-CSharp, and greater simplicity and additional features.

Project structure

The repo consists of the following projects:

  • The core PolyType library containing:
  • The PolyType.SourceGenerator project contains the built-in source generator implementation.
  • The PolyType.Roslyn library exposes a set of components for extracting data models from Roslyn type symbols. Used as the foundation for the built-in source generator.
  • PolyType.Examples containing library examples:
    • A serializer built on top of System.Text.Json,
    • A serializer built on top of System.Xml,
    • A serializer built on top of System.Formats.Cbor,
    • A ConfigurationBinder like implementation,
    • A simple pretty-printer for .NET values,
    • A generic random value generator based on System.Random,
    • A JSON schema generator for .NET types,
    • An object cloning function,
    • A structural IEqualityComparer<T> generator for POCOs and collections,
    • An object validator in the style of System.ComponentModel.DataAnnotations.
    • A simple .NET object mapper.
  • The applications folder contains sample Native AOT console applications.

About

note

Generating shape like reflection from classes. See PolyType.Examples for more details

How to use

Example ( source csproj, source files )

This is the CSharp Project that references polytype

<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="PolyType" Version="0.16.1" />
<PackageReference Include="PolyType.Examples" Version="0.16.1" />
</ItemGroup>
<PropertyGroup>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
<CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
</PropertyGroup>
</Project>

Generated Files

Those are taken from $(BaseIntermediateOutputPath)\GX

// <auto-generated/>

#nullable enable annotations
#nullable disable warnings

namespace ConsoleApp1
{
public partial record Person : global::PolyType.IShapeable<global::ConsoleApp1.Person>
{
static global::PolyType.Abstractions.ITypeShape<global::ConsoleApp1.Person> global::PolyType.IShapeable<global::ConsoleApp1.Person>.GetShape()
=> global::PolyType.SourceGenerator.GenerateShapeProvider.Default.Person;
}
}

Usefull

Download Example (.NET C# )

Share polytype

https://ignatandrei.github.io/RSCG_Examples/v2/docs/polytype

In the same category (FunctionalProgramming) - 14 other generators

cachesourcegenerator

dunet

Dusharp

Funcky.DiscriminatedUnion

FunicularSwitch

N.SourceGenerators.UnionTypes

OneOf

PartiallyApplied

rscg_queryables

RSCG_Utils_Memo

Sera.Union

TypeUtilities

UnionGen

UnionsGenerator