Use encoding cache

This commit is contained in:
Douglas Eichelberger 2023-11-26 15:36:02 -08:00
parent ff43ec2793
commit 410fc64b7b

View File

@ -133,6 +133,12 @@ end
class String
BLANK_RE = /\A[[:space:]]*\z/.freeze
# This is a cache that is intentionally mutable
# rubocop:disable Style/MutableConstant
ENCODED_BLANKS_ = T.let(Hash.new do |h, enc|
h[enc] = Regexp.new(BLANK_RE.source.encode(enc), BLANK_RE.options | Regexp::FIXEDENCODING)
end, T::Hash[Encoding, Regexp])
# rubocop:enable Style/MutableConstant
# A string is blank if it's empty or contains whitespaces only:
#
@ -153,7 +159,7 @@ class String
begin
BLANK_RE.match?(self)
rescue Encoding::CompatibilityError
Regexp.new(BLANK_RE.source.encode(encoding), BLANK_RE.options | Regexp::FIXEDENCODING).match?(self)
T.must(ENCODED_BLANKS_[encoding]).match?(self)
end
end