* random.c (rand_int): prevent from GC.

git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@24353 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
This commit is contained in:
nobu 2009-08-02 05:20:51 +00:00
parent 3fcfe38c1a
commit e626e0bdec
3 changed files with 33 additions and 13 deletions

View File

@ -1,3 +1,7 @@
Sun Aug 2 14:20:43 2009 Nobuyoshi Nakada <nobu@ruby-lang.org>
* random.c (rand_int): prevent from GC.
Sat Aug 1 19:23:27 2009 NARUSE, Yui <naruse@ruby-lang.org> Sat Aug 1 19:23:27 2009 NARUSE, Yui <naruse@ruby-lang.org>
* string.c (tr_trans): change condition of singlebyte * string.c (tr_trans): change condition of singlebyte

View File

@ -855,27 +855,32 @@ add_to_begin(VALUE beg, VALUE offset)
static VALUE static VALUE
rand_int(struct MT *mt, VALUE vmax) rand_int(struct MT *mt, VALUE vmax)
{ {
long max;
unsigned long r;
if (FIXNUM_P(vmax)) { if (FIXNUM_P(vmax)) {
long max = FIX2LONG(vmax); max = FIX2LONG(vmax);
unsigned long r;
if (!max) return Qnil; if (!max) return Qnil;
r = limited_rand(mt, (unsigned long)(max < 0 ? -max : max) - 1); r = limited_rand(mt, (unsigned long)(max < 0 ? -max : max) - 1);
return ULONG2NUM(r); return ULONG2NUM(r);
} }
else { else {
struct RBignum *limit = (struct RBignum *)vmax; VALUE ret;
if (rb_bigzero_p(vmax)) return Qnil; if (rb_bigzero_p(vmax)) return Qnil;
if (!RBIGNUM_SIGN(limit)) { if (!RBIGNUM_SIGN(vmax)) {
limit = (struct RBignum *)rb_big_clone(vmax); vmax = rb_big_clone(vmax);
RBIGNUM_SET_SIGN(limit, 1); RBIGNUM_SET_SIGN(vmax, 1);
} }
limit = (struct RBignum *)rb_big_minus((VALUE)limit, INT2FIX(1)); vmax = rb_big_minus(vmax, INT2FIX(1));
if (FIXNUM_P((VALUE)limit)) { if (FIXNUM_P(vmax)) {
if (FIX2LONG((VALUE)limit) == -1) max = FIX2LONG(vmax);
return Qnil; if (max == -1) return Qnil;
return LONG2NUM(limited_rand(mt, FIX2LONG((VALUE)limit))); r = limited_rand(mt, max);
return LONG2NUM(r);
} }
return limited_big_rand(mt, limit); ret = limited_big_rand(mt, RBIGNUM(vmax));
RB_GC_GUARD(vmax);
return ret;
} }
} }

View File

@ -4,13 +4,24 @@ class TestRand < Test::Unit::TestCase
def assert_random_int(ws, m, init = 0) def assert_random_int(ws, m, init = 0)
srand(init) srand(init)
rnds = [Random.new(init)] rnds = [Random.new(init)]
ws.each do |w| rnds2 = [rnds[0].dup]
rnds3 = [rnds[0].dup]
ws.each_with_index do |w, i|
w = w.to_i w = w.to_i
assert_equal(w, rand(m)) assert_equal(w, rand(m))
rnds.each do |rnd| rnds.each do |rnd|
assert_equal(w, rnd.int(m)) assert_equal(w, rnd.int(m))
end end
rnds2.each do |rnd|
r=rnd.int(i...(m+i))
assert_equal(w+i, r)
end
rnds3.each do |rnd|
r=rnd.int(i..(m+i-1))
assert_equal(w+i, r)
end
rnds << Marshal.load(Marshal.dump(rnds[-1])) rnds << Marshal.load(Marshal.dump(rnds[-1]))
rnds2 << Marshal.load(Marshal.dump(rnds2[-1]))
end end
end end