-
-
Save SimonCropp/8b8c11c06af43de5769409437224aba6 to your computer and use it in GitHub Desktop.
StringBuilder AsSpan
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#if NET8_0_OR_GREATER | |
[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "m_ChunkPrevious")] | |
private static extern ref StringBuilder? ChunkPrevious(StringBuilder builder); | |
static bool HasSingleChunk(this StringBuilder builder) => | |
ChunkPrevious(builder) == null; | |
#endif | |
public static CharSpan AsSpan(this StringBuilder builder) | |
{ | |
#if NET8_0_OR_GREATER | |
if (builder.HasSingleChunk()) | |
{ | |
foreach (var chunk in builder.GetChunks()) | |
{ | |
return chunk.Span; | |
} | |
} | |
#endif | |
return builder | |
.ToString() | |
.AsSpan(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment