-
Notifications
You must be signed in to change notification settings - Fork 4.8k
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
API Proposal: String.{Try}CopyTo(Span<char>) #51061
Comments
I think this category of API is generally useful. When I was experimenting with Utf8String I had an internal runtime/src/libraries/System.Private.CoreLib/src/System/Utf8String.cs Lines 72 to 80 in 066a24c
The general idea is that it was for scenarios where I really didn't expect the string instance to be null, and I was willing to take the NRE in order to avoid complicated branching in my hot paths. |
namespace System
{
public sealed class String
{
...
public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count);
+ public void CopyTo(Span<char> destination);
+ public bool TryCopyTo(Span<char> destination);
}
} |
Background and Motivation
When working with text (strings and spans), it's relatively common to need to copy a string to a span, which can be done with:
We can make this simpler and faster by adding such a CopyTo directly to string:
Same with TryCopyTo. For example, Number.Formatting.cs in corelib has this:
runtime/src/libraries/System.Private.CoreLib/src/System/Number.Formatting.cs
Lines 757 to 769 in f0f3b84
by changing the
source.AsSpan().TryCopyTo(destination)
there tosource.TryCopyTo(destination)
(with an implementation of TryCopyTo on string that's the same 7-line implementation on span), we get this diff:Proposed API
Risks
string.AsSpan().{Try}CopyTo
works with null input strings, becauseAsSpan()
special-cases null to return an empty span. As a result, someone switching from the former to these new APIs could incur a null reference exception if they used a null string.The text was updated successfully, but these errors were encountered: