random-integer should check for positive bounds

This commit is contained in:
Alex Shinn 2019-09-03 19:56:59 +08:00
parent 0bfc31a1e5
commit e9c8bed95a
2 changed files with 10 additions and 3 deletions

View file

@ -63,8 +63,12 @@ sexp sexp_rs_random_integer (sexp ctx, sexp self, sexp_sint_t n, sexp rs, sexp b
if (!sexp_random_source_p(self, rs)) if (!sexp_random_source_p(self, rs))
return sexp_type_exception(ctx, self, sexp_unbox_fixnum(sexp_opcode_arg1_type(self)), rs); return sexp_type_exception(ctx, self, sexp_unbox_fixnum(sexp_opcode_arg1_type(self)), rs);
if (sexp_fixnump(bound)) { if (sexp_fixnump(bound)) {
sexp_call_random(rs, m); if (sexp_unbox_fixnum(bound) <= 0) {
res = sexp_make_fixnum(m % sexp_unbox_fixnum(bound)); res = sexp_xtype_exception(ctx, self, "random bound must be positive", bound);
} else {
sexp_call_random(rs, m);
res = sexp_make_fixnum(m % sexp_unbox_fixnum(bound));
}
#if SEXP_USE_BIGNUMS #if SEXP_USE_BIGNUMS
} else if (sexp_bignump(bound)) { } else if (sexp_bignump(bound)) {
hi = sexp_bignum_hi(bound); hi = sexp_bignum_hi(bound);

View file

@ -23,5 +23,8 @@
(test-not (= x (rand 1000000))) (test-not (= x (rand 1000000)))
(random-source-state-set! rs state) (random-source-state-set! rs state)
;; (test x (rand 1000000)) ;; (test x (rand 1000000))
))) ))
(test 0 (random-integer 1))
(test-error (random-integer 0))
(test-error (random-integer -1)))
(test-end)))) (test-end))))