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

JuliaLang / julia / #37643

05 Oct 2023 03:14PM UTC coverage: 86.883% (+0.05%) from 86.835%
#37643

push

local

web-flow
Use a simple error when reporting sysimg load failures. (#51598)

`jl_errorexception_type` is undefined at the point we (fail to) load a
sysimg.

73424 of 84509 relevant lines covered (86.88%)

11771585.16 hits per line

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

92.08
/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,624,962✔
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,609✔
33
    reinterpret(Float64, 0x3ff0000000000000 | rand(r, UInt52()))
34

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

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

59
function _rand!(rng::AbstractRNG, z::BigFloat, sp::SamplerBigFloat)
13,554,347✔
60
    precision(z) == sp.prec || throw(ArgumentError("incompatible BigFloat precision"))
13,554,349✔
61
    limbs = sp.limbs
13,554,345✔
62
    rand!(rng, limbs)
13,554,345✔
63
    @inbounds begin
13,554,345✔
64
        limbs[1] <<= sp.shift
13,554,345✔
65
        randbool = iszero(limbs[end] & Limb_high_bit)
13,554,345✔
66
        limbs[end] |= Limb_high_bit
13,554,345✔
67
    end
68
    z.sign = 1
13,554,345✔
69
    GC.@preserve limbs unsafe_copyto!(z.d, pointer(limbs), sp.nlimbs)
13,554,345✔
70
    randbool
13,554,345✔
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,554,344✔
80
    randbool = _rand!(rng, z, sp)
13,554,344✔
81
    z.exp = 0
13,554,343✔
82
    randbool &&
13,554,343✔
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,554,343✔
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,554,347✔
101
          _rand!(rng, z, sp, T())
102

103
rand(rng::AbstractRNG, sp::SamplerBigFloat{T}) where {T<:FloatInterval{BigFloat}} =
13,554,343✔
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,365✔
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,365✔
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,255✔
126
rand(r::AbstractRNG, ::SamplerTrivial{UInt104{UInt128}}) = rand(r, UInt104Raw()) & 0x000000ffffffffffffffffffffffffff
×
127

128
rand(r::AbstractRNG, sp::SamplerTrivial{<:UniformBits{T}}) where {T} =
1,404,589✔
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} =
165,924✔
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}
488✔
166
    c = rand(r, 0x00000000:0x0010f7ff)
488✔
167
    (c < 0xd800) ? T(c) : T(c+0x800)
513✔
168
end
169

170
### random tuples
171

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

177
function Sampler(::Type{RNG}, ::Type{Tuple{Vararg{T, N}}}, n::Repetition) where {T, N, RNG<:AbstractRNG}
52✔
178
    SamplerTag{Tuple{Vararg{T, N}}}((Sampler(RNG, T, n),))
52✔
179
end
180

181
function rand(rng::AbstractRNG, sp::SamplerTag{T}) where T<:Tuple
256✔
182
    ntuple(i -> rand(rng, sp.data[min(i, length(sp.data))]), Val{fieldcount(T)}())::T
824✔
183
end
184

185
## Generate random integer within a range
186

187
### BitInteger
188

189
# there are three implemented samplers for unit ranges, the second one
190
# assumes that Float64 (i.e. 52 random bits) is the native type for the RNG:
191
# 1) "Fast" (SamplerRangeFast), which is most efficient when the range length is close
192
#    (or equal) to a power of 2 from below.
193
#    The tradeoff is faster creation of the sampler, but more consumption of entropy bits.
194
# 2) "Slow" (SamplerRangeInt) which tries to use as few entropy bits as possible, at the
195
#    cost of a bigger upfront price associated with the creation of the sampler.
196
#    This sampler is most appropriate for slower random generators.
197
# 3) "Nearly Division Less" (NDL) which is generally the fastest algorithm for types of size
198
#    up to 64 bits. This is the default for these types since Julia 1.5.
199
#    The "Fast" algorithm can be faster than NDL when the length of the range is
200
#    less than and close to a power of 2.
201

