From 53720c80d7d1aef2d419e468d574cf17cf55fd04 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Gonz=C3=A1lez?= Date: Mon, 2 Sep 2024 11:50:35 +0200 Subject: [PATCH 1/2] Guard against length-1 edge case --- src/FindFirstFunctions.jl | 4 +++- test/runtests.jl | 14 ++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/FindFirstFunctions.jl b/src/FindFirstFunctions.jl index 6322da8..744adf3 100644 --- a/src/FindFirstFunctions.jl +++ b/src/FindFirstFunctions.jl @@ -233,7 +233,9 @@ end function (g::Guesser)(x) (; v, idx_prev, linear_lookup) = g if linear_lookup - f = (x - first(v)) / (last(v) - first(v)) + δx = x - first(v) + δx == 0 && return firstindex(v) + f = δx / (last(v) - first(v)) if isinf(f) f > 0 ? lastindex(v) : firstindex(v) else diff --git a/test/runtests.jl b/test/runtests.jl index 1e49042..2d3a88b 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -39,5 +39,19 @@ using SafeTestsets, Test @test searchsortedfirstcorrelated(v, 4.0, guesser_linear) == 3 @test searchsortedlastcorrelated(v, 4.0, guesser_prev) == 2 @test guesser_prev.idx_prev[] == 2 + + # Edge case + v1 = [42.0] + guesser = Guesser(v1) + @test guesser_linear.linear_lookup + @test guesser(100) == 1 + @test guesser(42.0) == 1 + @test guesser(0) == 1 + @test searchsortedfirstcorrelated(v1, 0, guesser) == 1 + @test searchsortedfirstcorrelated(v1, 100, guesser) == 1 + 1 # see searchsortedfirst + @test searchsortedfirstcorrelated(v1, 42.0, guesser) == 1 + @test searchsortedlastcorrelated(v1, 0, guesser) == 1 - 1 # see searchsortedlast + @test searchsortedlastcorrelated(v1, 100, guesser) == 1 + @test searchsortedlastcorrelated(v1, 42.0, guesser) == 1 end end From 72d9f76f0a1cbdc1148a19787a206f649dff8e2c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Gonz=C3=A1lez?= Date: Mon, 2 Sep 2024 11:52:31 +0200 Subject: [PATCH 2/2] Generalize the check for 0 --- src/FindFirstFunctions.jl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/FindFirstFunctions.jl b/src/FindFirstFunctions.jl index 744adf3..c324303 100644 --- a/src/FindFirstFunctions.jl +++ b/src/FindFirstFunctions.jl @@ -234,7 +234,7 @@ function (g::Guesser)(x) (; v, idx_prev, linear_lookup) = g if linear_lookup δx = x - first(v) - δx == 0 && return firstindex(v) + iszero(δx) && return firstindex(v) f = δx / (last(v) - first(v)) if isinf(f) f > 0 ? lastindex(v) : firstindex(v)