Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix read! for types with size not a power of 2 #41711

Closed
wants to merge 2 commits into from
Closed
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
3 changes: 2 additions & 1 deletion base/io.jl
Original file line number Diff line number Diff line change
Expand Up @@ -738,7 +738,8 @@ function read!(s::IO, a::Array{UInt8})
end

function read!(s::IO, a::AbstractArray{T}) where T
if isbitstype(T) && (a isa Array || a isa FastContiguousSubArray{T,<:Any,<:Array{T}})
if isbitstype(T) && sizeof(T) == aligned_sizeof(T) &&
(a isa Array || a isa FastContiguousSubArray{T,<:Any,<:Array{T}})
GC.@preserve a unsafe_read(s, pointer(a), sizeof(a))
else
for i in eachindex(a)
Expand Down
12 changes: 12 additions & 0 deletions test/read.jl
Original file line number Diff line number Diff line change
Expand Up @@ -621,3 +621,15 @@ end
first(itr) # consume the iterator
@test isempty(itr) # now it is empty
end

@testset "read! with non-power-of-2 types" begin
primitive type Int24 <: Integer 24 end
Base.read(io::IO, ::Type{Int24}) = only(reinterpret(Int24, read(io, sizeof(Int24))))
bytes = [0xa4, 0x01, 0x0, 0x45, 0x0, 0x0]
io = IOBuffer()
write(io, bytes)
seekstart(io)
x = Vector{Int24}(undef, 2)
read!(io, x)
@test x == reinterpret(Int24, bytes)
end
1 change: 1 addition & 0 deletions test/subarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -588,6 +588,7 @@ end
primitive type UInt48 48 end
UInt48(x::UInt64) = Core.Intrinsics.trunc_int(UInt48, x)
UInt48(x::UInt32) = Core.Intrinsics.zext_int(UInt48, x)
Base.read(io::IO, ::Type{UInt48}) = only(reinterpret(UInt48, read(io, sizeof(UInt48))))
Copy link
Sponsor Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This must be what's causing the failure --- it reads too few bytes, failing to skip the alignment padding.


@testset "sizeof" begin
@test sizeof(view(zeros(UInt8, 10), 1:4)) == 4
Expand Down