diff --git a/src/bufferedinputstream.jl b/src/bufferedinputstream.jl index cf2be6b..bfcdba4 100644 --- a/src/bufferedinputstream.jl +++ b/src/bufferedinputstream.jl @@ -228,32 +228,16 @@ end function readbytes!(stream::BufferedInputStream, buffer::AbstractArray{UInt8}, - from::Int, - to::Int) - checkopen(stream) - oldbuflen = buflen = length(buffer) - nb = to - from + 1 - while !eof(stream) && from <= to - if stream.position > stream.available && fillbuffer!(stream) < 1 - break - end - - num_chunk_bytes = min(to - from + 1, stream.available - stream.position + 1) - if from + num_chunk_bytes > buflen - buflen = max(buflen + num_chunk_bytes, 2*buflen) - resize!(buffer, buflen) - end - - copy!(buffer, from, stream.buffer, stream.position, num_chunk_bytes) - stream.position += num_chunk_bytes - from += num_chunk_bytes - end - - if buflen > oldbuflen - resize!(buffer, nb - (to - from + 1)) + from::Int, to::Int) + p = from + while !eof(stream) && p ≤ to + @assert ensurebuffered!(stream, 1) + n = min(to - p + 1, stream.available - stream.position + 1) + copy!(buffer, p, stream.buffer, stream.position, n) + p += n + stream.position += n end - - return nb - (to - from + 1) + return p - from end function Base.ismarked(stream::BufferedInputStream) diff --git a/test/runtests.jl b/test/runtests.jl index c0edf5d..40becbc 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -321,6 +321,14 @@ end @assert read(stream, UInt8) == UInt8('b') BufferedStreams.fillbuffer!(stream) @test stream.buffer[2] == UInt8('b') + + stream = BufferedInputStream(IOBuffer("abcdefg"), 6) + stream.immobilized = true + data = Vector{UInt8}(7) + BufferedStreams.readbytes!(stream, data, 1, 3) + @test data[1:3] == b"abc" + BufferedStreams.readbytes!(stream, data, 4, 7) + @test data[4:7] == b"defg" end @testset "misc." begin