Skip to content

Instantly share code, notes, and snippets.

@SimonCropp
Last active December 22, 2023 01:58
Show Gist options
  • Save SimonCropp/8b8c11c06af43de5769409437224aba6 to your computer and use it in GitHub Desktop.
Save SimonCropp/8b8c11c06af43de5769409437224aba6 to your computer and use it in GitHub Desktop.
StringBuilder AsSpan
#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