Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Do not clone empty arrays in CloneByteArray #93231

Merged
merged 2 commits into from
Oct 9, 2023

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
107 of 109 checks passed
@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