Skip to content

Commit

Permalink
Add clamp(x, T) (#34426)
Browse files Browse the repository at this point in the history
This is #22235, but with the reversed argument order.
```
julia> clamp( 260, UInt8 )
0xff
```

Co-authored-by: "arghhhh <[email protected]>"
  • Loading branch information
Keno authored and KristofferC committed Apr 11, 2020
1 parent 2c18e99 commit 1b0e987
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
16 changes: 16 additions & 0 deletions base/math.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
5 changes: 5 additions & 0 deletions test/math.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 1b0e987

Please sign in to comment.