Skip to content

Commit 44a7e8a

Browse files
committed
Removed branching
1 parent 584f510 commit 44a7e8a

File tree

1 file changed

+12
-21
lines changed

1 file changed

+12
-21
lines changed

src/DotNext/Buffers/Memory.ReadOnlySequence.cs

Lines changed: 12 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
using System.Buffers;
2-
using System.Runtime.CompilerServices;
32
using System.Runtime.InteropServices;
43
using System.Text;
54

@@ -207,29 +206,21 @@ public static ReadOnlySequence<T> Concat<T>(this ReadOnlyMemory<T> first, ReadOn
207206
/// <typeparam name="T">The type of the elements in the sequence.</typeparam>
208207
public static void CopyTo<T>(this in ReadOnlySequence<T> source, Span<T> destination, out int writtenCount)
209208
{
210-
if (source.IsSingleSegment)
211-
{
212-
// fast path - single-segment sequence
213-
source.FirstSpan.CopyTo(destination, out writtenCount);
214-
}
215-
else
216-
{
217-
// slow path - multisegment sequence
218-
writtenCount = CopyToSlow(in source, destination);
219-
}
209+
writtenCount = 0;
210+
ReadOnlyMemory<T> block;
220211

221-
static int CopyToSlow(in ReadOnlySequence<T> source, Span<T> destination)
212+
for (var position = source.Start;
213+
source.TryGet(ref position, out block) && block.Length <= destination.Length;
214+
writtenCount += block.Length)
222215
{
223-
int result = 0, subcount;
224-
225-
for (var position = source.Start; !destination.IsEmpty && source.TryGet(ref position, out var block); result += subcount)
226-
{
227-
block.Span.CopyTo(destination, out subcount);
228-
destination = destination.Slice(subcount);
229-
}
230-
231-
return result;
216+
block.Span.CopyTo(destination);
217+
destination = destination.Slice(block.Length);
232218
}
219+
220+
// copy the last segment
221+
block = block.TrimLength(destination.Length);
222+
block.Span.CopyTo(destination);
223+
writtenCount += block.Length;
233224
}
234225

235226
/// <summary>

0 commit comments

Comments
 (0)