From da10c47e49bd6e3aa121094031ce99057c0a6873 Mon Sep 17 00:00:00 2001 From: glass Date: Wed, 6 Nov 2013 02:50:28 +0000 Subject: * array.c (rb_ary_sample): use RARRAY_AREF() and RARRAY_PTR_USE() instead of RARRAY_PTR(). git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@43550 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- array.c | 65 ++++++++++++++++++++++++++++------------------------------------- 1 file changed, 28 insertions(+), 37 deletions(-) (limited to 'array.c') diff --git a/array.c b/array.c index ce27875a16..e708cb13dd 100644 --- a/array.c +++ b/array.c @@ -4516,7 +4516,7 @@ rb_ary_shuffle(int argc, VALUE *argv, VALUE ary) static VALUE rb_ary_sample(int argc, VALUE *argv, VALUE ary) { - VALUE nv, result, *ptr; + VALUE nv, result; VALUE opts, randgen = rb_cRandom; long n, len, i, j, k, idx[10]; long rnds[numberof(idx)]; @@ -4524,19 +4524,14 @@ rb_ary_sample(int argc, VALUE *argv, VALUE ary) if (OPTHASH_GIVEN_P(opts)) { randgen = rb_hash_lookup2(opts, sym_random, randgen); } - ptr = RARRAY_PTR(ary); len = RARRAY_LEN(ary); if (argc == 0) { - if (len == 0) return Qnil; - if (len == 1) { + if (len < 2) i = 0; - } - else { + else i = RAND_UPTO(len); - if ((len = RARRAY_LEN(ary)) <= i) return Qnil; - ptr = RARRAY_PTR(ary); - } - return ptr[i]; + + return rb_ary_elt(ary, i); } rb_scan_args(argc, argv, "1", &nv); n = NUM2LONG(nv); @@ -4549,28 +4544,23 @@ rb_ary_sample(int argc, VALUE *argv, VALUE ary) } k = len; len = RARRAY_LEN(ary); - ptr = RARRAY_PTR(ary); - if (len < k) { - if (n <= numberof(idx)) { - for (i = 0; i < n; ++i) { - if (rnds[i] >= len) { - return rb_ary_new2(0); - } - } + if (len < k && n <= numberof(idx)) { + for (i = 0; i < n; ++i) { + if (rnds[i] >= len) return rb_ary_new_capa(0); } } if (n > len) n = len; switch (n) { case 0: - return rb_ary_new2(0); + return rb_ary_new_capa(0); case 1: i = rnds[0]; - return rb_ary_new4(1, &ptr[i]); + return rb_ary_new_from_values(1, &RARRAY_AREF(ary, i)); case 2: i = rnds[0]; j = rnds[1]; if (j >= i) j++; - return rb_ary_new3(2, ptr[i], ptr[j]); + return rb_ary_new_from_args(2, RARRAY_AREF(ary, i), RARRAY_AREF(ary, j)); case 3: i = rnds[0]; j = rnds[1]; @@ -4580,10 +4570,9 @@ rb_ary_sample(int argc, VALUE *argv, VALUE ary) if (j >= i) l = i, g = ++j; if (k >= l && (++k >= g)) ++k; } - return rb_ary_new3(3, ptr[i], ptr[j], ptr[k]); + return rb_ary_new_from_args(3, RARRAY_AREF(ary, i), RARRAY_AREF(ary, j), RARRAY_AREF(ary, k)); } if (n <= numberof(idx)) { - VALUE *ptr_result; long sorted[numberof(idx)]; sorted[0] = idx[0] = rnds[0]; for (i=1; i