From 544e0c2cf735acd5c61bd3d26247350fc7a86691 Mon Sep 17 00:00:00 2001 From: Joao Fernandes Date: Thu, 2 Sep 2021 15:53:01 +0100 Subject: [PATCH 1/2] 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. --- lib/base64.rb | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/lib/base64.rb b/lib/base64.rb index 5c8df84..6b04998 100644 --- a/lib/base64.rb +++ b/lib/base64.rb @@ -82,8 +82,14 @@ def strict_decode64(str) # 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 From 39e22efa2bba48b4cdb447ee28c3957b38aa19ad Mon Sep 17 00:00:00 2001 From: Joao Fernandes Date: Thu, 2 Sep 2021 16:57:26 +0100 Subject: [PATCH 2/2] Simplify Thanks @nobu! --- lib/base64.rb | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/lib/base64.rb b/lib/base64.rb index 6b04998..de1e8c0 100644 --- a/lib/base64.rb +++ b/lib/base64.rb @@ -82,13 +82,7 @@ def strict_decode64(str) # 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.chomp!("==") or str.chomp!("=") unless padding str.tr!("+/", "-_") str end