How to know if I'm on the last segment of a sequence? #111551
-
This is how I'm doing it: var list = new byte[][]
{
new byte[] { 0, 1, 2, },
new byte[] { 3, 4, 5, },
new byte[] { 6, 7, 8, },
};
var seq = CreateReadOnlySequence(list);
var length = seq.Length;
foreach (var seg in seq)
{
length -= seg.Length;
if (length == 0)
{
Console.Write(" *");
}
foreach (var b in seg.Span)
{
Console.Write($" {b:X2}");
}
}
Console.WriteLine();
ReadOnlySequence<byte> CreateReadOnlySequence(IList<byte[]> byteArrayList)
{
if (byteArrayList is not { Count: > 0 })
{
return ReadOnlySequence<byte>.Empty;
}
if (byteArrayList.Count == 1)
{
return new ReadOnlySequence<byte>(byteArrayList[0]);
}
var firstSegment = new SequenceSegment(new ReadOnlyMemory<byte>(byteArrayList[0]));
var lastSegment = firstSegment;
for (var i = 1; i < byteArrayList.Count; i++)
{
var nextSegment = new SequenceSegment(new ReadOnlyMemory<byte>(byteArrayList[i]));
lastSegment.Append(nextSegment);
lastSegment = nextSegment;
}
return new ReadOnlySequence<byte>(firstSegment, 0, lastSegment, lastSegment.Memory.Length);
}
internal class SequenceSegment : ReadOnlySequenceSegment<byte>
{
public SequenceSegment(ReadOnlyMemory<byte> memory)
{
Memory = memory;
RunningIndex = 0;
}
public void Append(SequenceSegment next)
{
Next = next;
next.RunningIndex = RunningIndex + Memory.Length;
}
} Is there a better option? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Unrelated nit: allocating an array and enumerating it is very inefficient, try this instead: - foreach (var b in seg.ToArray())
+ foreach (var b in seg.Span) |
Beta Was this translation helpful? Give feedback.
-
It appears to me that you are using If the underlying structure of the sequence is important to your algorithm, and you need to answer questions like whether you are on the last segment of a sequence, you should be using a different API like |
Beta Was this translation helpful? Give feedback.
It appears to me that you are using
ReadOnlySequence<T>
wrong.ReadOnlySequence<T>
does not represent a sequence of sequences, but a single sequence that is backed by one or maybe more contiguous buffers. A sequence backed by a single array[1, 2, 3, 4, 5, 6, 7, 8, 9]
, and a sequence backed by three arrays[1, 2, 3]
,[4, 5, 6]
and[7, 8, 9]
represent the same thing.If the underlying structure of the sequence is important to your algorithm, and you need to answer questions like whether you are on the last segment of a sequence, you should be using a different API like
IReadOnlyCollection<ReadOnlyMemory<T>>
.