From 34f7349660692bb294be5615bec0110f9014ddd5 Mon Sep 17 00:00:00 2001 From: Neven Sajko Date: Wed, 4 Mar 2026 14:41:40 +0100 Subject: [PATCH] refactor `x < 1` error checks: optimized inlining and less duplication --- src/IterTools.jl | 27 ++++++++++++++++----------- test/runtests.jl | 4 ++++ 2 files changed, 20 insertions(+), 11 deletions(-) diff --git a/src/IterTools.jl b/src/IterTools.jl index 0fc05e8..37126c6 100644 --- a/src/IterTools.jl +++ b/src/IterTools.jl @@ -43,6 +43,18 @@ function has_length(it) return isa(it_size, HasLength) || isa(it_size, HasShape) end +@noinline function throw_not_positive_int(n::Int, msg) + s = lazy"$msg $n must be a positive integer" + throw(ArgumentError(s)) +end + +function validated_positive_int(n::Int, msg) + if n < 1 + throw_not_positive_int(n, msg) + end + n +end + # return the size for methods depending on the longest iterator longest(::T, ::T) where {T<:IteratorSize} = T() function longest(::S, ::T) where {T<:IteratorSize, S<:IteratorSize} @@ -316,13 +328,8 @@ i = (7, 8) @inline partition(xs, n::Int) = partition(xs, n, n) @inline function partition(xs::I, n::Int, step::Int) where I - if step < 1 - throw(ArgumentError("Partition step must be at least 1.")) - end - if n < 1 - throw(ArgumentError("Partition size n must be at least 1.")) - end - + step = validated_positive_int(step, "partition step") + n = validated_positive_int(n, "partition size") Partition{I, n, step}(xs) end @@ -674,10 +681,8 @@ julia> collect(takenth(5:15,3)) ``` """ function takenth(xs, interval::Integer) - if interval <= 0 - throw(ArgumentError(string("expected interval to be 1 or more, ", - "got $interval"))) - end + interval = Int(interval)::Int + interval = validated_positive_int(interval, "interval") TakeNth(xs, convert(UInt, interval)) end diff --git a/test/runtests.jl b/test/runtests.jl index 6aa6372..2b375dc 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -136,6 +136,10 @@ include("testing_macros.jl") # Test https://github.com/JuliaCollections/IterTools.jl/issues/39 _sliding_pairs_type(a) = eltype(IterTools.partition(a, 2, 1)) @inferred _sliding_pairs_type([1,2,3]) + + for n in (-2):0 + @test_throws ArgumentError partition(3:7, n) + end end @testset "imap" begin