Skip to content

Commit 1b0e987

Browse files
KenoKristofferC
authored andcommitted
Add clamp(x, T) (#34426)
This is #22235, but with the reversed argument order. ``` julia> clamp( 260, UInt8 ) 0xff ``` Co-authored-by: "arghhhh <david.hossack@gmail.com>"
1 parent 2c18e99 commit 1b0e987

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

base/math.jl

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,22 @@ clamp(x::X, lo::L, hi::H) where {X,L,H} =
6868
convert(promote_type(X,L,H), lo),
6969
convert(promote_type(X,L,H), x)))
7070

71+
"""
72+
clamp(x, T)::T
73+
74+
Clamp `x` between `typemin(T)` and `typemax(T)` and convert the result to type `T`.
75+
76+
# Examples
77+
```jldoctest
78+
julia> clamp(200, Int8)
79+
127
80+
julia> clamp(-200, Int8)
81+
-128
82+
```
83+
"""
84+
clamp(x, ::Type{T}) where {T<:Integer} = clamp(x, typemin(T), typemax(T)) % T
85+
86+
7187
"""
7288
clamp!(array::AbstractArray, lo, hi)
7389

test/math.jl

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,11 @@ end
2222

2323
@test clamp.([0, 1, 2, 3, 4], 1.0, 3.0) == [1.0, 1.0, 2.0, 3.0, 3.0]
2424
@test clamp.([0 1; 2 3], 1.0, 3.0) == [1.0 1.0; 2.0 3.0]
25+
26+
@test clamp(-200, Int8) === typemin(Int8)
27+
@test clamp(100, Int8) === Int8(100)
28+
@test clamp(200, Int8) === typemax(Int8)
29+
2530
begin
2631
x = [0.0, 1.0, 2.0, 3.0, 4.0]
2732
clamp!(x, 1, 3)

0 commit comments

Comments
 (0)