Skip to content

Commit 9257562

Browse files
fix type instability of restrict (#124)
Co-authored-by: Jishnu Bhattacharya <[email protected]>
1 parent a476cee commit 9257562

File tree

1 file changed

+16
-10
lines changed

1 file changed

+16
-10
lines changed

src/resizing.jl

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -77,20 +77,26 @@ end
7777

7878
function restrict(A::AbstractArray{T,N}, dim::Integer) where {T,N}
7979
indsA = axes(A)
80-
newinds = ntuple(i->i==dim ? restrict_indices(indsA[dim]) : indsA[i], Val(N))
81-
out = similar(Array{restrict_eltype(first(A)),N}, newinds)
80+
newinds = map(UnitRange, ntuple(i->i==dim ? restrict_indices(indsA[dim]) : indsA[i], Val(N)))
81+
out = similar(Array{restrict_eltype(first(A)), N}, newinds)
8282
restrict!(out, A, dim)
8383
out
8484
end
8585

86-
restrict_eltype_default(x) = typeof(x/4 + x/2)
87-
restrict_eltype(x) = restrict_eltype_default(x)
88-
restrict_eltype(x::AbstractGray) = restrict_eltype_default(x)
89-
restrict_eltype(x::AbstractRGB) = restrict_eltype_default(x)
90-
restrict_eltype(x::Color) = restrict_eltype_default(convert(RGB, x))
91-
restrict_eltype(x::TransparentGray) = restrict_eltype_default(x)
92-
restrict_eltype(x::TransparentRGB) = restrict_eltype_default(x)
93-
restrict_eltype(x::Colorant) = restrict_eltype_default(convert(ARGB, x))
86+
function restrict_eltype(A::AbstractArray)
87+
# infer the restrict_eltype on `eltype(A)` while preserving the container type
88+
# TODO: maybe there's more efficient way than the `similar` here..
89+
typeof(similar(A, _restrict_eltype(eltype(A)), ntuple(_->1, ndims(A))))
90+
end
91+
restrict_eltype(x) = _restrict_eltype(typeof(x))
92+
93+
for CT in (:AbstractGray, :AbstractRGB, :TransparentGray, :TransparentRGB)
94+
@eval _restrict_eltype(::Type{C}) where C<:$CT = __restrict_eltype(C)
95+
end
96+
_restrict_eltype(::Type{T}) where T = typeof(one(T)/4 + one(T)/2)
97+
_restrict_eltype(::Type{C}) where C<:Color = __restrict_eltype(RGB{eltype(C)})
98+
_restrict_eltype(::Type{C}) where C<:Colorant = __restrict_eltype(ARGB{eltype(C)})
99+
__restrict_eltype(::Type{C}) where C = base_colorant_type(C){promote_type(eltype(C), Float32)}
94100

95101
function restrict!(out::AbstractArray{T,N}, A::AbstractArray, dim) where {T,N}
96102
if dim > N

0 commit comments

Comments
 (0)