-
Notifications
You must be signed in to change notification settings - Fork 5.4k
Description
Background and motivation
With more and more methods having the signature of bool TryFoo(..., out int charsWritten), you run into situations where you're copying things from a span, but then have to manually deal with the out parameter.
Having overloads that out the number of elements written can help avoid the boilerplate.
API Proposal
namespace System;
public sealed class String
{
public bool TryCopyTo(Span<char> destination);
+ public bool TryCopyTo(Span<char> destination, out int charsWritten);
}
public readonly struct ReadOnlySpan<T>
{
public bool TryCopyTo(Span<T> destination);
+ public bool TryCopyTo(Span<T> destination, out int elementsWritten);
}
public readonly struct Span<T>
{
public bool TryCopyTo(Span<T> destination);
+ public bool TryCopyTo(Span<T> destination, out int elementsWritten);
}API Usage
-if (result.TryCopyTo(destination))
-{
- charsWritten = result.Length;
- return true;
-}
-
-charsWritten = 0;
-return false;
+return result.TryCopyTo(destination, out charsWritten);A couple examples from this repo:
runtime/src/libraries/System.Private.Uri/src/System/UriExt.cs
Lines 631 to 638 in b35e96b
| if (charsToUnescape.TryCopyTo(destination)) | |
| { | |
| charsWritten = charsToUnescape.Length; | |
| return true; | |
| } | |
| charsWritten = 0; | |
| return false; |
runtime/src/libraries/System.Private.Uri/src/System/Uri.cs
Lines 1630 to 1637 in b35e96b
| if (result.TryCopyTo(destination)) | |
| { | |
| charsWritten = result.Length; | |
| return true; | |
| } | |
| charsWritten = 0; | |
| return false; |
| internal static bool TryCopyToDestination(this ReadOnlySpan<byte> source, Span<byte> destination, out int bytesWritten) | |
| { | |
| if (source.TryCopyTo(destination)) | |
| { | |
| bytesWritten = source.Length; | |
| return true; | |
| } | |
| bytesWritten = 0; | |
| return false; | |
| } |
runtime/src/libraries/System.Private.CoreLib/src/System/Globalization/Normalization.cs
Lines 51 to 58 in b35e96b
| if (source.TryCopyTo(destination)) | |
| { | |
| charsWritten = source.Length; | |
| return true; | |
| } | |
| charsWritten = 0; | |
| return false; |
runtime/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/ValueListBuilder.cs
Lines 149 to 159 in b35e96b
| public bool TryCopyTo(Span<T> destination, out int itemsWritten) | |
| { | |
| if (_span.Slice(0, _pos).TryCopyTo(destination)) | |
| { | |
| itemsWritten = _pos; | |
| return true; | |
| } | |
| itemsWritten = 0; | |
| return false; | |
| } |
Alternative Designs
- More types?
elementsWrittenvsitemsWritten?
Risks
No response