Skip to content

Commit

Permalink
throw if no fields (#235)
Browse files Browse the repository at this point in the history
* throw if no fields

* after code review
  • Loading branch information
aplavin authored and piever committed Sep 5, 2022
1 parent 70a743e commit 7b955d8
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 10 deletions.
18 changes: 8 additions & 10 deletions src/structarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,11 @@ struct StructArray{T, N, C<:Tup, I} <: AbstractArray{T, N}
components::C

function StructArray{T, N, C}(c) where {T, N, C<:Tup}
if length(c) > 0
ax = axes(first(c))
length(ax) == N || error("wrong number of dimensions")
map(tail(c)) do ci
axes(ci) == ax || error("all field arrays must have same shape")
end
isempty(c) && error("at least one component array is required")
ax = axes(first(c))
length(ax) == N || error("wrong number of dimensions")
map(tail(c)) do ci
axes(ci) == ax || error("all field arrays must have same shape")
end
new{T, N, C, index_type(c)}(c)
end
Expand Down Expand Up @@ -91,9 +90,10 @@ julia> StructArray(a=zeros(2,2), b=ones(2,2))
"""
StructArray(tup::Union{Tuple,NamedTuple})

function StructArray{T}(c::C) where {T, C<:Tup}
function StructArray{T}(c::Tup) where {T}
cols = strip_params(staticschema(T))(c)
N = isempty(cols) ? 1 : ndims(cols[1])
isempty(cols) && error("at least one component array is required")
N = ndims(first(cols))
StructArray{T, N, typeof(cols)}(cols)
end

Expand Down Expand Up @@ -333,9 +333,7 @@ staticschema(::Type{StructArray{T, N, C, I}}) where {T, N, C, I} = staticschema(
createinstance(::Type{<:StructArray{T}}, args...) where {T} = StructArray{T}(args)

Base.size(s::StructArray) = size(components(s)[1])
Base.size(s::StructArray{<:Any, <:Any, <:EmptyTup}) = (0,)
Base.axes(s::StructArray) = axes(components(s)[1])
Base.axes(s::StructArray{<:Any, <:Any, <:EmptyTup}) = (1:0,)

"""
StructArrays.get_ith(cols::Union{Tuple,NamedTuple}, I...)
Expand Down
8 changes: 8 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -433,6 +433,14 @@ end
t = StructVector([(a=1,), (a=missing,)])::StructVector
@test isequal(t.a, [1, missing])
@test eltype(t) <: NamedTuple{(:a,)}

@test_throws ErrorException StructArray([nothing])
@test_throws ErrorException StructArray([1, 2, 3])
@test_throws ErrorException StructArray{Nothing}(())
@test_throws ErrorException StructArray{Tuple{}}(())
NT = NamedTuple{(), Tuple{}}
@test_throws ErrorException StructArray{NT}((a=rand(10),))
@test_throws ErrorException StructArray{Tuple{}, 1, Tuple{}}(())
end

@testset "tuple case" begin
Expand Down

0 comments on commit 7b955d8

Please sign in to comment.