From 19d0745356e90229d676bc505237bbfeed05d6eb Mon Sep 17 00:00:00 2001 From: Jeff Bezanson Date: Wed, 22 Jul 2020 15:46:17 -0400 Subject: [PATCH] fix `elsize` and `write` for SubArrays of Arrays (#36739) --- base/io.jl | 2 +- base/subarray.jl | 2 ++ test/subarray.jl | 17 +++++++++++++---- 3 files changed, 16 insertions(+), 5 deletions(-) diff --git a/base/io.jl b/base/io.jl index 05dd2198d68e9..d95b474d48cc3 100644 --- a/base/io.jl +++ b/base/io.jl @@ -676,7 +676,7 @@ function write(s::IO, a::SubArray{T,N,<:Array}) where {T,N} if !isbitstype(T) || !isa(a, StridedArray) return invoke(write, Tuple{IO, AbstractArray}, s, a) end - elsz = sizeof(T) + elsz = elsize(a) colsz = size(a,1) * elsz GC.@preserve a if stride(a,1) != 1 for idxs in CartesianIndices(size(a)) diff --git a/base/subarray.jl b/base/subarray.jl index 3905a85bec08d..3ecbe972cf3c8 100644 --- a/base/subarray.jl +++ b/base/subarray.jl @@ -67,6 +67,8 @@ similar(V::SubArray, T::Type, dims::Dims) = similar(V.parent, T, dims) sizeof(V::SubArray) = length(V) * sizeof(eltype(V)) sizeof(V::SubArray{<:Any,<:Any,<:Array}) = length(V) * elsize(V.parent) +elsize(::Type{<:SubArray{<:Any,<:Any,P}}) where {P<:Array} = elsize(P) + copy(V::SubArray) = V.parent[V.indices...] parent(V::SubArray) = V.parent diff --git a/test/subarray.jl b/test/subarray.jl index cf03d1b53ca64..33efc27f9bf9a 100644 --- a/test/subarray.jl +++ b/test/subarray.jl @@ -585,16 +585,16 @@ end @test IndexStyle(B18581) === IndexLinear() end +primitive type UInt48 48 end +UInt48(x::UInt64) = Core.Intrinsics.trunc_int(UInt48, x) +UInt48(x::UInt32) = Core.Intrinsics.zext_int(UInt48, x) + @testset "sizeof" begin @test sizeof(view(zeros(UInt8, 10), 1:4)) == 4 @test sizeof(view(zeros(UInt8, 10), 1:3)) == 3 @test sizeof(view(zeros(Float64, 10, 10), 1:3, 2:6)) == 120 # Test non-power of 2 types (Issue #35884) - primitive type UInt48 48 end - UInt48(x::UInt64) = Core.Intrinsics.trunc_int(UInt48, x) - UInt48(x::UInt32) = Core.Intrinsics.zext_int(UInt48, x) - a = UInt48(0x00000001); b = UInt48(0x00000002); c = UInt48(0x00000003); @@ -607,6 +607,15 @@ end @test sizeof(view(Diagonal(zeros(Float64, 10)), 1:3, 2:6)) == 120 end +@testset "write" begin + io = IOBuffer() + a = UInt48[ UInt48(UInt32(i+j)) for i = 1:5, j = 1:5 ] + @test write(io, view(a, :, 2)) == 40 + seekstart(io) + v = Vector{UInt48}(undef, 5) + read!(io, v) + @test v == view(a, :, 2) +end @testset "unaliascopy trimming; Issue #26263" begin A = rand(5,5,5,5)