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

JuliaLang / julia / #38162

06 Aug 2025 08:25PM UTC coverage: 25.688% (-43.6%) from 69.336%
#38162

push

local

web-flow
fix runtime cglobal builtin function implementation (#59210)

This had failed to be updated for the LazyLibrary changes to codegen.

12976 of 50513 relevant lines covered (25.69%)

676965.51 hits per line

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

7.35
/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} =
×
20
    Sampler(RNG, CloseOpen01(T), n)
21

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

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

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

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

35
rand(r::AbstractRNG, ::SamplerTrivial{CloseOpen01_64}) = rand(r, CloseOpen12()) - 1.0
×
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}
×
49
        nlimbs = (prec-1) ÷ bits_in_Limb + 1
×
50
        limbs = Vector{Limb}(undef, nlimbs)
×
51
        shift = nlimbs * bits_in_Limb - prec
×
52
        new(prec, nlimbs, limbs, shift)
×
53
    end
54
end
55

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

59
function _rand!(rng::AbstractRNG, z::BigFloat, sp::SamplerBigFloat)
×
60
    precision(z) == sp.prec || _throw_argerror("incompatible BigFloat precision")
×
61
    limbs = sp.limbs
×
62
    rand!(rng, limbs)
×
63
    @inbounds begin
×
64
        limbs[1] <<= sp.shift
×
65
        randbool = iszero(limbs[end] & Limb_high_bit)
×
66
        limbs[end] |= Limb_high_bit
×
67
    end
68
    z.sign = 1
×
69
    copyto!(z.d, limbs)
×
70
    randbool
×
71
end
72

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

79
function _rand!(rng::AbstractRNG, z::BigFloat, sp::SamplerBigFloat, ::CloseOpen01{BigFloat})
×
80
    randbool = _rand!(rng, z, sp)
×
81
    z.exp = 0
×
82
    randbool &&
×
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
×
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}} =
101
          _rand!(rng, z, sp, T())
102

103
rand(rng::AbstractRNG, sp::SamplerBigFloat{T}) where {T<:FloatInterval{BigFloat}} =
×
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)
×
112
rand(r::AbstractRNG, ::SamplerTrivial{UInt23Raw{UInt32}}) = rand(r, UInt32)
×
113

114
rand(r::AbstractRNG, ::SamplerTrivial{UInt52Raw{UInt64}}) =
×
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)
×
119

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

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

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

131
#### BitInteger
132

133
# rand_generic methods are intended to help RNG implementers 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} =
×
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}
×
166
    c = rand(r, 0x00000000:0x0010f7ff)
×
167
    (c < 0xd800) ? T(c) : T(c+0x800)
×
168
end
169

170
### random tuples
171

172
function Sampler(::Type{RNG}, ::Type{T}, n::Repetition) where {T<:Tuple, RNG<:AbstractRNG}
×
173
    tail_sp_ = Sampler(RNG, Tuple{Base.tail(fieldtypes(T))...}, n)
×
174
    SamplerTag{Ref{T}}((Sampler(RNG, fieldtype(T, 1), n), tail_sp_.data...))
×
175
    # Ref so that the gentype is `T` in SamplerTag's constructor
176
end
177

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

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

190
### random pairs
191

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

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

202

203
## Generate random integer within a range
204

205
### BitInteger
206

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

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

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

226
#### helper functions
227

228
uint_sup(::Type{<:Base.BitInteger32}) = UInt32
×
229
uint_sup(::Type{<:Union{Int64,UInt64}}) = UInt64
×
230
uint_sup(::Type{<:Union{Int128,UInt128}}) = UInt128
×
231

232
@noinline empty_collection_error() = throw(ArgumentError("collection must be non-empty"))
×
233

234

235
#### Fast
236

237
struct SamplerRangeFast{U<:BitUnsigned,T<:BitInteger} <: Sampler{T}
238
    a::T      # first element of the range
