Skip to content

Instantly share code, notes, and snippets.

@drub0y
Created May 16, 2020 17:13
Show Gist options
  • Save drub0y/a65c59a0682ff8266e145804968a72e9 to your computer and use it in GitHub Desktop.
Save drub0y/a65c59a0682ff8266e145804968a72e9 to your computer and use it in GitHub Desktop.
A System.Text.Json converter implementation that efficiently encodes the BigInteger to Base64
internal sealed class BigIntegerBase64JsonConverter : JsonConverter<BigInteger>
{
public override BigInteger Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var bigIntegerBytes = reader.GetBytesFromBase64();
return new BigInteger(bigIntegerBytes);
}
public override void Write(Utf8JsonWriter writer, BigInteger value, JsonSerializerOptions options)
{
var bytes = ArrayPool<byte>.Shared.Rent(value.GetByteCount());
try
{
value.TryWriteBytes(bytes, out _);
writer.WriteBase64StringValue(bytes);
}
finally
{
ArrayPool<byte>.Shared.Return(bytes);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment