Skip to content

Conversation

@BlobCodes
Copy link
Contributor

@BlobCodes BlobCodes commented Dec 26, 2025

Closes #14605

Adds the proposed #read_greedy method which tries to fill a Slice multiple times if it was only filled partially by the read method.

Since some users seem to expect this kind of behaviour from #read (leading to hard-to-debug bugs), this could be seen as a "safer" version of #read for some use-cases.

I didn't try to add a lazy reading function as there would be too many interpretations of what reading lazily even means depending on the use-case.

There's also a small optimization for IO::Memory (not benchmarked).

Copy link
Member

@straight-shoota straight-shoota left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should add some specs for this new method.

@crysbot
Copy link
Collaborator

crysbot commented Jan 15, 2026

This pull request has been mentioned on Crystal Forum. There might be relevant details there:

https://forum.crystal-lang.org/t/empty-content-when-reading-big-packets-on-tcp-ip/8652/4

@straight-shoota straight-shoota changed the title feat: add #read_greedy method Add IO#read_greedy Jan 20, 2026
@straight-shoota
Copy link
Member

suggestion: We could refactor the implementation of #read_fully? to use #read_greedy:

  def read_fully?(slice : Bytes) : Int32?
    count = read_greedy(slice)
    return nil unless count == slice.size
    count
  end

This could also be a follow-up.

@BlobCodes
Copy link
Contributor Author

I applied all suggestions and added the cross-reference to the docs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add methods for filling a buffer from an IO greedily/lazily

5 participants