202
Sampler(::Type{<:AbstractRNG}, r::AbstractUnitRange{T},
×
203
        ::Repetition) where {T<:Base.BitInteger64} = SamplerRangeNDL(r)
3,958,539✔
204

205
Sampler(::Type{<:AbstractRNG}, r::AbstractUnitRange{T},
×
206
        ::Repetition) where {T<:Union{Int128,UInt128}} = SamplerRangeFast(r)
40✔
207

208
#### helper functions
209

210
uint_sup(::Type{<:Base.BitInteger32}) = UInt32
400,758✔
211
uint_sup(::Type{<:Union{Int64,UInt64}}) = UInt64
3,557,984✔
212
uint_sup(::Type{<:Union{Int128,UInt128}}) = UInt128
76✔
213

214
#### Fast
215

216
struct SamplerRangeFast{U<:BitUnsigned,T<:BitInteger} <: Sampler{T}
217
    a::T      # first element of the range
103✔
218
    bw::UInt  # bit width
219
    m::U      # range length - 1
220
    mask::U   # mask generated values before threshold rejection
221
end
222

223
SamplerRangeFast(r::AbstractUnitRange{T}) where T<:BitInteger =
103✔
224
    SamplerRangeFast(r, uint_sup(T))
225

226
function SamplerRangeFast(r::AbstractUnitRange{T}, ::Type{U}) where {T,U}
103✔
227
    isempty(r) && throw(ArgumentError("collection must be non-empty"))
103✔
228
    m = (last(r) - first(r)) % unsigned(T) % U # % unsigned(T) to not propagate sign bit
103✔
229
    bw = (Base.top_set_bit(m)) % UInt # bit-width
103✔
230
    mask = ((1 % U) << bw) - (1 % U)
103✔
231
    SamplerRangeFast{U,T}(first(r), bw, m, mask)
103✔
232
end
233

234
function rand(rng::AbstractRNG, sp::SamplerRangeFast{UInt32,T}) where T
36✔
235
    a, bw, m, mask = sp.a, sp.bw, sp.m, sp.mask
36✔
236
    # below, we don't use UInt32, to get reproducible values, whether Int is Int64 or Int32
237
    x = rand(rng, LessThan(m, Masked(mask, UInt52Raw(UInt32))))
40✔
238
    (x + a % UInt32) % T
36✔
239
end
240

241
has_fast_64(rng::AbstractRNG) = rng_native_52(rng) != Float64
73✔
242
# for MersenneTwister, both options have very similar performance
243

244
function rand(rng::AbstractRNG, sp::SamplerRangeFast{UInt64,T}) where T
9✔
245
    a, bw, m, mask = sp.a, sp.bw, sp.m, sp.mask
9✔
246
    if !has_fast_64(rng) && bw <= 52
9✔
247
        x = rand(rng, LessThan(m, Masked(mask, UInt52Raw())))
3✔
248
    else
249
        x = rand(rng, LessThan(m, Masked(mask, uniform(UInt64))))
7✔
250
    end
251
    (x + a % UInt64) % T
9✔
252
end
253

254
function rand(rng::AbstractRNG, sp::SamplerRangeFast{UInt128,T}) where T
64✔
255
    a, bw, m, mask = sp.a, sp.bw, sp.m, sp.mask
64✔
256
    if has_fast_64(rng)
64✔
257
        x = bw <= 64 ?
56✔
258
            rand(rng, LessThan(m % UInt64, Masked(mask % UInt64, uniform(UInt64)))) % UInt128 :
259
            rand(rng, LessThan(m, Masked(mask, uniform(UInt128))))
260
    else
261
        x = bw <= 52  ?
15✔
262
            rand(rng, LessThan(m % UInt64, Masked(mask % UInt64, UInt52Raw()))) % UInt128 :
263
        bw <= 104 ?
264
            rand(rng, LessThan(m, Masked(mask, UInt104Raw()))) :
