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

add rand(::String) #22224

Merged
merged 7 commits into from
Jun 15, 2017
Merged
Changes from 1 commit
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
Prev Previous commit
Next Next commit
use isvalid instead of try/catch in generic implementation (StefanKar…
…pinski)
  • Loading branch information
rfourquet committed Jun 13, 2017
commit 3b97b615b46c27487ab53d25b7d15c84980a33bf
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