Skip to content

Commit

Permalink
Showing 3 changed files with 46 additions and 4 deletions.
9 changes: 9 additions & 0 deletions spec/std/io/sized_spec.cr
Original file line number Diff line number Diff line change
@@ -81,4 +81,13 @@ describe "IO::Sized" do
io.closed?.should eq(true)
end
end

it "read_byte" do
io = MemoryIO.new "abcdefg"
sized = IO::Sized.new(io, read_size: 3)
sized.read_byte.should eq('a'.ord)
sized.read_byte.should eq('b'.ord)
sized.read_byte.should eq('c'.ord)
sized.read_byte.should be_nil
end
end
29 changes: 25 additions & 4 deletions src/http/content.cr
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
module HTTP
# :nodoc:
module Content
include IO

def close
buffer = uninitialized UInt8[1024]
while read(buffer.to_slice) > 0
@@ -22,6 +20,7 @@ module HTTP

# :nodoc:
class UnknownLengthContent
include IO
include Content

def initialize(@io : IO)
@@ -31,13 +30,18 @@ module HTTP
@io.read(slice)
end

def read_byte
@io.read_byte
end

def write(slice : Slice(UInt8))
raise IO::Error.new "Can't write to UnknownLengthContent"
end
end

# :nodoc:
class ChunkedContent
include IO
include Content
@chunk_remaining : Int32

@@ -67,15 +71,32 @@ module HTTP
bytes_read = @io.read slice[0, to_read]
@chunk_remaining -= bytes_read

check_chunk_remaining_is_zero

bytes_read
end

def read_byte
if @chunk_remaining > 0
byte = @io.read_byte
if byte
@chunk_remaining -= 1
check_chunk_remaining_is_zero
end
byte
else
super
end
end

private def check_chunk_remaining_is_zero
# As soon as we finish reading a chunk we return,
# in case the next content is delayed (see #3270).
# We set @read_chunk_start to true so we read the next
# chunk start on the next call to `read`.
if @chunk_remaining == 0
@read_chunk_start = true
end

bytes_read
end

private def read_chunk_end
12 changes: 12 additions & 0 deletions src/io/sized.cr
Original file line number Diff line number Diff line change
@@ -37,6 +37,18 @@ module IO
bytes_read
end

def read_byte
check_open

if @read_remaining > 0
byte = @io.read_byte
@read_remaining -= 1 if byte
byte
else
nil
end
end

def write(slice : Slice(UInt8))
raise IO::Error.new "Can't write to IO::Sized"
end

0 comments on commit 6c5fb5a

Please sign in to comment.