• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

JuliaLang / julia / #37647

10 Oct 2023 06:49AM UTC coverage: 86.638% (-1.3%) from 87.96%
#37647

push

local

web-flow
srcfile module check: also allow single line docstrings (#51648)

4 of 4 new or added lines in 1 file covered. (100.0%)

71582 of 82622 relevant lines covered (86.64%)

12434033.01 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

92.37
/stdlib/Random/src/generation.jl
1
# This file is a part of Julia. License is MIT: https://julialang.org/license
2

3
# Uniform random generation
4

5
# This file contains the creation of Sampler objects and the associated generation of
6
# random values from them. More specifically, given the specification S of a set
7
# of values to pick from (e.g. 1:10, or "a string"), we define
8
#
9
# 1) Sampler(rng, S, ::Repetition) -> sampler
10
# 2) rand(rng, sampler) -> random value
11
#
12
# Note that the 1) is automated when the sampler is not intended to carry information,
13
# i.e. the default fall-backs SamplerType and SamplerTrivial are used.
14

15
## from types: rand(::Type, [dims...])
16

17
### random floats
18

19
Sampler(::Type{RNG}, ::Type{T}, n::Repetition) where {RNG<:AbstractRNG,T<:AbstractFloat} =
83,555,894✔
20
    Sampler(RNG, CloseOpen01(T), n)
21

22
# generic random generation function which can be used by RNG implementors
23
# it is not defined as a fallback rand method as this could create ambiguities
24

25
rand(r::AbstractRNG, ::SamplerTrivial{CloseOpen01{Float16}}) =
6,415✔
26
    Float16(reinterpret(Float32,
27
                        (rand(r, UInt10(UInt32)) << 13)  | 0x3f800000) - 1)
28

29
rand(r::AbstractRNG, ::SamplerTrivial{CloseOpen01{Float32}}) =
6,391✔
30
    reinterpret(Float32, rand(r, UInt23()) | 0x3f800000) - 1
31

32
rand(r::AbstractRNG, ::SamplerTrivial{CloseOpen12_64}) =
44,615✔
33
    reinterpret(Float64, 0x3ff0000000000000 | rand(r, UInt52()))
34

35
rand(r::AbstractRNG, ::SamplerTrivial{CloseOpen01_64}) = rand(r, CloseOpen12()) - 1.0
414,026✔
36

37
#### BigFloat
38

39
const bits_in_Limb = sizeof(Limb) << 3
40
const Limb_high_bit = one(Limb) << (bits_in_Limb-1)
41

42
struct SamplerBigFloat{I<:FloatInterval{BigFloat}} <: Sampler{BigFloat}
43
    prec::Int
44
    nlimbs::Int
45
    limbs::Vector{Limb}
46
    shift::UInt
47

48
    function SamplerBigFloat{I}(prec::Int) where I<:FloatInterval{BigFloat}
13,520,287✔
49
        nlimbs = (prec-1) ÷ bits_in_Limb + 1
13,520,287✔
50
        limbs = Vector{Limb}(undef, nlimbs)
13,520,287✔
51
        shift = nlimbs * bits_in_Limb - prec
13,520,287✔
52
        new(prec, nlimbs, limbs, shift)
13,520,287✔
53
    end
54
end
55

56
Sampler(::Type{<:AbstractRNG}, I::FloatInterval{BigFloat}, ::Repetition) =
13,520,287✔
57
    SamplerBigFloat{typeof(I)}(precision(BigFloat))
58

59
function _rand!(rng::AbstractRNG, z::BigFloat, sp::SamplerBigFloat)
13,562,213✔
60
    precision(z) == sp.prec || throw(ArgumentError("incompatible BigFloat precision"))
13,562,215✔
61
    limbs = sp.limbs
13,562,211✔
62
    rand!(rng, limbs)
13,562,211✔
63
    @inbounds begin
13,562,211✔
64
        limbs[1] <<= sp.shift
13,562,211✔
65
        randbool = iszero(limbs[end] & Limb_high_bit)
13,562,211✔
66
        limbs[end] |= Limb_high_bit
13,562,211✔
67
    end
68
    z.sign = 1
13,562,211✔
69
    GC.@preserve limbs unsafe_copyto!(z.d, pointer(limbs), sp.nlimbs)
13,562,211✔
70
    randbool
13,562,211✔
71
end
72

73
function _rand!(rng::AbstractRNG, z::BigFloat, sp::SamplerBigFloat, ::CloseOpen12{BigFloat})
3✔
74
    _rand!(rng, z, sp)
3✔
75
    z.exp = 1
2✔
76
    z
2✔
77
end
78

79
function _rand!(rng::AbstractRNG, z::BigFloat, sp::SamplerBigFloat, ::CloseOpen01{BigFloat})
13,562,210✔
80
    randbool = _rand!(rng, z, sp)
13,562,210✔
81
    z.exp = 0
13,562,209✔
82
    randbool &&
13,562,209✔
83
        ccall((:mpfr_sub_d, :libmpfr), Int32,
84
              (Ref{BigFloat}, Ref{BigFloat}, Cdouble, Base.MPFR.MPFRRoundingMode),
85
              z, z, 0.5, Base.MPFR.ROUNDING_MODE[])
86
    z
13,562,209✔
87
end
88

89
# alternative, with 1 bit less of precision
90
# TODO: make an API for requesting full or not-full precision
91
function _rand!(rng::AbstractRNG, z::BigFloat, sp::SamplerBigFloat, ::CloseOpen01{BigFloat},
×
92
                ::Nothing)
93
    _rand!(rng, z, sp, CloseOpen12(BigFloat))
×
94
    ccall((:mpfr_sub_ui, :libmpfr), Int32, (Ref{BigFloat}, Ref{BigFloat}, Culong, Base.MPFR.MPFRRoundingMode),
×
95
          z, z, 1, Base.MPFR.ROUNDING_MODE[])
96
    z
×
97
end
98

99
rand!(rng::AbstractRNG, z::BigFloat, sp::SamplerBigFloat{T}
×
100
      ) where {T<:FloatInterval{BigFloat}} =
13,562,213✔
101
          _rand!(rng, z, sp, T())
102

103
rand(rng::AbstractRNG, sp::SamplerBigFloat{T}) where {T<:FloatInterval{BigFloat}} =
13,562,209✔
104
    rand!(rng, BigFloat(; precision=sp.prec), sp)
105

106

107
### random integers
108

109
#### UniformBits
110

111
rand(r::AbstractRNG, ::SamplerTrivial{UInt10Raw{UInt16}}) = rand(r, UInt16)
6,415✔
112
rand(r::AbstractRNG, ::SamplerTrivial{UInt23Raw{UInt32}}) = rand(r, UInt32)
6,391✔
113

114
rand(r::AbstractRNG, ::SamplerTrivial{UInt52Raw{UInt64}}) =
5,366✔
115
    _rand52(r, rng_native_52(r))
116

117
_rand52(r::AbstractRNG, ::Type{Float64}) = reinterpret(UInt64, rand(r, CloseOpen12()))
×
118
_rand52(r::AbstractRNG, ::Type{UInt64})  = rand(r, UInt64)
5,366✔
119

120
rand(r::AbstractRNG, ::SamplerTrivial{UInt104Raw{UInt128}}) =
2✔
121
    rand(r, UInt52Raw(UInt128)) << 52 ⊻ rand(r, UInt52Raw(UInt128))
122

123
rand(r::AbstractRNG, ::SamplerTrivial{UInt10{UInt16}})   = rand(r, UInt10Raw())  & 0x03ff
6,415✔
124
rand(r::AbstractRNG, ::SamplerTrivial{UInt23{UInt32}})   = rand(r, UInt23Raw())  & 0x007fffff
6,391✔
125
rand(r::AbstractRNG, ::SamplerTrivial{UInt52{UInt64}})   = rand(r, UInt52Raw())  & 0x000fffffffffffff
6,441✔
126
rand(r::AbstractRNG, ::SamplerTrivial{UInt104{UInt128}}) = rand(r, UInt104Raw()) & 0x000000ffffffffffffffffffffffffff
×
127

128
rand(r::AbstractRNG, sp::SamplerTrivial{<:UniformBits{T}}) where {T} =
1,404,909✔
129
        rand(r, uint_default(sp[])) % T
130

131
#### BitInteger
132

133
# rand_generic methods are intended to help RNG implementors with common operations
134
# we don't call them simply `rand` as this can easily contribute to create
135
# ambiguities with user-side methods (forcing the user to resort to @eval)
136

137
rand_generic(r::AbstractRNG, T::Union{Bool,Int8,UInt8,Int16,UInt16,Int32,UInt32}) =
×
138
    rand(r, UInt52Raw()) % T[]
139

140
rand_generic(r::AbstractRNG, ::Type{UInt64}) =
×
141
    rand(r, UInt52Raw()) << 32 ⊻ rand(r, UInt52Raw())
142

143
rand_generic(r::AbstractRNG, ::Type{UInt128}) = _rand128(r, rng_native_52(r))
×
144

145
_rand128(r::AbstractRNG, ::Type{UInt64}) =
×
146
    ((rand(r, UInt64) % UInt128) << 64) ⊻ rand(r, UInt64)
147

148
function _rand128(r::AbstractRNG, ::Type{Float64})
×
149
    xor(rand(r, UInt52Raw(UInt128))  << 96,
×
150
        rand(r, UInt52Raw(UInt128))  << 48,
151
        rand(r, UInt52Raw(UInt128)))
152
end
153

154
rand_generic(r::AbstractRNG, ::Type{Int128}) = rand(r, UInt128) % Int128
×
155
rand_generic(r::AbstractRNG, ::Type{Int64})  = rand(r, UInt64) % Int64
×
156

157
### random complex numbers
158

159
rand(r::AbstractRNG, ::SamplerType{Complex{T}}) where {T<:Real} =
178,954✔
160
    complex(rand(r, T), rand(r, T))
161

162
### random characters
163

164
# returns a random valid Unicode scalar value (i.e. 0 - 0xd7ff, 0xe000 - # 0x10ffff)
165
function rand(r::AbstractRNG, ::SamplerType{T}) where {T<:AbstractChar}
495✔
166
    c = rand(r, 0x00000000:0x0010f7ff)
495✔
167
    (c < 0xd800) ? T(c) : T(c+0x800)
522✔
168
end
169

170
### random tuples
171

172
function Sampler(::Type{RNG}, ::Type{T}, n::Repetition) where {T<:Tuple, RNG<:AbstractRNG}
60✔
173
    tail_sp_ = Sampler(RNG, Tuple{Base.tail(fieldtypes(T))...}, n)
60✔
174
    SamplerTag{T}((Sampler(RNG, fieldtype(T, 1), n), tail_sp_.data...))
55✔
175
end
176

177
function Sampler(::Type{RNG}, ::Type{Tuple{Vararg{T, N}}}, n::Repetition) where {T, N, RNG<:AbstractRNG}
56✔
178
    if N > 0
56✔
179
        SamplerTag{Tuple{Vararg{T, N}}}((Sampler(RNG, T, n),))
55✔
180
    else
181
        SamplerTag{Tuple{}}(())
1✔
182
    end
183
end
184

185
function rand(rng::AbstractRNG, sp::SamplerTag{T}) where T<:Tuple
260✔
186
    ntuple(i -> rand(rng, sp.data[min(i, length(sp.data))]), Val{fieldcount(T)}())::T
863✔
187
end
188

189
### random pairs
190

191
function Sampler(::Type{RNG}, ::Type{Pair{A, B}}, n::Repetition) where {RNG<:AbstractRNG, A, B}
24✔
192
    sp1 = Sampler(RNG, A, n)
24✔
193
    sp2 = A === B ? sp1 : Sampler(RNG, B, n)
24✔
194
    SamplerTag{Ref{Pair{A,B}}}(sp1 => sp2) # Ref so that the gentype is Pair{A, B}
24✔
195
                                           # in SamplerTag's constructor
196
end
197

198
rand(rng::AbstractRNG, sp::SamplerTag{<:Ref{<:Pair}}) =
104✔
199
    rand(rng, sp.data.first) => rand(rng, sp.data.second)
200

201

202
## Generate random integer within a range
203

204
### BitInteger
205

206
# there are three implemented samplers for unit ranges, the second one
207
# assumes that Float64 (i.e. 52 random bits) is the native type for the RNG:
208
# 1) "Fast" (SamplerRangeFast), which is most efficient when the range length is close
209
#    (or equal) to a power of 2 from below.
210
#    The tradeoff is faster creation of the sampler, but more consumption of entropy bits.
211
# 2) "Slow" (SamplerRangeInt) which tries to use as few entropy bits as possible, at the
212
#    cost of a bigger upfront price associated with the creation of the sampler.
213
#    This sampler is most appropriate for slower random generators.
214
# 3) "Nearly Division Less" (NDL) which is generally the fastest algorithm for types of size
215
#    up to 64 bits. This is the default for these types since Julia 1.5.
216
#    The "Fast" algorithm can be faster than NDL when the length of the range is
217
#    less than and close to a power of 2.
218

219
Sampler(::Type{<:AbstractRNG}, r::AbstractUnitRange{T},
×
220
        ::Repetition) where {T<:Base.BitInteger64} = SamplerRangeNDL(r)
3,984,590✔
221

222
Sampler(::Type{<:AbstractRNG}, r::AbstractUnitRange{T},
×
223
        ::Repetition) where {T<:Union{Int128,UInt128}} = SamplerRangeFast(r)
40✔
224

225
#### helper functions
226

227
uint_sup(::Type{<:Base.BitInteger32}) = UInt32
400,765✔
228
uint_sup(::Type{<:Union{Int64,UInt64}}) = UInt64
3,584,028✔
229
uint_sup(::Type{<:Union{Int128,UInt128}}) = UInt128
76✔
230

231
#### Fast
232

233
struct SamplerRangeFast{U<:BitUnsigned,T<:BitInteger} <: Sampler{T}
234
    a::T      # first element of the range
103✔
235
    bw::UInt  # bit width
236
    m::U      # range length - 1
237
    mask::U   # mask generated values before threshold rejection
238
end
239

240
SamplerRangeFast(r::AbstractUnitRange{T}) where T<:BitInteger =
103✔
241
    SamplerRangeFast(r, uint_sup(T))
242

243
function SamplerRangeFast(r::AbstractUnitRange{T}, ::Type{U}) where {T,U}
103✔
244
    isempty(r) && throw(ArgumentError("collection must be non-empty"))
103✔
245
    m = (last(r) - first(r)) % unsigned(T) % U # % unsigned(T) to not propagate sign bit
103✔
246
    bw = (Base.top_set_bit(m)) % UInt # bit-width
103✔
247
    mask = ((1 % U) << bw) - (1 % U)
103✔
248
    SamplerRangeFast{U,T}(first(r), bw, m, mask)
103✔
249
end
250

251
function rand(rng::AbstractRNG, sp::SamplerRangeFast{UInt32,T}) where T
36✔
252
    a, bw, m, mask = sp.a, sp.bw, sp.m, sp.mask
36✔
253
    # below, we don't use UInt32, to get reproducible values, whether Int is Int64 or Int32
254
    x = rand(rng, LessThan(m, Masked(mask, UInt52Raw(UInt32))))
41✔
255
    (x + a % UInt32) % T
36✔
256
end
257

258
has_fast_64(rng::AbstractRNG) = rng_native_52(rng) != Float64
73✔
259
# for MersenneTwister, both options have very similar performance
260

261
function rand(rng::AbstractRNG, sp::SamplerRangeFast{UInt64,T}) where T
9✔
262
    a, bw, m, mask = sp.a, sp.bw, sp.m, sp.mask
9✔
263
    if !has_fast_64(rng) && bw <= 52
9✔
264
        x = rand(rng, LessThan(m, Masked(mask, UInt52Raw())))
3✔
265
    else
266
        x = rand(rng, LessThan(m, Masked(mask, uniform(UInt64))))
7✔
267
    end
268
    (x + a % UInt64) % T
9✔
269
end
270

271
function rand(rng::AbstractRNG, sp::SamplerRangeFast{UInt128,T}) where T
64✔
272
    a, bw, m, mask = sp.a, sp.bw, sp.m, sp.mask
64✔
273
    if has_fast_64(rng)
64✔
274
        x = bw <= 64 ?
55✔
275
            rand(rng, LessThan(m % UInt64, Masked(mask % UInt64, uniform(UInt64)))) % UInt128 :
276
            rand(rng, LessThan(m, Masked(mask, uniform(UInt128))))
277
    else
278
        x = bw <= 52  ?
16✔
279
            rand(rng, LessThan(m % UInt64, Masked(mask % UInt64, UInt52Raw()))) % UInt128 :
280
        bw <= 104 ?
281
            rand(rng, LessThan(m, Masked(mask, UInt104Raw()))) :
282
            rand(rng, LessThan(m, Masked(mask, uniform(UInt128))))
283
    end
284
    x % T + a
64✔
285
end
286

287
#### "Slow" / SamplerRangeInt
288

289
# remainder function according to Knuth, where rem_knuth(a, 0) = a
290
rem_knuth(a::UInt, b::UInt) = a % (b + (b == 0)) + a * (b == 0)
9✔
291
rem_knuth(a::T, b::T) where {T<:Unsigned} = b != 0 ? a % b : a
66✔
292

293
# maximum multiple of k <= sup decremented by one,
294
# that is 0xFFFF...FFFF if k = (typemax(T) - typemin(T)) + 1 and sup == typemax(T) - 1
295
# with intentional underflow
296
# see http://stackoverflow.com/questions/29182036/integer-arithmetic-add-1-to-uint-max-and-divide-by-n-without-overflow
297

298
# sup == 0 means typemax(T) + 1
299
maxmultiple(k::T, sup::T=zero(T)) where {T<:Unsigned} =
1,670✔
300
    (div(sup - k, k + (k == 0))*k + k - one(k))::T
301

302
# similar but sup must not be equal to typemax(T)
303
unsafe_maxmultiple(k::T, sup::T) where {T<:Unsigned} =
118✔
304
    div(sup, k + (k == 0))*k - one(k)
305

306
struct SamplerRangeInt{T<:Integer,U<:Unsigned} <: Sampler{T}
307
    a::T      # first element of the range
185✔
308
    bw::Int   # bit width
309
    k::U      # range length or zero for full range
310
    u::U      # rejection threshold
311
end
312

313

314
SamplerRangeInt(r::AbstractUnitRange{T}) where T<:BitInteger =
185✔
315
    SamplerRangeInt(r, uint_sup(T))
316

317
function SamplerRangeInt(r::AbstractUnitRange{T}, ::Type{U}) where {T,U}
185✔
318
    isempty(r) && throw(ArgumentError("collection must be non-empty"))
185✔
319
    a = first(r)
185✔
320
    m = (last(r) - first(r)) % unsigned(T) % U
185✔
321
    k = m + one(U)
185✔
322
    bw = (Base.top_set_bit(m)) % Int
185✔
323
    mult = if U === UInt32
185✔
324
        maxmultiple(k)
36✔
325
    elseif U === UInt64
149✔
326
        bw <= 52 ? unsafe_maxmultiple(k, one(UInt64) << 52) :
156✔
327
                   maxmultiple(k)
328
    else # U === UInt128
329
        bw <= 52  ? unsafe_maxmultiple(k, one(UInt128) << 52) :
24✔
330
        bw <= 104 ? unsafe_maxmultiple(k, one(UInt128) << 104) :
331
                    maxmultiple(k)
332
    end
333

334
    SamplerRangeInt{T,U}(a, bw, k, mult) # overflow ok
185✔
335
end
336

337
rand(rng::AbstractRNG, sp::SamplerRangeInt{T,UInt32}) where {T<:BitInteger} =
36✔
338
    (unsigned(sp.a) + rem_knuth(rand(rng, LessThan(sp.u, UInt52Raw(UInt32))), sp.k)) % T
339

340
# this function uses 52 bit entropy for small ranges of length <= 2^52
341
function rand(rng::AbstractRNG, sp::SamplerRangeInt{T,UInt64}) where T<:BitInteger
9✔
342
    x = sp.bw <= 52 ? rand(rng, LessThan(sp.u, UInt52())) :
10✔
343
                      rand(rng, LessThan(sp.u, uniform(UInt64)))
344
    return ((sp.a % UInt64) + rem_knuth(x, sp.k)) % T
9✔
345
end
346

347
function rand(rng::AbstractRNG, sp::SamplerRangeInt{T,UInt128}) where T<:BitInteger
18✔
348
    x = sp.bw <= 52  ? rand(rng, LessThan(sp.u, UInt52(UInt128))) :
20✔
349
        sp.bw <= 104 ? rand(rng, LessThan(sp.u, UInt104(UInt128))) :
350
                       rand(rng, LessThan(sp.u, uniform(UInt128)))
351
    return ((sp.a % UInt128) + rem_knuth(x, sp.k)) % T
18✔
352
end
353

354
#### Nearly Division Less
355

356
# cf. https://arxiv.org/abs/1805.10941 (algorithm 5)
357

358
struct SamplerRangeNDL{U<:Unsigned,T} <: Sampler{T}
359
    a::T  # first element of the range
3,984,584✔
360
    s::U  # range length or zero for full range
361
end
362

363
function SamplerRangeNDL(r::AbstractUnitRange{T}) where {T}
3,984,632✔
364
    isempty(r) && throw(ArgumentError("collection must be non-empty"))
3,984,635✔
365
    a = first(r)
3,984,584✔
366
    U = uint_sup(T)
3,984,581✔
367
    s = (last(r) - first(r)) % unsigned(T) % U + one(U) # overflow ok
3,984,584✔
368
    # mod(-s, s) could be put in the Sampler object for repeated calls, but
369
    # this would be an advantage only for very big s and number of calls
370
    SamplerRangeNDL(a, s)
3,984,584✔
371
end
372

373
function rand(rng::AbstractRNG, sp::SamplerRangeNDL{U,T}) where {U,T}
8,277,940✔
374
    s = sp.s
8,277,940✔
375
    x = widen(rand(rng, U))
8,277,940✔
376
    m = x * s
8,277,940✔
377
    l = m % U
8,277,940✔
378
    if l < s
8,277,940✔
379
        t = mod(-s, s) # as s is unsigned, -s is equal to 2^L - s in the paper
88✔
380
        while l < t
109✔
381
            x = widen(rand(rng, U))
21✔
382
            m = x * s
21✔
383
            l = m % U
21✔
384
        end
21✔
385
    end
386
    (s == 0 ? x : m >> (8*sizeof(U))) % T + sp.a
8,277,940✔
387
end
388

389

390
### BigInt
391

392
struct SamplerBigInt{SP<:Sampler{Limb}} <: Sampler{BigInt}
393
    a::BigInt         # first
72✔
394
    m::BigInt         # range length - 1
395
    nlimbs::Int       # number of limbs in generated BigInt's (z ∈ [0, m])
396
    nlimbsmax::Int    # max number of limbs for z+a
397
    highsp::SP        # sampler for the highest limb of z
398
end
399

400
function SamplerBigInt(::Type{RNG}, r::AbstractUnitRange{BigInt}, N::Repetition=Val(Inf)
73✔
401
                       ) where {RNG<:AbstractRNG}
402
    m = last(r) - first(r)
73✔
403
    m.size < 0 && throw(ArgumentError("collection must be non-empty"))
72✔
404
    nlimbs = Int(m.size)
72✔
405
    hm = nlimbs == 0 ? Limb(0) : GC.@preserve m unsafe_load(m.d, nlimbs)
141✔
406
    highsp = Sampler(RNG, Limb(0):hm, N)
72✔
407
    nlimbsmax = max(nlimbs, abs(last(r).size), abs(first(r).size))
72✔
408
    return SamplerBigInt(first(r), m, nlimbs, nlimbsmax, highsp)
72✔
409
end
410

411
Sampler(::Type{RNG}, r::AbstractUnitRange{BigInt}, N::Repetition) where {RNG<:AbstractRNG} =
71✔
412
    SamplerBigInt(RNG, r, N)
413

414
rand(rng::AbstractRNG, sp::SamplerBigInt) =
8,071✔
415
    rand!(rng, BigInt(nbits = sp.nlimbsmax*8*sizeof(Limb)), sp)
416

417
function rand!(rng::AbstractRNG, x::BigInt, sp::SamplerBigInt)
8,078✔
418
    nlimbs = sp.nlimbs
8,078✔
419
    nlimbs == 0 && return MPZ.set!(x, sp.a)
8,078✔
420
    MPZ.realloc2!(x, sp.nlimbsmax*8*sizeof(Limb))
8,072✔
421
    @assert x.alloc >= nlimbs
8,072✔
422
    # we randomize x ∈ [0, m] with rejection sampling:
423
    # 1. the first nlimbs-1 limbs of x are uniformly randomized
424
    # 2. the high limb hx of x is sampled from 0:hm where hm is the
425
    #    high limb of m
426
    # We repeat 1. and 2. until x <= m
427
    hm = GC.@preserve sp unsafe_load(sp.m.d, nlimbs)
8,072✔
428
    GC.@preserve x begin
8,072✔
429
        limbs = UnsafeView(x.d, nlimbs-1)
8,072✔
430
        while true
8,072✔
431
            rand!(rng, limbs)
8,072✔
432
            hx = limbs[nlimbs] = rand(rng, sp.highsp)
8,072✔
433
            hx < hm && break # avoid calling mpn_cmp most of the time
8,072✔
434
            MPZ.mpn_cmp(x, sp.m, nlimbs) <= 0 && break
5✔
435
        end
×
436
        # adjust x.size (normally done by mpz_limbs_finish, in GMP version >= 6)
437
        while nlimbs > 0
8,075✔
438
            limbs[nlimbs] != 0 && break
8,072✔
439
            nlimbs -= 1
3✔
440
        end
3✔
441
        x.size = nlimbs
8,072✔
442
    end
443
    MPZ.add!(x, sp.a)
8,072✔
444
end
445

446

447
## random values from AbstractArray
448

449
Sampler(::Type{RNG}, r::AbstractArray, n::Repetition) where {RNG<:AbstractRNG} =
1,209,006✔
450
    SamplerSimple(r, Sampler(RNG, firstindex(r):lastindex(r), n))
451

452
rand(rng::AbstractRNG, sp::SamplerSimple{<:AbstractArray,<:Sampler}) =
1,978,048✔
453
    @inbounds return sp[][rand(rng, sp.data)]
454

455

456
## random values from Dict
457

458
function Sampler(::Type{RNG}, t::Dict, ::Repetition) where RNG<:AbstractRNG
1,438✔
459
    isempty(t) && throw(ArgumentError("collection must be non-empty"))
1,438✔
460
    # we use Val(Inf) below as rand is called repeatedly internally
461
    # even for generating only one random value from t
462
    SamplerSimple(t, Sampler(RNG, LinearIndices(t.slots), Val(Inf)))
1,422✔
463
end
464

465
function rand(rng::AbstractRNG, sp::SamplerSimple{<:Dict,<:Sampler})
3,768✔
466
    while true
11,270✔
467
        i = rand(rng, sp.data)
11,270✔
468
        Base.isslotfilled(sp[], i) && @inbounds return (sp[].keys[i] => sp[].vals[i])
11,270✔
469
    end
7,502✔
470
end
471

472
rand(rng::AbstractRNG, sp::SamplerTrivial{<:Base.KeySet{<:Any,<:Dict}}) =
886✔
473
    rand(rng, sp[].dict).first
474

475
rand(rng::AbstractRNG, sp::SamplerTrivial{<:Base.ValueIterator{<:Dict}}) =
228✔
476
    rand(rng, sp[].dict).second
477

478
## random values from Set
479

480
Sampler(::Type{RNG}, t::Set{T}, n::Repetition) where {RNG<:AbstractRNG,T} =
58✔
481
    SamplerTag{Set{T}}(Sampler(RNG, t.dict, n))
482

483
rand(rng::AbstractRNG, sp::SamplerTag{<:Set,<:Sampler}) = rand(rng, sp.data).first
582✔
484

485
## random values from BitSet
486

487
function Sampler(RNG::Type{<:AbstractRNG}, t::BitSet, n::Repetition)
54✔
488
    isempty(t) && throw(ArgumentError("collection must be non-empty"))
54✔
489
    SamplerSimple(t, Sampler(RNG, minimum(t):maximum(t), Val(Inf)))
46✔
490
end
491

492
function rand(rng::AbstractRNG, sp::SamplerSimple{BitSet,<:Sampler})
230✔
493
    while true
1,253✔
494
        n = rand(rng, sp.data)
1,253✔
495
        n in sp[] && return n
1,253✔
496
    end
1,023✔
497
end
498

499
## random values from AbstractDict/AbstractSet
500

501
# we defer to _Sampler to avoid ambiguities with a call like Sampler(rng, Set(1), Val(1))
502
Sampler(RNG::Type{<:AbstractRNG}, t::Union{AbstractDict,AbstractSet}, n::Repetition) =
1,038✔
503
    _Sampler(RNG, t, n)
504

505
# avoid linear complexity for repeated calls
506
_Sampler(RNG::Type{<:AbstractRNG}, t::Union{AbstractDict,AbstractSet}, n::Val{Inf}) =
136✔
507
    Sampler(RNG, collect(t), n)
508

509
# when generating only one element, avoid the call to collect
510
_Sampler(::Type{<:AbstractRNG}, t::Union{AbstractDict,AbstractSet}, ::Val{1}) =
902✔
511
    SamplerTrivial(t)
512

513
function nth(iter, n::Integer)::eltype(iter)
8✔
514
    for (i, x) in enumerate(iter)
16✔
515
        i == n && return x
48✔
516
    end
40✔
517
end
518

519
rand(rng::AbstractRNG, sp::SamplerTrivial{<:Union{AbstractDict,AbstractSet}}) =
16✔
520
    nth(sp[], rand(rng, 1:length(sp[])))
521

522

523
## random characters from a string
524

525
# we use collect(str), which is most of the time more efficient than specialized methods
526
# (except maybe for very small arrays)
527
Sampler(RNG::Type{<:AbstractRNG}, str::AbstractString, n::Val{Inf}) = Sampler(RNG, collect(str), n)
1,196✔
528

529
# when generating only one char from a string, the specialized method below
530
# is usually more efficient
531
Sampler(RNG::Type{<:AbstractRNG}, str::AbstractString, ::Val{1}) =
24✔
532
    SamplerSimple(str, Sampler(RNG, 1:_lastindex(str), Val(Inf)))
533

534
isvalid_unsafe(s::String, i) = !Base.is_valid_continuation(GC.@preserve s unsafe_load(pointer(s), i))
6✔
535
isvalid_unsafe(s::AbstractString, i) = isvalid(s, i)
4✔
536
_lastindex(s::String) = sizeof(s)
8✔
537
_lastindex(s::AbstractString) = lastindex(s)
8✔
538

539
function rand(rng::AbstractRNG, sp::SamplerSimple{<:AbstractString,<:Sampler})::Char
8✔
540
    str = sp[]
8✔
541
    while true
10✔
542
        pos = rand(rng, sp.data)
10✔
543
        isvalid_unsafe(str, pos) && return str[pos]
10✔
544
    end
2✔
545
end
546

547

548
## random elements from tuples
549

550
### 1
551

552
Sampler(::Type{<:AbstractRNG}, t::Tuple{A}, ::Repetition) where {A} =
2✔
553
    SamplerTrivial(t)
554

555
rand(rng::AbstractRNG, sp::SamplerTrivial{Tuple{A}}) where {A} =
2✔
556
    @inbounds return sp[][1]
557

558
### 2
559

560
Sampler(RNG::Type{<:AbstractRNG}, t::Tuple{A,B}, n::Repetition) where {A,B} =
14✔
561
    SamplerSimple(t, Sampler(RNG, Bool, n))
562

563
rand(rng::AbstractRNG, sp::SamplerSimple{Tuple{A,B}}) where {A,B} =
242✔
564
    @inbounds return sp[][1 + rand(rng, sp.data)]
565

566
### 3
567

568
Sampler(RNG::Type{<:AbstractRNG}, t::Tuple{A,B,C}, n::Repetition) where {A,B,C} =
2✔
569
    SamplerSimple(t, Sampler(RNG, UInt52(), n))
570

571
function rand(rng::AbstractRNG, sp::SamplerSimple{Tuple{A,B,C}}) where {A,B,C}
2✔
572
    local r
2✔
573
    while true
2✔
574
        r = rand(rng, sp.data)
2✔
575
        r != 0x000fffffffffffff && break # _very_ likely
2✔
576
    end
×
577
    @inbounds return sp[][1 + r ÷ 0x0005555555555555]
2✔
578
end
579

580
### n
581

582
@generated function Sampler(RNG::Type{<:AbstractRNG}, t::Tuple, n::Repetition)
4,012✔
583
    l = fieldcount(t)
14✔
584
    if l < typemax(UInt32) && ispow2(l)
14✔
585
        :(SamplerSimple(t, Sampler(RNG, UInt32, n)))
8✔
586
    else
587
        :(SamplerSimple(t, Sampler(RNG, Base.OneTo(length(t)), n)))
14✔
588
    end
589
end
590

591
@generated function rand(rng::AbstractRNG, sp::SamplerSimple{T}) where T<:Tuple
2,010✔
592
    l = fieldcount(T)
11✔
593
    if l < typemax(UInt32) && ispow2(l)
11✔
594
        quote
5✔
595
            r = rand(rng, sp.data) & ($l-1)
2,002✔
596
            @inbounds return sp[][1 + r]
2,002✔
597
        end
598
    else
599
        :(@inbounds return sp[][rand(rng, sp.data)])
11✔
600
    end
601
end
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc