diff options
| author | knu <knu@b2dd03c8-39d4-4d8f-98ff-823fe69b080e> | 2010-01-17 18:43:04 +0000 |
|---|---|---|
| committer | knu <knu@b2dd03c8-39d4-4d8f-98ff-823fe69b080e> | 2010-01-17 18:43:04 +0000 |
| commit | c162703062d9ab174381d7be388237a6fd03ebdd (patch) | |
| tree | 4e9af778498db93849b07e00a0738904a0a2037f /lib | |
| parent | 2bfe3c67d89f5e44aede5608f543e66140b04bae (diff) | |
* lib/base64.rb (Base64#{strict_encode64,strict_decode64,urlsafe_encode64,
urlsafe_decode64): New methods backported from 1.9.
git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/branches/ruby_1_8@26337 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
Diffstat (limited to 'lib')
| -rw-r--r-- | lib/base64.rb | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/lib/base64.rb b/lib/base64.rb index 264530aac3..9b901a7597 100644 --- a/lib/base64.rb +++ b/lib/base64.rb @@ -97,6 +97,40 @@ module Base64 [bin].pack("m") end + # Returns the Base64-encoded version of +bin+. + # This method complies with RFC 4648. + # No line feeds are added. + def strict_encode64(bin) + [bin].pack((len = bin.bytesize) > 45 ? "m#{len+2}" : "m").chomp + end + + # Returns the Base64-decoded version of +str+. + # This method complies with RFC 4648. + # ArgumentError is raised if +str+ is incorrectly padded or contains + # non-alphabet characters. Note that CR or LF are also rejected. + def strict_decode64(str) + return str.unpack("m").first if str.bytesize % 4 == 0 && + str.match(%r{\A[A-Za-z0-9+/]*([A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?\z}) && + (!$1 || $1 == $1.unpack('m').pack('m').chomp) + raise ArgumentError, 'invalid base64' + end + + # Returns the Base64-encoded version of +bin+. + # This method complies with ``Base 64 Encoding with URL and Filename Safe + # Alphabet'' in RFC 4648. + # The alphabet uses '-' instead of '+' and '_' instead of '/'. + def urlsafe_encode64(bin) + strict_encode64(bin).tr("+/", "-_") + end + + # Returns the Base64-decoded version of +str+. + # This method complies with ``Base 64 Encoding with URL and Filename Safe + # Alphabet'' in RFC 4648. + # The alphabet uses '-' instead of '+' and '_' instead of '/'. + def urlsafe_decode64(str) + strict_decode64(str.tr("-_", "+/")) + end + # _Prints_ the Base64 encoded version of +bin+ (a +String+) in lines of # +len+ (default 60) characters. # |
