Skip to content

Commit

Permalink
faster rand(::UnitRange{Bool})
Browse files Browse the repository at this point in the history
  • Loading branch information
rfourquet committed Dec 19, 2017
1 parent c16c0cb commit 1ff6f6a
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions base/random/generation.jl
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,32 @@ end

## Generate random integer within a range

### Bool

struct SamplerRangeBool <: Sampler
a::Bool
mask::Bool
end

function SamplerRangeBool(r::AbstractUnitRange{Bool})
s = last(r) - first(r)
s < 0 && throw(ArgumentError("range must be non-empty"))
SamplerRangeBool(first(r), s % Bool)
end

rand(rng::AbstractRNG, sp::SamplerRangeBool) =
_rand(rng, sp, rng_gen_bool(rng))

rng_gen_bool(::AbstractRNG) = Val(:Default)

_rand(rng::AbstractRNG, sp::SamplerRangeBool, ::Val{:FastBool}) =
sp.a (rand(rng, Bool) & sp.mask)

_rand(rng::AbstractRNG, sp::SamplerRangeBool, ::Val{:Default}) =
sp.mask ? rand(rng, UInt8) % Bool : # sp.a == false
sp.a


### BitInteger

# there are two implemented samplers for unit ranges, which assume that Float64 (i.e.
Expand Down

0 comments on commit 1ff6f6a

Please sign in to comment.