* random.c (rand_random, rb_f_rand): refactor, split condition
  expressions, and return in the precedence.

git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@54931 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
This commit is contained in:
nobu 2016-05-06 07:18:33 +00:00
Родитель 3377db6b32
Коммит a331eeb529
1 изменённых файлов: 24 добавлений и 42 удалений

Просмотреть файл

@ -1281,45 +1281,29 @@ static VALUE
rand_random(int argc, VALUE *argv, VALUE obj, rb_random_t *rnd) rand_random(int argc, VALUE *argv, VALUE obj, rb_random_t *rnd)
{ {
VALUE vmax, v; VALUE vmax, v;
double max = 0.0;
if (argc == 0) { if (rb_check_arity(argc, 0, 1) == 0) {
goto float_rand; return rb_float_new(random_real(obj, rnd, TRUE));
}
else {
rb_check_arity(argc, 0, 1);
} }
vmax = argv[0]; vmax = argv[0];
if (NIL_P(vmax)) { if (NIL_P(vmax)) return Qnil;
v = Qnil; if (!RB_TYPE_P(vmax, T_FLOAT)) {
v = rb_check_to_int(vmax);
if (!NIL_P(v)) return rand_int(obj, rnd, v, 1);
} }
else if (!RB_TYPE_P(vmax, T_FLOAT) && (v = rb_check_to_int(vmax), !NIL_P(v))) { v = rb_check_to_float(vmax);
v = rand_int(obj, rnd, v, 1); if (!NIL_P(v)) {
} const double max = float_value(v);
else if (v = rb_check_to_float(vmax), !NIL_P(v)) {
max = float_value(v);
if (max < 0.0) { if (max < 0.0) {
v = Qnil; return Qnil;
} }
else { else {
uint32_t a, b; double r = random_real(obj, rnd, TRUE);
double r; if (max > 0.0) r *= max;
return rb_float_new(r);
float_rand:
a = random_int32(obj, rnd);
b = random_int32(obj, rnd);
r = int_pair_to_real_exclusive(a, b);
if (max > 0.0) r *= max;;
v = rb_float_new(r);
} }
} }
else if ((v = rand_range(obj, rnd, vmax)) != Qfalse) { return rand_range(obj, rnd, vmax);
/* nothing to do */
}
else {
return Qfalse;
}
return v;
} }
static VALUE static VALUE
@ -1404,21 +1388,19 @@ random_equal(VALUE self, VALUE other)
static VALUE static VALUE
rb_f_rand(int argc, VALUE *argv, VALUE obj) rb_f_rand(int argc, VALUE *argv, VALUE obj)
{ {
VALUE v, vmax, r; VALUE vmax;
rb_random_t *rnd = rand_start(&default_rand); rb_random_t *rnd = rand_start(&default_rand);
if (rb_check_arity(argc, 0, 1) == 0) goto zero_arg; if (rb_check_arity(argc, 0, 1) && !NIL_P(vmax = argv[0])) {
vmax = argv[0]; VALUE v = rand_range(Qnil, rnd, vmax);
if (NIL_P(vmax)) goto zero_arg; if (v != Qfalse) return v;
if ((v = rand_range(Qnil, rnd, vmax)) != Qfalse) { vmax = rb_to_int(vmax);
return v; if (vmax != INT2FIX(0)) {
v = rand_int(Qnil, rnd, vmax, 0);
if (!NIL_P(v)) return v;
}
} }
vmax = rb_to_int(vmax); return DBL2NUM(genrand_real(&rnd->mt));
if (vmax == INT2FIX(0) || NIL_P(r = rand_int(Qnil, rnd, vmax, 0))) {
zero_arg:
return DBL2NUM(genrand_real(&rnd->mt));
}
return r;
} }
/* /*