KEMBAR78
Do not clone empty arrays in CloneByteArray by vcsjones · Pull Request #93231 · dotnet/runtime · GitHub
Skip to content

Conversation

@vcsjones
Copy link
Member

@vcsjones vcsjones commented Oct 9, 2023

CloneByteArray is used heavily in S.S.Cryptography to create defensive copies of byte arrays. This is to avoid exposing any kind of mutability to callers.

Clone however appears to create a new byte[] for empty byte arrays every time. Empty arrays are not uncommon. It could be for a CNG property, it could be for key parameters, or other AsnEncodedData.

If its empty, just return the identity to save the allocation.

@ghost
Copy link

ghost commented Oct 9, 2023

Tagging subscribers to this area: @dotnet/area-system-security, @bartonjs, @vcsjones
See info in area-owners.md if you want to be subscribed.

Issue Details

CloneByteArray is used heavily in S.S.Cryptography to create defensive copies of byte arrays. This is to avoid exposing any kind of mutability to callers.

Clone however appears to create a new byte[] for empty byte arrays every time. Empty arrays are not uncommon. It could be for a CNG property, it could be for key parameters, or other AsnEncodedData.

If its empty, just return the identity to save the allocation.

Author: vcsjones
Assignees: vcsjones
Labels:

area-System.Security

Milestone: -

@vcsjones
Copy link
Member Author

vcsjones commented Oct 9, 2023

Failure is tracked in #93229. Merging.

@vcsjones vcsjones merged commit 63a375e into dotnet:main Oct 9, 2023
@vcsjones vcsjones deleted the no-alloc-clone-empty branch October 9, 2023 19:59
@vcsjones vcsjones added this to the 9.0.0 milestone Oct 9, 2023
Comment on lines +48 to +53
return src switch
{
return null;
}

return (byte[])(src.Clone());
null => null,
{ Length: 0 } => src,
_ => (byte[])src.Clone(),
};
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FWIW, it could also have been:

return src is not null ? src.AsSpan().ToArray() : null;

and let span's ToArray handle the empty case via Array.Empty.

@ghost ghost locked as resolved and limited conversation to collaborators Nov 9, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants