Skip to content

Commit 3b97b61

Browse files
committed
use isvalid instead of try/catch in generic implementation (StefanKarpinski)
1 parent 533dfb3 commit 3b97b61

File tree

1 file changed

+5
-11
lines changed

1 file changed

+5
-11
lines changed

base/random.jl

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -713,24 +713,18 @@ rand(rng::AbstractRNG, r::AbstractArray, dims::Integer...) = rand(rng, r, conver
713713
# rand from a string
714714

715715
isvalid_unsafe(s::String, i) = !Base.is_valid_continuation(unsafe_load(pointer(s), i))
716+
isvalid_unsafe(s::AbstractString, i) = isvalid(s, i)
717+
_endof(s::String) = s.len
718+
_endof(s::AbstractString) = endof(s)
716719

717-
function rand(rng::AbstractRNG, s::String)::Char
718-
g = RangeGenerator(1:s.len)
720+
function rand(rng::AbstractRNG, s::AbstractString)::Char
721+
g = RangeGenerator(1:_endof(s))
719722
while true
720723
pos = rand(rng, g)
721724
isvalid_unsafe(s, pos) && return s[pos]
722725
end
723726
end
724727

725-
function rand(rng::AbstractRNG, s::AbstractString)::Char
726-
g = RangeGenerator(1:endof(s))
727-
while true
728-
try # the generic `isvalid` includes an equivalent try/catch statement
729-
return s[rand(rng, g)]
730-
end
731-
end
732-
end
733-
734728
rand(s::AbstractString) = rand(GLOBAL_RNG, s)
735729

736730
## rand from a string for arrays

0 commit comments

Comments
 (0)