239
    bw::UInt  # bit width
240
    m::U      # range length - 1
241
    mask::U   # mask generated values before threshold rejection
242
end
243

244
SamplerRangeFast(r::AbstractUnitRange{T}) where T<:BitInteger =
×
245
    SamplerRangeFast(r, uint_sup(T))
246

247
function SamplerRangeFast(r::AbstractUnitRange{T}, ::Type{U}) where {T,U}
×
248
    isempty(r) && empty_collection_error()
×
249
    m = (last(r) - first(r)) % unsigned(T) % U # % unsigned(T) to not propagate sign bit
×
250
    bw = (Base.top_set_bit(m)) % UInt # bit-width
×
251
    mask = ((1 % U) << bw) - (1 % U)
×
252
    SamplerRangeFast{U,T}(first(r), bw, m, mask)
×
253
end
254

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

262
has_fast_64(rng::AbstractRNG) = rng_native_52(rng) != Float64
×
263
# for MersenneTwister, both options have very similar performance
264

265
function rand(rng::AbstractRNG, sp::SamplerRangeFast{UInt64,T}) where T
×
266
    a, bw, m, mask = sp.a, sp.bw, sp.m, sp.mask
×
267
    if !has_fast_64(rng) && bw <= 52
×
268
        x = rand(rng, LessThan(m, Masked(mask, UInt52Raw())))
×
269
    else
270
        x = rand(rng, LessThan(m, Masked(mask, uniform(UInt64))))
×
271
    end
272
    (x + a % UInt64) % T
×
273
end
274

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

291
#### "Slow" / SamplerRangeInt
292

293
# remainder function according to Knuth, where rem_knuth(a, 0) = a
294
rem_knuth(a::UInt, b::UInt) = a % (b + (b == 0)) + a * (b == 0)
×
295
rem_knuth(a::T, b::T) where {T<:Unsigned} = b != 0 ? a % b : a
×
296

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

302
# sup == 0 means typemax(T) + 1
303
maxmultiple(k::T, sup::T=zero(T)) where {T<:Unsigned} =
×
304
    (div(sup - k, k + (k == 0))*k + k - one(k))::T
305

306
# similar but sup must not be equal to typemax(T)
307
unsafe_maxmultiple(k::T, sup::T) where {T<:Unsigned} =
×
308
    div(sup, k + (k == 0))*k - one(k)
309

310
struct SamplerRangeInt{T<:Integer,U<:Unsigned} <: Sampler{T}
311
    a::T      # first element of the range
312
    bw::Int   # bit width
313
    k::U      # range length or zero for full range
314
    u::U      # rejection threshold
315
end
316

317

318
SamplerRangeInt(r::AbstractUnitRange{T}) where T<:BitInteger =
×
319
    SamplerRangeInt(r, uint_sup(T))
320

321
function SamplerRangeInt(r::AbstractUnitRange{T}, ::Type{U}) where {T,U}
×
322
    isempty(r) && empty_collection_error()
×
323
    a = first(r)
×
324
    m = (last(r) - first(r)) % unsigned(T) % U
×
325
    k = m + one(U)
×
326
    bw = (Base.top_set_bit(m)) % Int
×
327
    mult = if U === UInt32
×
328
        maxmultiple(k)
×
329
    elseif U === UInt64
×
330
        bw <= 52 ? unsafe_maxmultiple(k, one(UInt64) << 52) :
×
331
                   maxmultiple(k)
332
    else # U === UInt128
333
        bw <= 52  ? unsafe_maxmultiple(k, one(UInt128) << 52) :
×
334
        bw <= 104 ? unsafe_maxmultiple(k, one(UInt128) << 104) :
335
                    maxmultiple(k)
336
    end
337

338
    SamplerRangeInt{T,U}(a, bw, k, mult) # overflow ok
×
339
end
340