265
            rand(rng, LessThan(m, Masked(mask, uniform(UInt128))))
266
    end
267
    x % T + a
64✔
268
end
269

270
#### "Slow" / SamplerRangeInt
271

272
# remainder function according to Knuth, where rem_knuth(a, 0) = a
273
rem_knuth(a::UInt, b::UInt) = a % (b + (b == 0)) + a * (b == 0)
9✔
274
rem_knuth(a::T, b::T) where {T<:Unsigned} = b != 0 ? a % b : a
66✔
275

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

281
# sup == 0 means typemax(T) + 1
282
maxmultiple(k::T, sup::T=zero(T)) where {T<:Unsigned} =
1,670✔
283
    (div(sup - k, k + (k == 0))*k + k - one(k))::T
284

285
# similar but sup must not be equal to typemax(T)
286
unsafe_maxmultiple(k::T, sup::T) where {T<:Unsigned} =
118✔
287
    div(sup, k + (k == 0))*k - one(k)
288

289
struct SamplerRangeInt{T<:Integer,U<:Unsigned} <: Sampler{T}
290
    a::T      # first element of the range
185✔
291
    bw::Int   # bit width
292
    k::U      # range length or zero for full range
293
    u::U      # rejection threshold
294
end
295

296

297
SamplerRangeInt(r::AbstractUnitRange{T}) where T<:BitInteger =
185✔
298
    SamplerRangeInt(r, uint_sup(T))
299

300
function SamplerRangeInt(r::AbstractUnitRange{T}, ::Type{U}) where {T,U}
185✔
301
    isempty(r) && throw(ArgumentError("collection must be non-empty"))
185✔
302
    a = first(r)
185✔
303
    m = (last(r) - first(r)) % unsigned(T) % U
185✔
304
    k = m + one(U)
185✔
305
    bw = (Base.top_set_bit(m)) % Int
185✔
306
    mult = if U === UInt32
185✔
307
        maxmultiple(k)
36✔
308
    elseif U === UInt64
149✔
309
        bw <= 52 ? unsafe_maxmultiple(k, one(UInt64) << 52) :
156✔
310
                   maxmultiple(k)
311
    else # U === UInt128
312
        bw <= 52  ? unsafe_maxmultiple(k, one(UInt128) << 52) :
24✔
313
        bw <= 104 ? unsafe_maxmultiple(k, one(UInt128) << 104) :
314
                    maxmultiple(k)
315
    end
316

317
    SamplerRangeInt{T,U}(a, bw, k, mult) # overflow ok
185✔
318
end
319

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

323
# this function uses 52 bit entropy for small ranges of length <= 2^52
324
function rand(rng::AbstractRNG, sp::SamplerRangeInt{T,UInt64}) where T<:BitInteger
9✔
325
    x = sp.bw <= 52 ? rand(rng, LessThan(sp.u, UInt52())) :
10✔
326
                      rand(rng, LessThan(sp.u, uniform(UInt64)))
327
    return ((sp.a % UInt64) + rem_knuth(x, sp.k)) % T
9✔
328
end
329

330
function rand(rng::AbstractRNG, sp::SamplerRangeInt{T,UInt128}) where T<:BitInteger
18✔
331
    x = sp.bw <= 52  ? rand(rng, LessThan(sp.u, UInt52(UInt128))) :
20✔
332
        sp.bw <= 104 ? rand(rng, LessThan(sp.u, UInt104(UInt128))) :
333
                       rand(rng, LessThan(sp.u, uniform(UInt128)))
334
    return ((sp.a % UInt128) + rem_knuth(x, sp.k)) % T
18✔
335
end
336

337
#### Nearly Division Less
338

339
# cf. https://arxiv.org/abs/1805.10941 (algorithm 5)
340

341
struct SamplerRangeNDL{U<:Unsigned,T} <: Sampler{T}
342
    a::T  # first element of the range
3,958,533✔
343
    s::U  # range length or zero for full range
