From c9a5a71695af4596346e70f29dddb9ddb6106177 Mon Sep 17 00:00:00 2001 From: Takashi Kokubun Date: Tue, 12 Nov 2024 20:39:32 -0800 Subject: [PATCH] Move Array#select to Ruby Co-Authored-By: Aaron Patterson --- array.c | 6 ++++++ array.rb | 25 +++++++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/array.c b/array.c index ed7bc6ddb0..fbed28832f 100644 --- a/array.c +++ b/array.c @@ -6866,6 +6866,12 @@ ary_sample(rb_execution_context_t *ec, VALUE ary, VALUE randgen, VALUE nv, VALUE return result; } +static VALUE +ary_sized_alloc(rb_execution_context_t *ec, VALUE self) +{ + return rb_ary_new2(RARRAY_LEN(self)); +} + static VALUE ary_sample0(rb_execution_context_t *ec, VALUE ary) { diff --git a/array.rb b/array.rb index 67eafcc81b..ec204c2478 100644 --- a/array.rb +++ b/array.rb @@ -232,5 +232,30 @@ class Array self end end + + if Primitive.rb_builtin_basic_definition_p(:select) + undef :select + + def select # :nodoc: + Primitive.attr! :inline_block, :c_trace + + unless defined?(yield) + return Primitive.cexpr! 'SIZED_ENUMERATOR(self, 0, 0, ary_enum_length)' + end + + _i = 0 + value = nil + result = Primitive.ary_sized_alloc + while Primitive.cexpr!(%q{ ary_fetch_next(self, LOCAL_PTR(_i), LOCAL_PTR(value)) }) + result << value if yield value + end + result + end + + if Primitive.rb_builtin_basic_definition_p(:filter) + undef :filter + alias filter select + end + end end end