Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Converting between integer types #22235

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions base/math.jl
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,24 @@ 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(T, x)

Clamp `x` between `typemin(T)` and `typemax(T)` and convert the result to type `T`.

```jldoctest
julia> clamp(Int8, 200)
127

julia> clamp(Int8, -200)
-128
```
"""
clamp(::Type{T}, x) where {T<:Integer} = clamp(x, typemin(T), typemax(T)) % T

"""
clamp!(array::AbstractArray, lo, hi)
clamp!(array::AbstractArray, T)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line should be removed since you aren't defining this method


Restrict values in `array` to the specified range, in-place.
See also [`clamp`](@ref).
Expand Down
5 changes: 5 additions & 0 deletions test/math.jl
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@

@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(Int8,-200) === typemin(Int8)
@test clamp(Int8,100) === Int8(100)
@test clamp(Int8,200) === typemax(Int8)

begin
x = [0.0, 1.0, 2.0, 3.0, 4.0]
clamp!(x, 1, 3)
Expand Down