344
end
345

346
function SamplerRangeNDL(r::AbstractUnitRange{T}) where {T}
3,958,581✔
347
    isempty(r) && throw(ArgumentError("collection must be non-empty"))
3,958,584✔
348
    a = first(r)
3,958,533✔
349
    U = uint_sup(T)
3,958,530✔
350
    s = (last(r) - first(r)) % unsigned(T) % U + one(U) # overflow ok
3,958,533✔
351
    # mod(-s, s) could be put in the Sampler object for repeated calls, but
352
    # this would be an advantage only for very big s and number of calls
353
    SamplerRangeNDL(a, s)
3,958,533✔
354
end
355

356
function rand(rng::AbstractRNG, sp::SamplerRangeNDL{U,T}) where {U,T}
8,152,610✔
357
    s = sp.s
8,152,610✔
358
    x = widen(rand(rng, U))
8,152,610✔
359
    m = x * s
8,152,610✔
360
    l = m % U
8,152,610✔
361
    if l < s
8,152,610✔
362
        t = mod(-s, s) # as s is unsigned, -s is equal to 2^L - s in the paper
87✔
363
        while l < t
104✔
364
            x = widen(rand(rng, U))
17✔
365
            m = x * s
17✔
366
            l = m % U
17✔
367
        end
17✔
368
    end
369
    (s == 0 ? x : m >> (8*sizeof(U))) % T + sp.a
8,152,610✔
370
end
371

372

373
### BigInt
374

375
struct SamplerBigInt{SP<:Sampler{Limb}} <: Sampler{BigInt}
376
    a::BigInt         # first
72✔
377
    m::BigInt         # range length - 1
378
    nlimbs::Int       # number of limbs in generated BigInt's (z ∈ [0, m])
379
    nlimbsmax::Int    # max number of limbs for z+a
380
    highsp::SP        # sampler for the highest limb of z
381
end
382

383
function SamplerBigInt(::Type{RNG}, r::AbstractUnitRange{BigInt}, N::Repetition=Val(Inf)
73✔
384
                       ) where {RNG<:AbstractRNG}
385
    m = last(r) - first(r)
73✔
386
    m.size < 0 && throw(ArgumentError("collection must be non-empty"))
72✔
387
    nlimbs = Int(m.size)
72✔
388
    hm = nlimbs == 0 ? Limb(0) : GC.@preserve m unsafe_load(m.d, nlimbs)
141✔
389
    highsp = Sampler(RNG, Limb(0):hm, N)
72✔
390
    nlimbsmax = max(nlimbs, abs(last(r).size), abs(first(r).size))
72✔
391
    return SamplerBigInt(first(r), m, nlimbs, nlimbsmax, highsp)
72✔
392
end
393

394
Sampler(::Type{RNG}, r::AbstractUnitRange{BigInt}, N::Repetition) where {RNG<:AbstractRNG} =
71✔
395
    SamplerBigInt(RNG, r, N)
396

397
rand(rng::AbstractRNG, sp::SamplerBigInt) =
8,071✔
398
    rand!(rng, BigInt(nbits = sp.nlimbsmax*8*sizeof(Limb)), sp)
399

400
function rand!(rng::AbstractRNG, x::BigInt, sp::SamplerBigInt)
8,078✔
401
    nlimbs = sp.nlimbs
8,078✔
402
    nlimbs == 0 && return MPZ.set!(x, sp.a)
8,078✔
403
    MPZ.realloc2!(x, sp.nlimbsmax*8*sizeof(Limb))
8,072✔
404
    @assert x.alloc >= nlimbs
8,072✔
405
    # we randomize x ∈ [0, m] with rejection sampling:
406
    # 1. the first nlimbs-1 limbs of x are uniformly randomized
407
    # 2. the high limb hx of x is sampled from 0:hm where hm is the
408
    #    high limb of m
409
    # We repeat 1. and 2. until x <= m
410
    hm = GC.@preserve sp unsafe_load(sp.m.d, nlimbs)
