From 9a8ddd0c4339c98566ee0c4d3166bc8fb0f118fd Mon Sep 17 00:00:00 2001 From: Kristoffer Carlsson Date: Fri, 27 May 2022 20:33:25 +0200 Subject: [PATCH] Disallow reinterpreting a non-singleton array into a singleton type (#45370) (#45467) (cherry picked from commit fc52b3f1a7386400e3035fe3ab4283df03e968bd) Co-authored-by: Lionel Zoubritzky --- base/reinterpretarray.jl | 8 ++++---- test/reinterpretarray.jl | 6 ++++-- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/base/reinterpretarray.jl b/base/reinterpretarray.jl index 3b54ed04089cd..9211a66a99cbe 100644 --- a/base/reinterpretarray.jl +++ b/base/reinterpretarray.jl @@ -19,9 +19,9 @@ struct ReinterpretArray{T,N,S,A<:AbstractArray{S},IsReshaped} <: AbstractArray{T @noinline throw(ArgumentError("cannot reinterpret a zero-dimensional `$(S)` array to `$(T)` which is of a $msg size")) end - function throwsingleton(S::Type, T::Type, kind) + function throwsingleton(S::Type, T::Type) @noinline - throw(ArgumentError("cannot reinterpret $kind `$(S)` array to `$(T)` which is a singleton type")) + throw(ArgumentError("cannot reinterpret a `$(S)` array to `$(T)` which is a singleton type")) end global reinterpret @@ -44,7 +44,7 @@ struct ReinterpretArray{T,N,S,A<:AbstractArray{S},IsReshaped} <: AbstractArray{T ax1 = axes(a)[1] dim = length(ax1) if issingletontype(T) - dim == 0 || throwsingleton(S, T, "a non-empty") + issingletontype(S) || throwsingleton(S, T) else rem(dim*sizeof(S),sizeof(T)) == 0 || thrownonint(S, T, dim) end @@ -75,7 +75,7 @@ struct ReinterpretArray{T,N,S,A<:AbstractArray{S},IsReshaped} <: AbstractArray{T if sizeof(S) == sizeof(T) N = ndims(a) elseif sizeof(S) > sizeof(T) - issingletontype(T) && throwsingleton(S, T, "with reshape a") + issingletontype(T) && throwsingleton(S, T) rem(sizeof(S), sizeof(T)) == 0 || throwintmult(S, T) N = ndims(a) + 1 else diff --git a/test/reinterpretarray.jl b/test/reinterpretarray.jl index e623b407f70a6..bc3ffa63b0b0c 100644 --- a/test/reinterpretarray.jl +++ b/test/reinterpretarray.jl @@ -465,9 +465,11 @@ end @test_throws ArgumentError reinterpret(Nothing, 1:6) @test_throws ArgumentError reinterpret(reshape, Missing, [0.0]) - # reintepret of empty array with reshape - @test reinterpret(reshape, Nothing, fill(missing, (0,0,0))) == fill(nothing, (0,0,0)) + # reintepret of empty array + @test reinterpret(reshape, Nothing, fill(missing, (1,0,3))) == fill(nothing, (1,0,3)) + @test reinterpret(reshape, Missing, fill((), (0,))) == fill(missing, (0,)) @test_throws ArgumentError reinterpret(reshape, Nothing, fill(3.2, (0,0))) + @test_throws ArgumentError reinterpret(Missing, fill(77, (0,1))) @test_throws ArgumentError reinterpret(reshape, Float64, fill(nothing, 0)) # reinterpret of 0-dimensional array