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

Make StructArrays broadcast aware #90

Closed
wants to merge 1 commit 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
11 changes: 9 additions & 2 deletions src/structarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,14 @@ index_type(::Type{NamedTuple{names, types}}) where {names, types} = index_type(t
index_type(::Type{Tuple{}}) = Int
function index_type(::Type{T}) where {T<:Tuple}
S, U = tuple_type_head(T), tuple_type_tail(T)
IndexStyle(S) isa IndexCartesian ? CartesianIndex{ndims(S)} : index_type(U)
IndexStyle(S) isa IndexCartesian ? CartesianIndex{ndims(S)} : index_type(U)
end

index_type(::Type{StructArray{T, N, C, I}}) where {T, N, C, I} = I

function StructArray{T}(c::C) where {T, C<:Tup}
cols = strip_params(staticschema(T))(c)
N = isempty(cols) ? 1 : ndims(cols[1])
N = isempty(cols) ? 1 : ndims(cols[1])
StructArray{T, N, typeof(cols)}(cols)
end

Expand Down Expand Up @@ -227,3 +227,10 @@ function Base.showarg(io::IO, s::StructArray{T}, toplevel) where T
showfields(io, Tuple(fieldarrays(s)))
toplevel && print(io, " with eltype ", T)
end

# broadcast
import Base.Broadcast: BroadcastStyle, ArrayStyle, Broadcasted

BroadcastStyle(::Type{<:StructArray}) = ArrayStyle{StructArray}()
Base.similar(bc::Broadcasted{ArrayStyle{StructArray}}, ::Type{ElType}) where {N,ElType} =
similar(StructArray{ElType}, axes(bc))
5 changes: 5 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -646,3 +646,8 @@ end
str = String(take!(io))
@test str == "StructArray(::Array{Int64,1}, ::Array{Int64,1})"
end

@testset "broadcast" begin
s = StructArray{ComplexF64}((rand(2,2), rand(2,2)))
@test isa(s .+ s, StructArray)
Copy link
Collaborator

Choose a reason for hiding this comment

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

Probably this also needs to test that things like broadcast(t -> 1, s) don't give an error (I'm not sure what exactly should happen when the result of broadcasting StructArrays has a eltype that is not a struct).

end