Skip to content

API Proposal: SequenceReader<T>.TryRead overloads to read a specified number of elements #30778

Closed

Description

@davidfowl

The use case is to return a contiguous ReadOnlySpan<byte> or a ReadOnlySequence<byte> the current position.

public partial ref struct SequenceReader<T>
{
    bool TryRead(int count, out ReadOnlySpan<T> value);
    bool TryRead(int count, out ReadOnlySequence<T> value);
}

One use case for this type of method is length prefixed network protocols e.g.

void Parse(ref ReadOnlySequence<byte> buffer)
{
    var reader = new SequenceReader<byte>(buffer);
    // Read the length prefix, then read the payload
    if (!reader.TryReadBigEndian(out int length) || !reader.TryRead(length, out ReadOnlySequence<byte> payload))
    {
        return;
    }
    
    ProcessPayload(payload);
}

Activity

  1. JeremyKuhne commented on Sep 6, 2019

    @JeremyKuhne
    Member

    We should consider adding skip/start to align with dotnet/corefx#40871. It isn't as necessary in this case as we're moving the reader forward (unlike peeking, where there is no way to skip without rewinding), but it would improve perf a little.

  2. softworkz commented on Sep 6, 2019

    @softworkz

    The problem I'm seeing with this approach over my other suggestion here (https://github.com/dotnet/corefx/issues/40885) is the code flow.

    1. You might not always want to actually consume and advance
    2. You might want to read from another position
    3. You don't want to check the return value each time:
      When parsing certain protocols, you'd rather want to check the remaining content for parsing one time, and then read out a number of values subsequently. Checking the return value each time makes the parsing code ugly.
      I think it should rather throw an Exception instead when there's not enough data in the sequence.

    Also this does not allow elegant parsing code like in the "Example 2" here: https://github.com/dotnet/corefx/issues/40885

  3. JeremyKuhne commented on Sep 6, 2019

    @JeremyKuhne
    Member

    You might not always want to actually consume and advance

    The TryPeek APIs dotnet/corefx#40871 should address that part of it.

    You might want to read from another position

    I don't think we should be turning the reader into a random access reader. The APIs are specifically designed around performance, skipping around to random SequencePositions is expensive and will increase the cognitive overhead on how to use the reader efficiently.

    I think it should rather throw an Exception instead when there's not enough data in the sequence.

    Only our positioning APIs throw, and they never should if your code is written correctly. I don't think we'll want to change the design so that some read methods throw and some don't. It also makes writing high performance consuming code more difficult as try..catch makes JIT optimizations much more difficult.

    Also this does not allow elegant parsing code like in the "Example 2" here: dotnet/corefx#40885

    While you can't write an inline call with the out, it allows the no-throw design for high performance. The current design is pretty consistent, I don't think we want to mix another usage pattern in.

  4. softworkz commented on Sep 6, 2019

    @softworkz

    I have written high performance parsing code and the bottom line was that I was faster by copying to a byte array and parsing from there than by using the insufficient crippled API of the SequenceReader in its current form.

    The TryPeek APIs dotnet/corefx#40871 should address that part of it.

    You're exactly hitting the problem here: "part of it"

    Now tell me, which code should a consumer of this API write, when he doesn't need to peek for a byte, but for an unsigned 32bit integer?

  5. JeremyKuhne commented on Sep 6, 2019

    @JeremyKuhne
    Member

    You're exactly hitting the problem here: "part of it"

    No API is going to address every use case. I'm not sure what you're suggesting here.

    Now tell me, which code should a consumer of this API write, when he doesn't need to peek for a byte, but for an unsigned 32bit integer?

    We have binary reader extensions. We didn't put peek versions of those as there was no request. Please feel free to create a proposal if you think it's useful. You can build the same sort of helpers in the meantime.

  6. softworkz commented on Sep 6, 2019

    @softworkz

    What proposing here is the functionality that any of those helper methods would need to implement. So why should we propose a hundred helper method when a single method would be sufficient?

    Those 6 extension methods that you are referencing is just a minimal subset of methods available from BinaryPrimitives for example.

    Also, .NET Core recently added hundreds of various TryParse(..) overloads working on spans (mostly ReadOnlySpan<char). The single method that I'm proposing here allows using all of them.

    Are you seriously suggesting that I should create proposals for duplicating all those TryParse and binary extension methods?

    No API is going to address every use case. I'm not sure what you're suggesting here.

    It's not about a specific single use case. It's about the ability to make this usable in a hundred of cases.

    That single method that I'm proposing would allow that.

  7. JeremyKuhne commented on Sep 6, 2019

    @JeremyKuhne
    Member

    Are you seriously suggesting that I should create proposals for duplicating all those TryParse and binary extension methods?

    No. I'm suggesting you create TryPeek equivalent set of the things you want, if you want them. If you don't, that's ok.

    It's about the ability to make this usable in a hundred of cases. That single method that I'm proposing would allow that.

    I don't see how understand how your proposal provides more functionality then this proposal or the "peek" option that doesn't advance the reader. Yes, you can do it inline, but I've already gone into the reasons why we are unlikely to do that. If you have examples to demonstrate where your proposal provides functionality this does not please share them.

  8. JeremyKuhne commented on Sep 6, 2019

    @JeremyKuhne
    Member

    For the proposal example, here is what you currently would have to write:

    void Parse(ref ReadOnlySequence<byte> buffer)
    {
        var reader = new SequenceReader<byte>(buffer);
    
        // Read the length prefix, validate we have enough content left
        if (!reader.TryReadBigEndian(out int length) || reader.Remaining < length)
        {
            return;
        }
    
        ProcessPayload(reader.Sequence.Slice(reader.Position, length));
    }

    With this proposal it becomes:

    void Parse(ref ReadOnlySequence<byte> buffer)
    {
        var reader = new SequenceReader<byte>(buffer);
        // Read the length prefix, then read the payload
        if (!reader.TryReadBigEndian(out int length) || !reader.TryRead(length, out ReadOnlySequence<byte> payload))
        {
            return;
        }
        
        ProcessPayload(payload);
    }

    It's more awkward for a span in the current code as you'd have to use TryCopyTo and manage your own span buffer. Presumption is the span API here would allocate an array like the other APIs do when it has to.

  9. softworkz commented on Sep 6, 2019

    @softworkz

    With my proposal (https://github.com/dotnet/corefx/issues/40885) it's a one-liner:

    var myValue = BinaryPrimitives.ReadUInt32BigEndian(reader.GetSpan(offset, 4));
    
    

    PS: I need UInt32, not Int32 - what would I do currently (except casting)?

  10. davidfowl commented on Sep 6, 2019

    @davidfowl
    MemberAuthor

    With your proposal what gets returned when length exceeds the bounds?

  11. JeremyKuhne commented on Sep 6, 2019

    @JeremyKuhne
    Member

    PS: I need UInt32, not Int32 - what would I do currently (except casting)?

    Just cast, there is another discussion bout adding the unsigned overloads. There is no cost to casting, which is why we didn't add them originally- just trying to be deliberate in adding API so we didn't end up with a really huge surface area. #30580

  12. softworkz commented on Sep 6, 2019

    @softworkz

    With your proposal what gets returned when length exceeds the bounds?

    An IndexOutOfRangeException (or similar). I have written parsing code that is processing large volumes of data and there's just a single try catch at the very top of the call stack.
    Jeremy pointed out that high performance code should not use Exception handling and I agree in a way that it should not be used for controlling code flow.
    The caller can check if there's enough data for calling, so IMO it's legit to throw as that would be the caller's fault.

  13. JeremyKuhne commented on Sep 6, 2019

    @JeremyKuhne
    Member

    The caller can check if there's enough data for calling, so IMO it's legit to throw as that would be the caller's fault.

    There is also some cost to adding the throw in the reader as well. I spent over two months getting the fast path as fast as possible- adding a single line or method call can measure in some of the cases.

    Perf not withstanding, we didn't go that route with the design here so it would not align with the rest of the API.

  14. softworkz commented on Sep 6, 2019

    @softworkz

    The caller can check if there's enough data for calling, so IMO it's legit to throw as that would be the caller's fault.

    There is also some cost to adding the throw in the reader as well. I spent over two months getting the fast path as fast as possible- adding a single line or method call can measure in some of the cases.

    The check for the condition ("buffer long enough") is required in either case.
    How would some conditionally called code affect performance by its sole existence as long as it's never called?
    Or is the compiler adding some MSIL stuff due to the fact that the method could throw?

  15. 20 remaining items

  16. terrajobst commented on Feb 20, 2020

    @terrajobst
    Contributor

    Video

    • The first API will have to allocate when count causes spanning blocks in the sequence. The bigger the count, the more likely it is to cross such a boundary. This could be changed to allow the caller to pass in a pre-allocated span or we could change the semantics to only succeed if the data is available contiguously. This API will need more design.
    • The second overload is fine but we should change the name to TryReadExact to make it clear that returning less or more is both not possible.
    public partial ref struct SequenceReader<T>
    {
        bool TryReadExact(int count, out ReadOnlySequence<T> value);
    }
  17. reflectronic commented on Feb 21, 2020

    @reflectronic
    Contributor

    We talked about this API (and some others) more in #30807 (comment). Specifically, we discussed putting the out parameter first (as it is on every other SequenceReader API), and also renaming value to sequence. For the sake of having a congruent API surface, that should probably be done for this API.

    On the topic of the Span overload, I think that keeping the overload is also important for having a congruent API surface. There are existing APIs like TryReadTo and TryReadToAny that take both Span and Sequence overloads; it would be strange/annoying to have a new API, which is similar in purpose to the existing ones, but with no Span overload "because reasons."

    Of course, having some type of alternative which doesn't necessarily allocate is useful, especially since the buffer size can be much more predictable. But I think that the matching APIs should be added for this method, and likewise anything new we come up with should be added to TryReadTo/TryReadToAny/TryPeek/etc.

  18. modified the milestones: 5.0.0, 6.0.0 on Aug 26, 2020
  19. modified the milestones: 6.0.0, Future on Aug 9, 2021
  20. added
    help wanted
    on Aug 9, 2021
  21. tannergooding commented on Aug 9, 2021

    @tannergooding
    Member

    Moved this to future and marked as up-for-grabs. @davidfowl if this is needed for 6.0.0, please let us know.

  22. davidfowl commented on Aug 9, 2021

    @davidfowl
    MemberAuthor

    This is fine for .NET 7

  23. ghost added
    in-pr
    on Aug 23, 2021
  24. lateapexearlyspeed commented on Aug 23, 2021

    @lateapexearlyspeed
    Contributor

    Hi, I would try and learn this. I have raised draft PR and will change its status when it is ready for review, thanks !

  25. lateapexearlyspeed commented on Aug 23, 2021

    @lateapexearlyspeed
    Contributor

    PR is ready for review now, please review, thanks.

  26. ghost removed
    in-pr
    on Oct 13, 2021
  27. ghost locked as resolved and limited conversation to collaborators on Nov 12, 2021
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-approvedarea-System.Buffershelp wanted

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions