Skip to content

Commit

Permalink
fix readbytes! (#35)
Browse files Browse the repository at this point in the history
  • Loading branch information
bicycle1885 authored Mar 10, 2017
1 parent f4e2f9f commit cf9b40b
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 25 deletions.
34 changes: 9 additions & 25 deletions src/bufferedinputstream.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
8 changes: 8 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit cf9b40b

Please sign in to comment.