2019-05-03 06:17:27 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2017-08-22 23:46:15 +08:00
|
|
|
# Modified version of: https://github.com/steventen/base62-rb
|
|
|
|
|
|
|
|
module Base62
|
2024-11-06 06:27:49 +08:00
|
|
|
KEYS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
|
|
|
KEYS_HASH = KEYS.each_char.with_index.to_h
|
|
|
|
BASE = KEYS.length
|
2017-08-22 23:46:15 +08:00
|
|
|
|
|
|
|
# Encodes base10 (decimal) number to base62 string.
|
|
|
|
def self.encode(num)
|
|
|
|
return "0" if num == 0
|
|
|
|
return nil if num < 0
|
|
|
|
|
|
|
|
str = ""
|
|
|
|
while num > 0
|
2021-05-21 09:43:47 +08:00
|
|
|
# prepend base62 characters
|
2017-08-22 23:46:15 +08:00
|
|
|
str = KEYS[num % BASE] + str
|
|
|
|
num = num / BASE
|
|
|
|
end
|
|
|
|
str
|
|
|
|
end
|
|
|
|
|
|
|
|
# Decodes base62 string to a base10 (decimal) number.
|
|
|
|
def self.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
|
|
|
|
end
|