Created
November 11, 2025 18:40
-
-
Save TheConstructor/28eadd0510b85717f0a8271f7b1010b1 to your computer and use it in GitHub Desktop.
Represent StringBuilder as ReadOnlySequence<char>
This file contains hidden or 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
| public class StringBuilderSegment : ReadOnlySequenceSegment<char> | |
| { | |
| public static ReadOnlySequence<char> FromStringBuilder(StringBuilder sb) | |
| { | |
| var enumerator = sb.GetChunks(); | |
| if (!enumerator.MoveNext()) | |
| { | |
| return ReadOnlySequence<char>.Empty; | |
| } | |
| var i = 0; | |
| var firstChunk = new StringBuilderSegment | |
| { | |
| RunningIndex = i, | |
| Memory = enumerator.Current, | |
| }; | |
| var lastChunk = firstChunk; | |
| while (enumerator.MoveNext()) | |
| { | |
| i += lastChunk.Memory.Length; | |
| var nextChunk = new StringBuilderSegment | |
| { | |
| RunningIndex = i, | |
| Memory = enumerator.Current, | |
| }; | |
| lastChunk.Next = nextChunk; | |
| lastChunk = nextChunk; | |
| } | |
| return new ReadOnlySequence<char>(firstChunk, 0, lastChunk, lastChunk.Memory.Length); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment