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

JuliaLang / julia / 1391

29 Dec 2025 07:41PM UTC coverage: 76.638% (+0.02%) from 76.621%
1391

push

buildkite

web-flow
🤖 Bump StyledStrings stdlib 9bb8ffd → a033d46 (#60503)

Co-authored-by: KristofferC <1282691+KristofferC@users.noreply.github.com>

62409 of 81433 relevant lines covered (76.64%)

22974996.93 hits per line

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

92.64
/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} =
305,835,893✔
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}}) =
46,005✔
26
    Float16(reinterpret(Float32,
27
                        (rand(r, UInt10(UInt32)) << 13)  | 0x3f800000) - 1)
28

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

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

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

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

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

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

79
function _rand!(rng::AbstractRNG, z::BigFloat, sp::SamplerBigFloat, ::CloseOpen01{BigFloat})
80
    randbool = _rand!(rng, z, sp)
76,747,920✔
81
    z.exp = 0
76,747,917✔
82
    randbool &&
76,747,917✔
83
        ccall((:mpfr_sub_d, Base.MPFR.libmpfr), Int32,
84
              (Ref{BigFloat}, Ref{BigFloat}, Cdouble, Base.MPFR.MPFRRoundingMode),
85
              z, z, 0.5, Base.MPFR.ROUNDING_MODE[])
86
    z
76,747,917✔
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, Base.MPFR.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}
76,747,929✔
100
      ) where {T<:FloatInterval{BigFloat}} =
101
          _rand!(rng, z, sp, T())
102

103
rand(rng::AbstractRNG, sp::SamplerBigFloat{T}) where {T<:FloatInterval{BigFloat}} =
76,747,917✔
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)
46,014✔
112
rand(r::AbstractRNG, ::SamplerTrivial{UInt23Raw{UInt32}}) = rand(r, UInt32)
71,313✔
113

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

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

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

128
rand(r::AbstractRNG, sp::SamplerTrivial{<:UniformBits{T}}) where {T} =
47,127✔
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} =
543,094✔
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}
594✔
166
    c = rand(r, 0x00000000:0x0010f7ff)
5,943✔
167
    (c < 0xd800) ? T(c) : T(c+0x800)
3,378✔
168
end
169

170
### random tuples
171

172
function Sampler(::Type{RNG}, ::Type{T}, n::Repetition) where {T<:Tuple, RNG<:AbstractRNG}
18✔
173
    tail_sp_ = Sampler(RNG, Tuple{Base.tail(fieldtypes(T))...}, n)
285✔
174
    SamplerTag{Ref{T}}((Sampler(RNG, fieldtype(T, 1), n), tail_sp_.data...))
267✔
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
5,215✔
180
        SamplerTag{Ref{Tuple{Vararg{T, N}}}}((Sampler(RNG, T, n),))
5,209✔
181
    else
182
        SamplerTag{Ref{Tuple{}}}(())
6✔
183
    end
184
end
185

186
function rand(rng::AbstractRNG, sp::SamplerTag{Ref{T}}) where T<:Tuple
5,251✔
187
    ntuple(i -> rand(rng, sp.data[min(i, length(sp.data))]), Val{fieldcount(T)}())::T
60,525✔
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)
117✔
194
    sp2 = A === B ? sp1 : Sampler(RNG, B, n)
117✔
195
    SamplerTag{Ref{Pair{A,B}}}(sp1 => sp2) # Ref so that the gentype is Pair{A, B}
117✔
196
                                           # in SamplerTag's constructor
197
end
198

199
rand(rng::AbstractRNG, sp::SamplerTag{<:Ref{<:Pair}}) =
1,104✔
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},
11,027,406✔
221
        ::Repetition) where {T<:Base.BitInteger64} = SamplerRangeNDL(r)
222

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

226
#### helper functions
227

228
uint_sup(::Type{<:Base.BitInteger32}) = UInt32
1,204,200✔
229
uint_sup(::Type{<:Union{Int64,UInt64}}) = UInt64
301,057✔
230
uint_sup(::Type{<:Union{Int128,UInt128}}) = UInt128
264✔
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
372✔
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 =
372✔
245
    SamplerRangeFast(r, uint_sup(T))
246

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

