Skip to content

Commit

Permalink
use isvalid instead of try/catch in generic implementation (StefanKar…
Browse files Browse the repository at this point in the history
…pinski)
  • Loading branch information
rfourquet committed Jun 13, 2017
1 parent 533dfb3 commit 3b97b61
Showing 1 changed file with 5 additions and 11 deletions.
16 changes: 5 additions & 11 deletions base/random.jl
Original file line number Diff line number Diff line change
Expand Up @@ -713,24 +713,18 @@ rand(rng::AbstractRNG, r::AbstractArray, dims::Integer...) = rand(rng, r, conver
# rand from a string

isvalid_unsafe(s::String, i) = !Base.is_valid_continuation(unsafe_load(pointer(s), i))
isvalid_unsafe(s::AbstractString, i) = isvalid(s, i)
_endof(s::String) = s.len
_endof(s::AbstractString) = endof(s)

function rand(rng::AbstractRNG, s::String)::Char
g = RangeGenerator(1:s.len)
function rand(rng::AbstractRNG, s::AbstractString)::Char
g = RangeGenerator(1:_endof(s))
while true
pos = rand(rng, g)
isvalid_unsafe(s, pos) && return s[pos]
end
end

function rand(rng::AbstractRNG, s::AbstractString)::Char
g = RangeGenerator(1:endof(s))
while true
try # the generic `isvalid` includes an equivalent try/catch statement
return s[rand(rng, g)]
end
end
end

rand(s::AbstractString) = rand(GLOBAL_RNG, s)

## rand from a string for arrays
Expand Down

0 comments on commit 3b97b61

Please sign in to comment.