Module: Philiprehberger::BaseConvert::Base62

Defined in:
lib/philiprehberger/base_convert/base62.rb

Overview

Base62 encoding and decoding

Alphabet: 0-9A-Za-z (URL-safe, no special characters)

Constant Summary collapse

ALPHABET =
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
BASE =
ALPHABET.length
DECODE_MAP =
ALPHABET.each_char.with_index.to_h.freeze

Class Method Summary collapse

Class Method Details

.decode(string) ⇒ Integer

Decode a Base62 string to an integer

Parameters:

  • string (String)

    the Base62-encoded string

Returns:

  • (Integer)

    the decoded integer

Raises:

  • (Error)

    if the string contains invalid characters



39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/philiprehberger/base_convert/base62.rb', line 39

def self.decode(string)
  raise Error, 'input must be a non-empty string' if string.nil? || string.empty?

  num = 0
  string.each_char do |char|
    value = DECODE_MAP[char]
    raise Error, "invalid Base62 character: #{char}" if value.nil?

    num = (num * BASE) + value
  end

  num
end

.encode(integer) ⇒ String

Encode an integer to Base62

Parameters:

  • integer (Integer)

    the input integer (must be >= 0)

Returns:

  • (String)

    the Base62-encoded string

Raises:

  • (Error)

    if the input is negative



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/philiprehberger/base_convert/base62.rb', line 18

def self.encode(integer)
  raise Error, 'input must be a non-negative integer' unless integer.is_a?(Integer) && integer >= 0

  return ALPHABET[0] if integer.zero?

  result = []
  num = integer

  while num.positive?
    num, remainder = num.divmod(BASE)
    result << ALPHABET[remainder]
  end

  result.reverse.join
end