Skip to content

Commit

Permalink
fix #28481, faster reading of primitive types from IOStream and IOBuf…
Browse files Browse the repository at this point in the history
…fer (#29186)
  • Loading branch information
JeffBezanson authored Sep 17, 2018
1 parent 632ca40 commit c0afddf
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
15 changes: 15 additions & 0 deletions base/iobuffer.jl
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,21 @@ function unsafe_read(from::GenericIOBuffer, p::Ptr{UInt8}, nb::UInt)
nothing
end

function read(from::GenericIOBuffer, T::Union{Type{Int16},Type{UInt16},Type{Int32},Type{UInt32},Type{Int64},Type{UInt64},Type{Int128},Type{UInt128},Type{Float16},Type{Float32},Type{Float64}})
from.readable || throw(ArgumentError("read failed, IOBuffer is not readable"))
avail = bytesavailable(from)
nb = sizeof(T)
if nb > avail
throw(EOFError())
end
GC.@preserve from begin
ptr::Ptr{T} = pointer(from.data, from.ptr)
x = unsafe_load(ptr)
end
from.ptr += nb
return x
end

function read_sub(from::GenericIOBuffer, a::AbstractArray{T}, offs, nel) where T
@assert !has_offset_axes(a)
from.readable || throw(ArgumentError("read failed, IOBuffer is not readable"))
Expand Down
4 changes: 4 additions & 0 deletions base/iostream.jl
Original file line number Diff line number Diff line change
Expand Up @@ -401,6 +401,10 @@ if ENDIAN_BOM == 0x04030201
function read(s::IOStream, T::Union{Type{Int16},Type{UInt16},Type{Int32},Type{UInt32},Type{Int64},Type{UInt64}})
return ccall(:jl_ios_get_nbyte_int, UInt64, (Ptr{Cvoid}, Csize_t), s.ios, sizeof(T)) % T
end

read(s::IOStream, ::Type{Float16}) = reinterpret(Float16, read(s, Int16))
read(s::IOStream, ::Type{Float32}) = reinterpret(Float32, read(s, Int32))
read(s::IOStream, ::Type{Float64}) = reinterpret(Float64, read(s, Int64))
end

function unsafe_read(s::IOStream, p::Ptr{UInt8}, nb::UInt)
Expand Down

0 comments on commit c0afddf

Please sign in to comment.