Skip to content

Commit

Permalink
Allow clamp(n, 1:10) (JuliaLang#37548)
Browse files Browse the repository at this point in the history
* clamp method for unitrange

* add tests & narrower type

* move to Base.Math

* triple equals

Co-authored-by: Michael Abbott <me@escbook>
  • Loading branch information
mcabbott and Michael Abbott committed Nov 12, 2020
1 parent 36efff9 commit ef69851
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
9 changes: 9 additions & 0 deletions base/math.jl
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,15 @@ function clamp!(x::AbstractArray, lo, hi)
x
end

"""
clamp(x::Integer, r::AbstractUnitRange)
Clamp `x` to lie within range `r`.
!!! compat "Julia 1.6"
This method requires at least Julia 1.6.
"""
clamp(x::Integer, r::AbstractUnitRange{<:Integer}) = clamp(x, first(r), last(r))

"""
evalpoly(x, p)
Expand Down
14 changes: 14 additions & 0 deletions test/ranges.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1633,6 +1633,20 @@ end
@test_throws DivideError mod(3, 1:0)
end

@testset "clamp with unitrange" begin
for n in -10:10
@test clamp(n, 0:4) == clamp(n, 0, 4)
@test clamp(n, Base.OneTo(5)) == clamp(n, 1, 5)
end
@test clamp(Int32(3), 1:5) === Int(3)
@test clamp(big(typemax(Int))+99, 0:4) == 4
@test_throws MethodError clamp(3.141, 1:5)
@test_throws MethodError clamp(3, UnitRange(1.0,5.0))
@test_throws MethodError clamp(3, 1:2:7)
@test clamp(3, 1:0) == clamp(3, 1, 0) == 0
@test clamp(-3, 1:0) == clamp(-3, 1, 0) == 1
end

@testset "issue #33882" begin
r = StepRangeLen('a',2,4)
@test step(r) === 2
Expand Down

0 comments on commit ef69851

Please sign in to comment.