Skip to content

Commit c754a60

Browse files
committed
RandIntGen: improve error message
This is @ivarne suggestion (cf. #8309 (comment)): move invariant checking in inner constructor, and emit a clearer error message when this fail.
1 parent 38bef62 commit c754a60

File tree

1 file changed

+8
-7
lines changed

1 file changed

+8
-7
lines changed

base/random.jl

+8-7
Original file line numberDiff line numberDiff line change
@@ -160,22 +160,23 @@ maxmultiplemix(k::Uint64) = k >> 32 == 0 ? uint64(maxmultiple(itrunc(Uint32, k))
160160
immutable RandIntGen{T<:Integer, U<:Unsigned}
161161
k::U # range length
162162
u::U # rejection threshold
163-
end
164-
# generators with 32, 128 bits entropy
165-
RandIntGen{U<:Union(Uint32, Uint128)}(T::Type, k::U) = RandIntGen{T, U}(k, maxmultiple(k))
166-
# mixed 32/64 bits entropy generator
167-
RandIntGen(T::Type, k::Uint64) = RandIntGen{T,Uint64}(k, maxmultiplemix(k))
168163

164+
function RandIntGen(k::U)
165+
@assert U in (Uint32, Uint64, Uint128) # respectively 32, mixed 32/64 and 128 bits of entropy
166+
k < 1 && error("No integers in the range [1, $k]. Did you try to pick an element from a empty collection?")
167+
new(k, U == Uint64 ? maxmultiplemix(k) : maxmultiple(k))
168+
end
169+
end
169170

170171
# generator API
171172
# randintgen(k) returns a helper object for generating random integers in the range 1:k
172-
randintgen{T<:Unsigned}(k::T) = k<1 ? error("range must be non-empty") : RandIntGen(T, k)
173+
randintgen{T<:Unsigned}(k::T) = RandIntGen{T, T}(k)
173174
# specialized versions
174175
for (T, U) in [(Uint8, Uint32), (Uint16, Uint32),
175176
(Int8, Uint32), (Int16, Uint32), (Int32, Uint32), (Int64, Uint64), (Int128, Uint128),
176177
(Bool, Uint32), (Char, Uint32)]
177178

178-
@eval randintgen(k::$T) = k<1 ? error("range must be non-empty") : RandIntGen($T, convert($U, k))
179+
@eval randintgen(k::$T) = RandIntGen{$T,$U}(convert($U, k))
179180
end
180181

181182
@inline function rand_lessthan{U}(u::U)

0 commit comments

Comments
 (0)