Created
May 16, 2020 17:13
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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