Skip to content
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
28 changes: 11 additions & 17 deletions src/api/buffered.jl
Original file line number Diff line number Diff line change
Expand Up @@ -39,24 +39,18 @@ function Base.read(io::BufferedConn, ::Type{UInt8})
return b
end

function Base.unsafe_read(io::BufferedConn, p::Ptr{UInt8}, n::UInt)
remaining = Int(n)
while remaining > 0
if bytesavailable(io) == 0
# a remainder larger than the scratch buffer goes straight to `p`
if remaining >= length(io.scratch) && !io.ended
unsafe_read(io.transport, p, UInt(remaining))
return nothing
end
fill_buffer!(io) || throw(EOFError())
end
k = min(remaining, bytesavailable(io))
GC.@preserve io unsafe_copyto!(p, pointer(io.buffer, io.pos), k)
io.pos += k
p += k
remaining -= k
# Message headers carry an Int32 length, so this runs once per protocol
# message. Base's `read(io, T)` reads through a heap-allocated `Ref`.
Base.read(io::BufferedConn, T::Union{Type{Int16}, Type{UInt16}, Type{Int32}, Type{UInt32}}) = read_fixed(io, T)

function read_fixed(io::BufferedConn, ::Type{T}) where {T}
while bytesavailable(io) < sizeof(T)
fill_buffer!(io) || throw(EOFError())
end
return nothing
buf = io.buffer
x = GC.@preserve buf unsafe_load(Ptr{T}(pointer(buf, io.pos)))
io.pos += sizeof(T)
return x
end

function Base.readbytes!(io::BufferedConn, buf::AbstractVector{UInt8}, nb::Integer=length(buf); all::Bool=true)
Expand Down
10 changes: 10 additions & 0 deletions test/execute_fake_server.jl
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,16 @@ function test_execute_fake_server()
close(io)
end
end
@testset "a message header split across transport reads" begin
msg = pgmsg('d', UInt8[1, 2, 3])
with_fake_server((sock, n) -> foreach(b -> (send(sock, [b]); sleep(0.02)), msg)) do port, accepted
io = Postgres.API.BufferedConn(Postgres.API.connectsocket("127.0.0.1", port, Int64(0)))
@test Postgres.API.readheader(io) == (UInt8('d'), 3)
@test Postgres.API.readbody(io, 3) == UInt8[1, 2, 3]
@test_throws EOFError read(io, Int32)
close(io)
end
end
# the replies the server gets out before the connection is lost
partial_replies = (
"before ParseComplete" => UInt8[],
Expand Down
Loading