From 5bed77063e96cccab3411543fd578665ad312ebd Mon Sep 17 00:00:00 2001 From: Keno Fischer Date: Sat, 18 Jan 2020 21:40:10 -0500 Subject: [PATCH] Add clamp(x, T) (#34426) This is #22235, but with the reversed argument order. ``` julia> clamp( 260, UInt8 ) 0xff ``` Co-authored-by: "arghhhh " --- base/math.jl | 16 ++++++++++++++++ test/math.jl | 5 +++++ 2 files changed, 21 insertions(+) diff --git a/base/math.jl b/base/math.jl index c3429723db932..875a2be7d1998 100644 --- a/base/math.jl +++ b/base/math.jl @@ -68,6 +68,22 @@ clamp(x::X, lo::L, hi::H) where {X,L,H} = convert(promote_type(X,L,H), lo), convert(promote_type(X,L,H), x))) +""" + clamp(x, T)::T + +Clamp `x` between `typemin(T)` and `typemax(T)` and convert the result to type `T`. + +# Examples +```jldoctest +julia> clamp(200, Int8) +127 +julia> clamp(-200, Int8) +-128 +``` +""" +clamp(x, ::Type{T}) where {T<:Integer} = clamp(x, typemin(T), typemax(T)) % T + + """ clamp!(array::AbstractArray, lo, hi) diff --git a/test/math.jl b/test/math.jl index 4515f8ca7b862..22d7f91685a0a 100644 --- a/test/math.jl +++ b/test/math.jl @@ -22,6 +22,11 @@ end @test clamp.([0, 1, 2, 3, 4], 1.0, 3.0) == [1.0, 1.0, 2.0, 3.0, 3.0] @test clamp.([0 1; 2 3], 1.0, 3.0) == [1.0 1.0; 2.0 3.0] + + @test clamp(-200, Int8) === typemin(Int8) + @test clamp(100, Int8) === Int8(100) + @test clamp(200, Int8) === typemax(Int8) + begin x = [0.0, 1.0, 2.0, 3.0, 4.0] clamp!(x, 1, 3)