Skip to content

Commit a8fd370

Browse files
authored
Specialize zeros/ones/fill for SOneTo (#1234)
* Specialize zeros/ones/fill for SOneTo * Add comment * Restrict methods to SOneTo
1 parent 819dbc6 commit a8fd370

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

src/abstractarray.jl

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,3 +291,19 @@ function Base.view(S::SArray, I::Union{Colon, Integer, SOneTo, StaticArray{<:Tup
291291
V = getindex(S, I...)
292292
_maybewrapscalar(S, V)
293293
end
294+
295+
# zeros, ones and fill may return SArrays if all the axes are statically sized
296+
for (arrf, elf) in ((:zeros, :zero), (:ones, :one))
297+
_arrf = Symbol(:_, arrf)
298+
@eval begin
299+
function $arrf(::Type{T}, ax::Tuple{SOneTo,Vararg{SOneTo}}) where {T}
300+
sz = homogenize_shape(ax)
301+
similar_type(SArray, T, sz)(ntuple(_->$elf(T), prod(sz)))
302+
end
303+
end
304+
end
305+
306+
function fill(v, ax::Tuple{SOneTo,Vararg{SOneTo}})
307+
sz = homogenize_shape(ax)
308+
similar_type(SArray, typeof(v), sz)(ntuple(_->v, prod(sz)))
309+
end

test/abstractarray.jl

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -418,3 +418,14 @@ end
418418
@test b isa Vec{0}
419419
end
420420
end
421+
422+
@testset "zeros/ones/fill" begin
423+
for ax in ((SOneTo(2),), (SOneTo(2),SOneTo(3)))
424+
@test @inferred(fill(:abc, ax...)) === @inferred(fill(:abc, ax))
425+
@test fill(:abc, ax) == fill(:abc, length.(ax)) == fill(:abc, Base.OneTo.(length.(ax)))
426+
for fz in (zeros, ones)
427+
@test @inferred(fz(Float32, ax...)) === @inferred(fz(Float32, ax))
428+
@test fz(Float32, ax) == fz(Float32, length.(ax)) == fz(Float32, Base.OneTo.(length.(ax)))
429+
end
430+
end
431+
end

0 commit comments

Comments
 (0)