Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix IO::Delimited reading into limited slice with peek #14772

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions spec/std/io/delimited_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,22 @@ describe "IO::Delimited" do
io.gets_to_end.should eq("hello")
end

it "handles the case of peek matching first byte, not having enough room, but later not matching (limted slice)" do
# not a delimiter
# ---
io = MemoryIOWithFixedPeek.new("abcdefgwijkfghhello")
# ------- ---
# peek delimiter
io.peek_size = 7
delimited = IO::Delimited.new(io, read_delimiter: "fgh")

delimited.peek.should eq("abcde".to_slice)
delimited.read_string(6).should eq "abcdef"
delimited.read_string(5).should eq("gwijk")
delimited.gets_to_end.should eq("")
io.gets_to_end.should eq("hello")
end

it "handles the case of peek matching first byte, not having enough room, later only partially matching" do
# delimiter
# ------------
Expand Down
4 changes: 3 additions & 1 deletion src/io/delimited.cr
Original file line number Diff line number Diff line change
Expand Up @@ -111,11 +111,13 @@ class IO::Delimited < IO
next_index = @active_delimiter_buffer.index(first_byte, 1)

# We read up to that new match, if any, or the entire buffer
read_bytes = next_index || @active_delimiter_buffer.size
read_bytes = Math.min(next_index || @active_delimiter_buffer.size, slice.size)

slice.copy_from(@active_delimiter_buffer[0, read_bytes])
slice += read_bytes
@active_delimiter_buffer += read_bytes

return read_bytes if slice.empty?
return read_bytes + read_internal(slice)
end
end
Expand Down
Loading