Skip to content

Commit ae44947

Browse files
authored
Avoid temporary byte[] allocation in Pkcs' HeapBlockReatiner.AllocAsciiString (#75136)
1 parent 7646e76 commit ae44947

File tree

1 file changed

+10
-8
lines changed
  • src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows

1 file changed

+10
-8
lines changed

src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/HeapBlockRetainer.cs

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -42,15 +42,17 @@ public IntPtr Alloc(int howMany, int cbElement)
4242
return Alloc(cbSize);
4343
}
4444

45-
public IntPtr AllocAsciiString(string s)
45+
public unsafe IntPtr AllocAsciiString(string s)
4646
{
47-
byte[] b = Encoding.ASCII.GetBytes(s);
48-
IntPtr pb = Alloc(b.Length + 1);
49-
Marshal.Copy(b, 0, pb, b.Length);
50-
unsafe
51-
{
52-
((byte*)pb)[b.Length] = 0; // NUL termination.
53-
}
47+
int length = Encoding.ASCII.GetByteCount(s);
48+
length++; // for null termination
49+
50+
IntPtr pb = Alloc(length);
51+
52+
var ascii = new Span<byte>((byte*)pb, length);
53+
Encoding.ASCII.GetBytes(s, ascii);
54+
ascii[^1] = 0;
55+
5456
return pb;
5557
}
5658

0 commit comments

Comments
 (0)