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

Add type-bound MemoryPackCustomFormatter #347

Open
aradalvand opened this issue Nov 2, 2024 · 3 comments
Open

Add type-bound MemoryPackCustomFormatter #347

aradalvand opened this issue Nov 2, 2024 · 3 comments

Comments

@aradalvand
Copy link

aradalvand commented Nov 2, 2024

Currently, if you have a custom formatter for a particular type (e.g. NodaTime's Instant, for example), you have to specify the formatter on every single property of that type — this is tedious and error-prone:

public record SomeDto(
    // ...
    [property: InstantFormatter]
    Instant CreatedAt,
    [property: InstantFormatter]
    Instant UpdatedAt,
    [property: InstantFormatter]
    Instant ExpiresAt
    // ...
);

public class InstantFormatter : MemoryPackCustomFormatterAttribute<Instant>
{
    public override IMemoryPackFormatter<Instant> GetFormatter() => new Formatter();

    private class Formatter : MemoryPackFormatter<Instant>
    {
        public override void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, scoped ref Instant value)
        {
            writer.WriteValue(value.ToUnixTimeTicks());
        }

        public override void Deserialize(ref MemoryPackReader reader, scoped ref Instant value)
        {
            value = Instant.FromUnixTimeTicks(reader.ReadValue<long>());
        }
    }
}

Introduce a way to globally associate a type with a specific formatter — e.g. using an assembly attribute:

[assembly: MemoryPackCustomFormatter<Instant, InstantFormatter>]

Additionally, add a way to annotate a type directly with a custom formatter (a la [JsonConverterAttribute]).

[MemoryPackCustomFormatter<FooFormatter>]
public readonly struct Foo { ... }

So as to eliminate the need for individual annotations on every single property of that type. This is highly useful in cases where there's a 1:1 correspondence between a formatter and a type (which is extremely common).

@aradalvand
Copy link
Author

@neuecc Hello, would you accept a PR for this?

@aradalvand
Copy link
Author

This (specifically the last snippet in my original comment) would help tools like Vogen to add MemoryPack support.

@aradalvand
Copy link
Author

aradalvand commented Nov 16, 2024

@neuecc Any thoughts? MemoryPack effectively lacks proper extensibility points without this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant