Skip to content

Commit 7819a3c

Browse files
committed
Simpler flatten_tuples
1 parent ca5e6fa commit 7819a3c

File tree

1 file changed

+12
-19
lines changed

1 file changed

+12
-19
lines changed

lib/ArrayInterfaceCore/src/ArrayInterfaceCore.jl

Lines changed: 12 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -66,27 +66,20 @@ julia> ArrayInterfaceCore.flatten_tuples((1, (2, (3,))))
6666
6767
```
6868
"""
69-
@inline function flatten_tuples(t::Tuple)
70-
if @generated
71-
texpr = Expr(:tuple)
72-
for i in 1:fieldcount(t)
73-
p = fieldtype(t, i)
74-
if p <: Tuple
75-
for j in 1:fieldcount(p)
76-
push!(texpr.args, :(@inbounds(getfield(getfield(t, $i), $j))))
77-
end
78-
else
79-
push!(texpr.args, :(@inbounds(getfield(t, $i))))
80-
end
81-
end
82-
Expr(:block, Expr(:meta, :inline), texpr)
83-
else
84-
_flatten(t)
69+
function flatten_tuples(t::Tuple)
70+
fields = _new_field_positions(t)
71+
ntuple(Val{nfields(fields)}()) do k
72+
i, j = getfield(fields, k)
73+
i = length(t) - i
74+
@inbounds j === 0 ? getfield(t, i) : getfield(getfield(t, i), j)
8575
end
8676
end
87-
_flatten(::Tuple{}) = ()
88-
@inline _flatten(t::Tuple{Any,Vararg{Any}}) = (getfield(t, 1), _flatten(Base.tail(t))...)
89-
@inline _flatten(t::Tuple{Tuple,Vararg{Any}}) = (getfield(t, 1)..., _flatten(Base.tail(t))...)
77+
_new_field_positions(::Tuple{}) = ()
78+
@nospecialize
79+
_new_field_positions(x::Tuple) = (_fl1(x, x[1])..., _new_field_positions(Base.tail(x))...)
80+
_fl1(x::Tuple, x1::Tuple) = ntuple(Base.Fix1(tuple, length(x) - 1), Val(length(x1)))
81+
_fl1(x::Tuple, x1) = ((length(x) - 1, 0),)
82+
@specialize
9083

9184
"""
9285
parent_type(::Type{T}) -> Type

0 commit comments

Comments
 (0)