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:
string.AsSpan().CopyTo(destination)
We can make this simpler and faster by adding such a CopyTo directly to string:
string.CopyTo(destination)
Same with TryCopyTo. For example, Number.Formatting.cs in corelib has this:
|
private static bool TryCopyTo(string source, Span<char> destination, out int charsWritten) |
|
{ |
|
Debug.Assert(source != null); |
|
|
|
if (source.AsSpan().TryCopyTo(destination)) |
|
{ |
|
charsWritten = source.Length; |
|
return true; |
|
} |
|
|
|
charsWritten = 0; |
|
return false; |
|
} |
by changing the
source.AsSpan().TryCopyTo(destination) there to
source.TryCopyTo(destination) (with an implementation of TryCopyTo on string that's the same 7-line implementation on span), we get this diff:
Proposed API
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);
}
}
Risks
string.AsSpan().{Try}CopyTo works with null input strings, because AsSpan() 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.
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
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); } }Risks
string.AsSpan().{Try}CopyToworks 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.