341
rand(rng::AbstractRNG, sp::SamplerRangeInt{T,UInt32}) where {T<:BitInteger} =
×
342
    (unsigned(sp.a) + rem_knuth(rand(rng, LessThan(sp.u, UInt52Raw(UInt32))), sp.k)) % T
343

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

351
function rand(rng::AbstractRNG, sp::SamplerRangeInt{T,UInt128}) where T<:BitInteger
×
352
    x = sp.bw <= 52  ? rand(rng, LessThan(sp.u, UInt52(UInt128))) :
×
353
        sp.bw <= 104 ? rand(rng, LessThan(sp.u, UInt104(UInt128))) :
354
                       rand(rng, LessThan(sp.u, uniform(UInt128)))
355
    return ((sp.a % UInt128) + rem_knuth(x, sp.k)) % T
×
356
end
357

358
#### Nearly Division Less
359

360
# cf. https://arxiv.org/abs/1805.10941 (algorithm 5)
361

362
struct SamplerRangeNDL{U<:Unsigned,T} <: Sampler{T}
363
    a::T  # first element of the range
87✔
364
    s::U  # range length or zero for full range
365
end
366

367
function SamplerRangeNDL(r::AbstractUnitRange{T}) where {T}
2✔
368
    isempty(r) && empty_collection_error()
87✔
369
    a = first(r)
2✔
370
    U = uint_sup(T)
×
371
    s = (last(r) - first(r)) % unsigned(T) % U + one(U) # overflow ok
87✔
372
    # mod(-s, s) could be put in the Sampler object for repeated calls, but
373
    # this would be an advantage only for very big s and number of calls
374
    SamplerRangeNDL(a, s)
87✔
375
end
376

377
function rand(rng::AbstractRNG, sp::SamplerRangeNDL{U,T}) where {U,T}
378
    s = sp.s
18✔
379
    x = widen(rand(rng, U))
18✔
380
    m = x * s
18✔
381
    r::T = (m % U) < s ? rand_unlikely(rng, s, m) % T :
36✔
382
           iszero(s)   ? x % T :
383
                         (m >> (8*sizeof(U))) % T
384
    r + sp.a
18✔
385
end
386

387
# similar to `randn_unlikely` : splitting this unlikely path out results in faster code
388
@noinline function rand_unlikely(rng, s::U, m)::U where {U}
×
389
    t = mod(-s, s) # as s is unsigned, -s is equal to 2^L - s in the paper
×
390
    while (m % U) < t
×
391
        x = widen(rand(rng, U))
×
392
        m = x * s
×
393
    end
×
394
    (m >> (8*sizeof(U))) % U
×
395
end
396

397

398
### BigInt
399

400
struct SamplerBigInt{SP<:Sampler{Limb}} <: Sampler{BigInt}
401
    a::BigInt         # first
402
    m::BigInt         # range length - 1
403
    nlimbs::Int       # number of limbs in generated BigInt's (z ∈ [0, m])
404
    nlimbsmax::Int    # max number of limbs for z+a
405
    highsp::SP        # sampler for the highest limb of z
406
end
407

408
function SamplerBigInt(::Type{RNG}, r::AbstractUnitRange{BigInt}, N::Repetition=Val(Inf)
×
409
                       ) where {RNG<:AbstractRNG}
410
    m = last(r) - first(r)
×
411
    m.size < 0 && empty_collection_error()
×
412
    nlimbs = Int(m.size)
×
413
    hm = nlimbs == 0 ? Limb(0) : GC.@preserve m unsafe_load(m.d, nlimbs)
×
414
    highsp = Sampler(RNG, Limb(0):hm, N)
×
415
    nlimbsmax = max(nlimbs, abs(last(r).size), abs(first(r).size))
×
416
    return SamplerBigInt(first(r), m, nlimbs, nlimbsmax, highsp)
×
417
end
418

419
Sampler(::Type{RNG}, r::AbstractUnitRange{BigInt}, N::Repetition) where {RNG<:AbstractRNG} =
×
420
    SamplerBigInt(RNG, r, N)