255
function rand(rng::AbstractRNG, sp::SamplerRangeFast{UInt32,T}) where T
144✔
256
    a, bw, m, mask = sp.a, sp.bw, sp.m, sp.mask
144✔
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))))
177✔
259
    (x + a % UInt32) % T
144✔
260
end
261

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

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

275
function rand(rng::AbstractRNG, sp::SamplerRangeFast{UInt128,T}) where T
120✔
276
    a, bw, m, mask = sp.a, sp.bw, sp.m, sp.mask
210✔
277
    if has_fast_64(rng)
210✔
278
        x = bw <= 64 ?
191✔
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  ?
49✔
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
210✔
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)
36✔
295
rem_knuth(a::T, b::T) where {T<:Unsigned} = b != 0 ? a % b : a
216✔
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} =
5,100✔
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} =
372✔
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
618✔
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 =
684✔
319
    SamplerRangeInt(r, uint_sup(T))
320

321
function SamplerRangeInt(r::AbstractUnitRange{T}, ::Type{U}) where {T,U}
322
    isempty(r) && empty_collection_error()
618✔
323
    a = first(r)
618✔
324
    m = (last(r) - first(r)) % unsigned(T) % U
618✔
325
    k = m + one(U)
618✔
326
    bw = (Base.top_set_bit(m)) % Int
618✔
327
    mult = if U === UInt32
618✔
328
        maxmultiple(k)
144✔
329
    elseif U === UInt64
474✔
330
        bw <= 52 ? unsafe_maxmultiple(k, one(UInt64) << 52) :
480✔
331
                   maxmultiple(k)
332
    else # U === UInt128
333
        bw <= 52  ? unsafe_maxmultiple(k, one(UInt128) << 52) :
96✔
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
618✔
339
end
340

341
rand(rng::AbstractRNG, sp::SamplerRangeInt{T,UInt32}) where {T<:BitInteger} =
144✔
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
36✔
346
    x = sp.bw <= 52 ? rand(rng, LessThan(sp.u, UInt52())) :
39✔
347
                      rand(rng, LessThan(sp.u, uniform(UInt64)))
348
    return ((sp.a % UInt64) + rem_knuth(x, sp.k)) % T
36✔
349
end
350

351
function rand(rng::AbstractRNG, sp::SamplerRangeInt{T,UInt128}) where T<:BitInteger
72✔
352
    x = sp.bw <= 52  ? rand(rng, LessThan(sp.u, UInt52(UInt128))) :
78✔
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
72✔
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
1,556,350✔
364
    s::U  # range length or zero for full range
365
end
366

367
function SamplerRangeNDL(r::AbstractUnitRange{T}) where {T}
514✔
368
    isempty(r) && empty_collection_error()
5,426,513✔
369
    a = first(r)
1,856,648✔
370
    U = uint_sup(T)
1,812,847✔
371
    s = (last(r) - first(r)) % unsigned(T) % U + one(U) # overflow ok
5,426,321✔
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)
1,864,405✔
375
end
376

377
function rand(rng::AbstractRNG, sp::SamplerRangeNDL{U,T}) where {U,T}
204✔
378
    s = sp.s
26,892,757✔
379
    x = widen(rand(rng, U))
27,027,682✔
380
    m = x * s
26,932,320✔
381
    r::T = (m % U) < s ? rand_unlikely(rng, s, m) % T :
53,864,315✔
382
           iszero(s)   ? x % T :
383
                         (m >> (8*sizeof(U))) % T
384
    r + sp.a
26,932,320✔
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}
255✔
389
    t = mod(-s, s) # as s is unsigned, -s is equal to 2^L - s in the paper
255✔
390
    while (m % U) < t
310✔
391
        x = widen(rand(rng, U))
55✔
392
        m = x * s
55✔
393
    end
55✔
394
    (m >> (8*sizeof(U))) % U
255✔
395
end
396

397

398
### BigInt
399

400
struct SamplerBigInt{SP<:Sampler{Limb}} <: Sampler{BigInt}
401
    a::BigInt         # first
216✔
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)
3✔
409
                       ) where {RNG<:AbstractRNG}
410
    m = last(r) - first(r)
219✔
411
    m.size < 0 && empty_collection_error()
216✔
412
    nlimbs = Int(m.size)
