Skip to content

Commit c69a202

Browse files
authored
add special case for findlast on tuples of length >= 32, fixes #45117 (#45254)
1 parent 0ba4e71 commit c69a202

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

base/tuple.jl

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -419,10 +419,17 @@ function _findfirst_loop(f::Function, t)
419419
end
420420
findfirst(f::Function, t::Tuple) = length(t) < 32 ? _findfirst_rec(f, 1, t) : _findfirst_loop(f, t)
421421

422-
function findlast(f::Function, x::Tuple)
422+
findlast(f::Function, t::Tuple) = length(t) < 32 ? _findlast_rec(f, t) : _findlast_loop(f, t)
423+
function _findlast_rec(f::Function, x::Tuple)
423424
r = findfirst(f, reverse(x))
424425
return isnothing(r) ? r : length(x) - r + 1
425426
end
427+
function _findlast_loop(f::Function, t)
428+
for i in reverse(1:length(t))
429+
f(t[i]) && return i
430+
end
431+
return nothing
432+
end
426433

427434
## filter ##
428435

test/tuple.jl

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -600,6 +600,12 @@ end
600600
@test Base.return_types() do
601601
findlast(==(0), (1.0,2,3f0))
602602
end == Any[Nothing]
603+
604+
@testset "long tuples" begin
605+
longtuple = ntuple(i -> i in (15,17) ? 1 : 0, 40)
606+
@test findfirst(isequal(1), longtuple) == 15
607+
@test findlast(isequal(1), longtuple) == 17
608+
end
603609
end
604610

605611
@testset "properties" begin

0 commit comments

Comments
 (0)