File: base64.rb

package info (click to toggle)
ruby-http-2 1.1.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 13,360 kB
  • sloc: ruby: 6,031; makefile: 4
file content (45 lines) | stat: -rw-r--r-- 937 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# frozen_string_literal: true

if RUBY_VERSION < "3.3.0"
  require "base64"
elsif !defined?(Base64)
  module HTTP2
    # require "base64" will not be a default gem after ruby 3.4.0
    module Base64
      module_function

      def encode64(bin)
        [bin].pack("m")
      end

      def decode64(str)
        str.unpack1("m")
      end

      def strict_encode64(bin)
        [bin].pack("m0")
      end

      def strict_decode64(str)
        str.unpack1("m0")
      end

      def urlsafe_encode64(bin, padding: true)
        str = strict_encode64(bin)
        str.chomp!("==") or str.chomp!("=") unless padding
        str.tr!("+/", "-_")
        str
      end
    end

    def urlsafe_decode64(str)
      if !str.end_with?("=") && str.length % 4 != 0
        str = str.ljust((str.length + 3) & ~3, "=")
        str.tr!("-_", "+/")
      else
        str = str.tr("-_", "+/")
      end
      strict_decode64(str)
    end
  end
end