421

422
rand(rng::AbstractRNG, sp::SamplerBigInt) =
×
423
    rand!(rng, BigInt(nbits = sp.nlimbsmax*8*sizeof(Limb)), sp)
424

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

454

455
## random values from AbstractArray
456

457
Sampler(::Type{RNG}, r::AbstractArray, n::Repetition) where {RNG<:AbstractRNG} =
85✔
458
    SamplerSimple(r, Sampler(RNG, firstindex(r):lastindex(r), n))
459

460
rand(rng::AbstractRNG, sp::SamplerSimple{<:AbstractArray,<:Sampler}) =
16✔
461
    @inbounds return sp[][rand(rng, sp.data)]
462

463

464
## random values from Dict
465

466
function Sampler(::Type{RNG}, t::Dict, ::Repetition) where RNG<:AbstractRNG
×
467
    isempty(t) && empty_collection_error()
×
468
    # we use Val(Inf) below as rand is called repeatedly internally
469
    # even for generating only one random value from t
470
    SamplerSimple(t, Sampler(RNG, LinearIndices(t.slots), Val(Inf)))
×
471
end
472

473
function rand(rng::AbstractRNG, sp::SamplerSimple{<:Dict,<:Sampler})
×
474
    while true
×
475
        i = rand(rng, sp.data)
×
476
        Base.isslotfilled(sp[], i) && @inbounds return (sp[].keys[i] => sp[].vals[i])
×
477
    end
×
478
end
479

480
rand(rng::AbstractRNG, sp::SamplerTrivial{<:Base.KeySet{<:Any,<:Dict}}) =
×
481
    rand(rng, sp[].dict).first
482

483
rand(rng::AbstractRNG, sp::SamplerTrivial{<:Base.ValueIterator{<:Dict}}) =
×
484
    rand(rng, sp[].dict).second
485

486
## random values from Set
487

488
Sampler(::Type{RNG}, t::Set{T}, n::Repetition) where {RNG<:AbstractRNG,T} =
×
489
    SamplerTag{Set{T}}(Sampler(RNG, t.dict, n))
490

491
rand(rng::AbstractRNG, sp::SamplerTag{<:Set,<:Sampler}) = rand(rng, sp.data).first
×
492

493
## random values from BitSet
494

495
function Sampler(RNG::Type{<:AbstractRNG}, t::BitSet, n::Repetition)
×
496
    isempty(t) && empty_collection_error()
×
497
    SamplerSimple(t, Sampler(RNG, minimum(t):maximum(t), Val(Inf)))
×
498
end
499

500
function rand(rng::AbstractRNG, sp::SamplerSimple{BitSet,<:Sampler})
×
501
    while true
×
502
        n = rand(rng, sp.data)
×
503
        n in sp[] && return n
×
504
    end
×
505
end
506

507
## random values from AbstractDict/AbstractSet
508

509
# we defer to _Sampler to avoid ambiguities with a call like Sampler(rng, Set(1), Val(1))
510
Sampler(RNG::Type{<:AbstractRNG}, t::Union{AbstractDict,AbstractSet}, n::Repetition) =
×
511
    _Sampler(RNG, t, n)
512

513
# avoid linear complexity for repeated calls
514
_Sampler(RNG::Type{<:AbstractRNG}, t::Union{AbstractDict,AbstractSet}, n::Val{Inf}) =
×
515
    Sampler(RNG, collect(t), n)
516

517
# when generating only one element, avoid the call to collect
518
_Sampler(::Type{<:AbstractRNG}, t::Union{AbstractDict,AbstractSet}, ::Val{1}) =
×
519
    SamplerTrivial(t)
520

521
function nth(iter, n::Integer)::eltype(iter)
×
522
    for (i, x) in enumerate(iter)
×
523
        i == n && return x
×
524
    end
×
525
end
526

