Skip to content

Commit 30202dc

Browse files
committed
avoid allocation in hex decode
1 parent 5bbca56 commit 30202dc

File tree

1 file changed

+8
-4
lines changed
  • src/Science.Cryptography.Ciphers.Specialized/Encodings

1 file changed

+8
-4
lines changed

src/Science.Cryptography.Ciphers.Specialized/Encodings/HexEncoder.cs

+8-4
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,10 @@ public void Decrypt(ReadOnlySpan<char> ciphertext, Span<char> plaintext, out int
5151
if (start < end && (end - start) % 2 == 0)
5252
{
5353
var span = ciphertext[start..end];
54-
var bytes = Convert.FromHexString(span);
55-
writtenPosition += Encoding.GetChars(bytes, plaintext);
54+
var bytesLength = span.Length / 2;
55+
Span<byte> bytesBuffer = bytesLength < 1024 ? stackalloc byte[bytesLength] : new byte[bytesLength];
56+
Convert.FromHexString(span, bytesBuffer, out _, out _);
57+
writtenPosition += Encoding.GetChars(bytesBuffer, plaintext);
5658
}
5759

5860
plaintext[writtenPosition++] = ch;
@@ -63,8 +65,10 @@ public void Decrypt(ReadOnlySpan<char> ciphertext, Span<char> plaintext, out int
6365
if (start < end && (end - start) % 2 == 0)
6466
{
6567
var span = ciphertext[start..end];
66-
var bytes = Convert.FromHexString(span);
67-
writtenPosition += Encoding.GetChars(bytes, plaintext);
68+
var bytesLength = span.Length / 2;
69+
Span<byte> bytesBuffer = bytesLength < 1024 ? stackalloc byte[bytesLength] : new byte[bytesLength];
70+
Convert.FromHexString(span, bytesBuffer, out _, out _);
71+
writtenPosition += Encoding.GetChars(bytesBuffer, plaintext);
6872
}
6973

7074
written = writtenPosition;

0 commit comments

Comments
 (0)