8,072✔
411
    GC.@preserve x begin
8,072✔
412
        limbs = UnsafeView(x.d, nlimbs-1)
8,072✔
413
        while true
8,072✔
414
            rand!(rng, limbs)
8,072✔
415
            hx = limbs[nlimbs] = rand(rng, sp.highsp)
8,072✔
416
            hx < hm && break # avoid calling mpn_cmp most of the time
8,072✔
417
            MPZ.mpn_cmp(x, sp.m, nlimbs) <= 0 && break
4✔
418
        end
×
419
        # adjust x.size (normally done by mpz_limbs_finish, in GMP version >= 6)
420
        while nlimbs > 0
8,074✔
421
            limbs[nlimbs] != 0 && break
8,072✔
422
            nlimbs -= 1
2✔
423
        end
2✔
424
        x.size = nlimbs
8,072✔
425
    end
426
    MPZ.add!(x, sp.a)
8,072✔
427
end
428

429

430
## random values from AbstractArray
431

432
Sampler(::Type{RNG}, r::AbstractArray, n::Repetition) where {RNG<:AbstractRNG} =
1,171,473✔
433
    SamplerSimple(r, Sampler(RNG, firstindex(r):lastindex(r), n))
434

435
rand(rng::AbstractRNG, sp::SamplerSimple{<:AbstractArray,<:Sampler}) =
1,935,754✔
436
    @inbounds return sp[][rand(rng, sp.data)]
437

438

439
## random values from Dict
440

441
function Sampler(::Type{RNG}, t::Dict, ::Repetition) where RNG<:AbstractRNG
327✔
442
    isempty(t) && throw(ArgumentError("collection must be non-empty"))
327✔
443
    # we use Val(Inf) below as rand is called repeatedly internally
444
    # even for generating only one random value from t
445
    SamplerSimple(t, Sampler(RNG, LinearIndices(t.slots), Val(Inf)))
311✔
446
end
447

448
function rand(rng::AbstractRNG, sp::SamplerSimple{<:Dict,<:Sampler})
2,702✔
449
    while true
6,156✔
450
        i = rand(rng, sp.data)
6,156✔
451
        Base.isslotfilled(sp[], i) && @inbounds return (sp[].keys[i] => sp[].vals[i])
6,156✔
452
    end
3,454✔
453
end
454

455
## random values from Set
456

457
Sampler(::Type{RNG}, t::Set{T}, n::Repetition) where {RNG<:AbstractRNG,T} =
56✔
458
    SamplerTag{Set{T}}(Sampler(RNG, t.dict, n))
459

460
rand(rng::AbstractRNG, sp::SamplerTag{<:Set,<:Sampler}) = rand(rng, sp.data).first
538✔
461

462
## random values from BitSet
463

464
function Sampler(RNG::Type{<:AbstractRNG}, t::BitSet, n::Repetition)
52✔
465
    isempty(t) && throw(ArgumentError("collection must be non-empty"))
52✔
466
    SamplerSimple(t, Sampler(RNG, minimum(t):maximum(t), Val(Inf)))
44✔
467
end
468

469
function rand(rng::AbstractRNG, sp::SamplerSimple{BitSet,<:Sampler})
228✔
470
    while true
1,248✔
471
        n = rand(rng, sp.data)
1,248✔
472
        n in sp[] && return n
1,248✔
473
    end
1,020✔
474
end
475

476
## random values from AbstractDict/AbstractSet
477

478
# we defer to _Sampler to avoid ambiguities with a call like Sampler(rng, Set(1), Val(1))
479
Sampler(RNG::Type{<:AbstractRNG}, t::Union{AbstractDict,AbstractSet}, n::Repetition) =
955✔
480
    _Sampler(RNG, t, n)
481

482
# avoid linear complexity for repeated calls
483
_Sampler(RNG::Type{<:AbstractRNG}, t::Union{AbstractDict,AbstractSet}, n::Val{Inf}) =
96✔
484
    Sampler(RNG, collect(t), n)
