Module: Base62

Included in:
SimpleStructuredSecrets
Defined in:
lib/sssecrets.rb

Overview

Based on github.com/steventen/base62-rb, with light modifications

Constant Summary collapse

KEYS =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
KEYS_HASH =
KEYS.each_char.with_index.each_with_object({}) do |(k, v), h|
  h[k] = v
end
BASE =
KEYS.length

Instance Method Summary collapse

Instance Method Details

#base62_decode(str) ⇒ Object

Decodes base62 string to a base10 (decimal) number.



26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/sssecrets.rb', line 26

def base62_decode(str)
  num = 0
  i = 0
  len = str.length - 1
  # while loop is faster than each_char or other 'idiomatic' way
  while i < str.length
    pow = BASE**(len - i)
    num += KEYS_HASH[str[i]] * pow
    i += 1
  end
  num
end

#base62_encode(num) ⇒ Object

Encodes base10 (decimal) number to base62 string.



12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/sssecrets.rb', line 12

def base62_encode(num)
  return "0" if num.zero?
  return nil if num.negative?

  str = ""
  while num.positive?
    # prepend base62 charaters
    str = KEYS[num % BASE] + str
    num /= BASE
  end
  str
end