ruby-changes:69731
From: Koichi <ko1@a...>
Date: Mon, 15 Nov 2021 15:59:15 +0900 (JST)
Subject: [ruby-changes:69731] a24eeee556 (master): Use `Primitive.mandatory_only?` for `Array#sample`
https://git.ruby-lang.org/ruby.git/commit/?id=a24eeee556 From a24eeee5567a14841b37d9a3428e14e4f3c45c07 Mon Sep 17 00:00:00 2001 From: Koichi Sasada <ko1@a...> Date: Sat, 13 Nov 2021 02:15:09 +0900 Subject: Use `Primitive.mandatory_only?` for `Array#sample` --- array.c | 8 +++++++- array.rb | 8 +++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/array.c b/array.c index be09151f435..240fb7e0f56 100644 --- a/array.c +++ b/array.c @@ -6337,7 +6337,7 @@ rb_ary_shuffle(rb_execution_context_t *ec, VALUE ary, VALUE randgen) https://github.com/ruby/ruby/blob/trunk/array.c#L6337 } static VALUE -rb_ary_sample(rb_execution_context_t *ec, VALUE ary, VALUE randgen, VALUE nv, VALUE to_array) +ary_sample(rb_execution_context_t *ec, VALUE ary, VALUE randgen, VALUE nv, VALUE to_array) { VALUE result; long n, len, i, j, k, idx[10]; @@ -6466,6 +6466,12 @@ rb_ary_sample(rb_execution_context_t *ec, VALUE ary, VALUE randgen, VALUE nv, VA https://github.com/ruby/ruby/blob/trunk/array.c#L6466 return result; } +static VALUE +ary_sample0(rb_execution_context_t *ec, VALUE ary) +{ + return ary_sample(ec, ary, rb_cRandom, Qfalse, Qfalse); +} + static VALUE rb_ary_cycle_size(VALUE self, VALUE args, VALUE eobj) { diff --git a/array.rb b/array.rb index 05ce60773e7..b9fa9844e69 100644 --- a/array.rb +++ b/array.rb @@ -58,6 +58,12 @@ class Array https://github.com/ruby/ruby/blob/trunk/array.rb#L58 # a.sample(random: Random.new(1)) #=> 6 # a.sample(4, random: Random.new(1)) #=> [6, 10, 9, 2] def sample(n = (ary = false), random: Random) - Primitive.rb_ary_sample(random, n, ary) + if Primitive.mandatory_only? + # Primitive.cexpr! %{ rb_ary_sample(self, rb_cRandom, Qfalse, Qfalse) } + Primitive.ary_sample0 + else + # Primitive.cexpr! %{ rb_ary_sample(self, random, n, ary) } + Primitive.ary_sample(random, n, ary) + end end end -- cgit v1.2.1 -- ML: ruby-changes@q... Info: http://www.atdot.net/~ko1/quickml/