ruby/string.rb
Sampo Kuokkanen 93e977936f Define String#ascii_only? and #valid_encoding? in Ruby
Get rid of the CFUNC overhead in String#ascii_only? and #valid_encoding?. Define them as leaf Primitive.cexpr! builtins in a new string.rb, following the pattern of numeric.rb.

This makes them 1.2x-1.4x faster across the interpreter, YJIT, and
ZJIT.

Move ZJIT's cfunc annotation for String#ascii_only? to annotate_builtin!, and add one for String#valid_encoding?.

Fix CI for builtin String#ascii_only?
2026-06-24 17:17:33 -04:00

26 lines
604 B
Ruby

class String
# call-seq:
# valid_encoding? -> true or false
#
# :include: doc/string/valid_encoding_p.rdoc
#
def valid_encoding?
Primitive.attr! :leaf
Primitive.cexpr! 'rb_str_valid_encoding_p(self)'
end
# call-seq:
# ascii_only? -> true or false
#
# Returns whether +self+ contains only ASCII characters:
#
# 'abc'.ascii_only? # => true
# "abc\u{6666}".ascii_only? # => false
#
# Related: see {Querying}[rdoc-ref:String@Querying].
def ascii_only?
Primitive.attr! :leaf
Primitive.cexpr! 'rb_str_is_ascii_only_p(self)'
end
end