Read a single element vs array from stream

Since the single case is used often, I use read1T as a convenience function.

Novice question: can the two functions be combined without violating type stability?

Or, more generally, does Union{T, AbstractArray{T}} as input or output type already get a performance hit?

function readnT(io, n, T, Tr)
    s = sizeof(T)
    f = UInt8[s]
    readbytes!(io, f, n*s)
    return Tr.(reinterpret(T, f))
end

function read1T(io, T, Tr)
    s = sizeof(T)
    f = UInt8[s]
    readbytes!(io, f, s)
    return Tr.(reinterpret(T, f))[1]
end

Have you tried read(io, T) and read!(io, array) from the standard library?
The first reads one value of T, the second reads until array is full.

3 Likes

interesting way to read the correct amount of data, thx!

Continued here.