216✔
413
    hm = nlimbs == 0 ? Limb(0) : GC.@preserve m unsafe_load(m.d, nlimbs)
423✔
414
    highsp = Sampler(RNG, Limb(0):hm, N)
216✔
415
    nlimbsmax = max(nlimbs, abs(last(r).size), abs(first(r).size))
216✔
416
    return SamplerBigInt(first(r), m, nlimbs, nlimbsmax, highsp)
216✔
417
end
418

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

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

425
function rand!(rng::AbstractRNG, x::BigInt, sp::SamplerBigInt)
24,234✔
426
    nlimbs = sp.nlimbs
24,234✔
427
    nlimbs == 0 && return MPZ.set!(x, sp.a)
24,234✔
428
    MPZ.realloc2!(x, sp.nlimbsmax*8*sizeof(Limb))
24,216✔
429
    @assert x.alloc >= nlimbs
24,216✔
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)
24,216✔
436
    GC.@preserve x begin
24,216✔
437
        limbs = UnsafeView(x.d, nlimbs-1)
24,216✔
438
        while true
24,216✔
439
            rand!(rng, limbs)
24,216✔
440
            hx = limbs[nlimbs] = rand(rng, sp.highsp)
48,429✔
441
            hx < hm && break # avoid calling mpn_cmp most of the time
24,216✔
442
            MPZ.mpn_cmp(x, sp.m, nlimbs) <= 0 && break
9✔
443
        end
×
444
        # adjust x.size (normally done by mpz_limbs_finish, in GMP version >= 6)
445
        while nlimbs > 0
24,227✔
446
            limbs[nlimbs] != 0 && break
24,218✔
447
            nlimbs -= 1
11✔
448
        end
11✔
449
        x.size = nlimbs
24,216✔
450
    end
451
    MPZ.add!(x, sp.a)
24,216✔
452
end
453

454

455
## random values from AbstractArray
456

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

460
rand(rng::AbstractRNG, sp::SamplerSimple{<:AbstractArray,<:Sampler}) =
5,978,755✔
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()
6,607✔
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)))
6,547✔
471
end
472

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

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

483
rand(rng::AbstractRNG, sp::SamplerTrivial{<:Base.ValueIterator{<:Dict}}) =
2,790✔
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} =
256✔
489
    SamplerTag{Set{T}}(Sampler(RNG, t.dict, n))
490

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

493
## random values from BitSet
494

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

500
function rand(rng::AbstractRNG, sp::SamplerSimple{BitSet,<:Sampler})
2,242✔
501
    while true
13,570✔
502
        n = rand(rng, sp.data)
27,140✔
503
        n in sp[] && return n
13,570✔
504
    end
10,776✔
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) =
3,066✔
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}) =
570✔
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}) =
2,496✔
519
    SamplerTrivial(t)
520

521
function nth(iter, n::Integer)::eltype(iter)
1,890✔
522
    for (i, x) in enumerate(iter)
3,780✔
523
        i == n && return x
15,159✔
524
    end
13,269✔
525
end
526

527
rand(rng::AbstractRNG, sp::SamplerTrivial{<:Union{AbstractDict,AbstractSet}}) =
1,920✔
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)
3,702✔
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}) =
90✔
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))
1,299✔
543
isvalid_unsafe(s::AbstractString, i) = isvalid(s, i)
1,102✔
544
_lastindex(s::String) = sizeof(s)
45✔
545
_lastindex(s::AbstractString) = lastindex(s)
45✔
546

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

555

556
## random elements from tuples
557

558
### 1
559

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

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

566
### 2
567

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

571
rand(rng::AbstractRNG, sp::SamplerSimple{Tuple{A,B}}) where {A,B} =
666✔
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} =
6✔
577
    SamplerSimple(t, Sampler(RNG, UInt52(), n))
578

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

588
### n
589

590
@generated function Sampler(RNG::Type{<:AbstractRNG}, t::Tuple, n::Repetition)
12,036✔
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
6,030✔
600
    l = fieldcount(T)
601
    if l < typemax(UInt32) && ispow2(l)
602
        quote
603
            r = rand(rng, sp.data) & ($l-1)
6,006✔
604
            @inbounds return sp[][1 + r]
6,006✔
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