527
rand(rng::AbstractRNG, sp::SamplerTrivial{<:Union{AbstractDict,AbstractSet}}) =
×
528
    nth(sp[], rand(rng, 1:length(sp[])))
529

530

531
## random characters from a string
532

533
# we use collect(str), which is most of the time more efficient than specialized methods
534
# (except maybe for very small arrays)
535
Sampler(RNG::Type{<:AbstractRNG}, str::AbstractString, n::Val{Inf}) = Sampler(RNG, collect(str), n)
×
536

537
# when generating only one char from a string, the specialized method below
538
# is usually more efficient
539
Sampler(RNG::Type{<:AbstractRNG}, str::AbstractString, ::Val{1}) =
×
540
    SamplerSimple(str, Sampler(RNG, 1:_lastindex(str), Val(Inf)))
541

542
isvalid_unsafe(s::String, i) = !Base.is_valid_continuation(GC.@preserve s unsafe_load(pointer(s), i))
×
543
isvalid_unsafe(s::AbstractString, i) = isvalid(s, i)
×
544
_lastindex(s::String) = sizeof(s)
×
545
_lastindex(s::AbstractString) = lastindex(s)
×
546

547
function rand(rng::AbstractRNG, sp::SamplerSimple{<:AbstractString,<:Sampler})::Char
×
548
    str = sp[]
×
549
    while true
×
550
        pos = rand(rng, sp.data)
×
551
        isvalid_unsafe(str, pos) && return str[pos]
×
552
    end
×
553
end
554

555

556
## random elements from tuples
557

558
### 1
559

560
Sampler(::Type{<:AbstractRNG}, t::Tuple{A}, ::Repetition) where {A} =
×
561
    SamplerTrivial(t)
562

563
rand(rng::AbstractRNG, sp::SamplerTrivial{Tuple{A}}) where {A} =
×
564
    @inbounds return sp[][1]
×
565

566
### 2
567

568
Sampler(RNG::Type{<:AbstractRNG}, t::Tuple{A,B}, n::Repetition) where {A,B} =
×
569
    SamplerSimple(t, Sampler(RNG, Bool, n))
570

571
rand(rng::AbstractRNG, sp::SamplerSimple{Tuple{A,B}}) where {A,B} =
×
572
    @inbounds return sp[][1 + rand(rng, sp.data)]
×
573

574
### 3
575

576
Sampler(RNG::Type{<:AbstractRNG}, t::Tuple{A,B,C}, n::Repetition) where {A,B,C} =
×
577
    SamplerSimple(t, Sampler(RNG, UInt52(), n))
578

579
function rand(rng::AbstractRNG, sp::SamplerSimple{Tuple{A,B,C}}) where {A,B,C}
×
580
    local r
×
581
    while true
×
582
        r = rand(rng, sp.data)
×
583
        r != 0x000fffffffffffff && break # _very_ likely
×
584
    end
×
585
    @inbounds return sp[][1 + r ÷ 0x0005555555555555]
×
586
end
587

588
### n
589

590
@generated function Sampler(RNG::Type{<:AbstractRNG}, t::Tuple, n::Repetition)
×
591
    l = fieldcount(t)
×
592
    if l < typemax(UInt32) && ispow2(l)
×
593
        :(SamplerSimple(t, Sampler(RNG, UInt32, n)))
×
594
    else
595
        :(SamplerSimple(t, Sampler(RNG, Base.OneTo(length(t)), n)))
×
596
    end
597
end
598

599
@generated function rand(rng::AbstractRNG, sp::SamplerSimple{T}) where T<:Tuple
×
600
    l = fieldcount(T)
×
601
    if l < typemax(UInt32) && ispow2(l)
×
602
        quote
×
603
            r = rand(rng, sp.data) & ($l-1)
×
604
            @inbounds return sp[][1 + r]
×
605
        end
606
    else
607
        :(@inbounds return sp[][rand(rng, sp.data)])
×
608
    end
609
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