485

486
# when generating only one element, avoid the call to collect
487
_Sampler(::Type{<:AbstractRNG}, t::Union{AbstractDict,AbstractSet}, ::Val{1}) =
859✔
488
    SamplerTrivial(t)
489

490
function nth(iter, n::Integer)::eltype(iter)
851✔
491
    for (i, x) in enumerate(iter)
1,702✔
492
        i == n && return x
2,163✔
493
    end
1,312✔
494
end
495

496
rand(rng::AbstractRNG, sp::SamplerTrivial{<:Union{AbstractDict,AbstractSet}}) =
859✔
497
    nth(sp[], rand(rng, 1:length(sp[])))
498

499

500
## random characters from a string
501

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

506
# when generating only one char from a string, the specialized method below
507
# is usually more efficient
508
Sampler(RNG::Type{<:AbstractRNG}, str::AbstractString, ::Val{1}) =
24✔
509
    SamplerSimple(str, Sampler(RNG, 1:_lastindex(str), Val(Inf)))
510

511
isvalid_unsafe(s::String, i) = !Base.is_valid_continuation(GC.@preserve s unsafe_load(pointer(s), i))
4✔
512
isvalid_unsafe(s::AbstractString, i) = isvalid(s, i)
5✔
513
_lastindex(s::String) = sizeof(s)
8✔
514
_lastindex(s::AbstractString) = lastindex(s)
8✔
515

516
function rand(rng::AbstractRNG, sp::SamplerSimple{<:AbstractString,<:Sampler})::Char
8✔
517
    str = sp[]
8✔
518
    while true
9✔
519
        pos = rand(rng, sp.data)
9✔
520
        isvalid_unsafe(str, pos) && return str[pos]
9✔
521
    end
1✔
522
end
523

524

525
## random elements from tuples
526

527
### 1
528

529
Sampler(::Type{<:AbstractRNG}, t::Tuple{A}, ::Repetition) where {A} =
2✔
530
    SamplerTrivial(t)
531

532
rand(rng::AbstractRNG, sp::SamplerTrivial{Tuple{A}}) where {A} =
2✔
533
    @inbounds return sp[][1]
534

535
### 2
536

537
Sampler(RNG::Type{<:AbstractRNG}, t::Tuple{A,B}, n::Repetition) where {A,B} =
14✔
538
    SamplerSimple(t, Sampler(RNG, Bool, n))
539

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

543
### 3
544

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

548
function rand(rng::AbstractRNG, sp::SamplerSimple{Tuple{A,B,C}}) where {A,B,C}
2✔
549
    local r
2✔
550
    while true
2✔
551
        r = rand(rng, sp.data)
2✔
552
        r != 0x000fffffffffffff && break # _very_ likely
2✔
553
    end
×
554
    @inbounds return sp[][1 + r ÷ 0x0005555555555555]
2✔
555
end
556

557
### n
558

559
@generated function Sampler(RNG::Type{<:AbstractRNG}, t::Tuple, n::Repetition)
4,012✔
560
    l = fieldcount(t)
14✔
561
    if l < typemax(UInt32) && ispow2(l)
14✔
562
        :(SamplerSimple(t, Sampler(RNG, UInt32, n)))
8✔
563
    else
564
        :(SamplerSimple(t, Sampler(RNG, Base.OneTo(length(t)), n)))
14✔
565
    end
566
end
567

568
@generated function rand(rng::AbstractRNG, sp::SamplerSimple{T}) where T<:Tuple
2,010✔
569
    l = fieldcount(T)
11✔
570
    if l < typemax(UInt32) && ispow2(l)
11✔
571
        quote
5✔
572
            r = rand(rng, sp.data) & ($l-1)
2,002✔
573
            @inbounds return sp[][1 + r]
2,002✔
574
        end
575
    else
576
        :(@inbounds return sp[][rand(rng, sp.data)])
11✔
577
    end
578
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