[ruby/base64] Improve Base64.urlsafe_encode64 performance

Improves the method's performance when asked to remove padding.

str.delete!("=") iterates over the entire string looking for the equals
character, but we know that we will, at most, find two at the end of the
string.

https://github.com/ruby/base64/commit/544e0c2cf7
This commit is contained in:
Joao Fernandes 2021-09-02 15:53:01 +01:00 committed by Hiroshi SHIBATA
parent f7ffe9dbde
commit 05a28ce5b1

View File

@ -82,8 +82,14 @@ module Base64
# You can remove the padding by setting +padding+ as false.
def urlsafe_encode64(bin, padding: true)
str = strict_encode64(bin)
unless padding
if str.end_with?("==")
str.delete_suffix!("==")
elsif str.end_with?("=")
str.chop!
end
end
str.tr!("+/", "-_")
str.delete!("=") unless padding
str
end