Module: KSUID::Base62
- Defined in:
- lib/ksuid/base62.rb
Overview
Converts between numbers and an alphanumeric encoding
We store and report KSUIDs as base 62-encoded numbers to make them lexicographically sortable and compact to transmit. The base 62 alphabet consists of the Arabic numerals, followed by the English capital letters and the English lowercase letters.
Constant Summary collapse
- CHARSET =
This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.
The character set used to encode numbers into base 62
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'- BASE =
This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.
The base (62) that this module encodes numbers into
CHARSET.size
Class Method Summary collapse
-
.compatible?(string) ⇒ Boolean
Checks whether a string is a base 62-compatible string.
-
.decode(ksuid) ⇒ Integer
Decodes a base 62-encoded string into an integer.
-
.encode(number) ⇒ String
Encodes a number (integer) as a base 62 string.
-
.encode_bytes(bytes) ⇒ String
Encodes a byte string or byte array into base 62.
Class Method Details
.compatible?(string) ⇒ Boolean
Checks whether a string is a base 62-compatible string
32 33 34 |
# File 'lib/ksuid/base62.rb', line 32 def self.compatible?(string) string.each_char.all? { |char| CHARSET.include?(char) } end |
.decode(ksuid) ⇒ Integer
Decodes a base 62-encoded string into an integer
46 47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/ksuid/base62.rb', line 46 def self.decode(ksuid) result = 0 ksuid.split('').each_with_index do |char, position| unless (digit = CHARSET.index(char)) raise(ArgumentError, "#{ksuid} is not a base 62 number") end result += digit * BASE**(ksuid.length - (position + 1)) end result end |
.encode(number) ⇒ String
Encodes a number (integer) as a base 62 string
70 71 72 73 74 75 |
# File 'lib/ksuid/base62.rb', line 70 def self.encode(number) chars = encode_without_padding(number) chars << padding if chars.empty? chars.reverse.join('').rjust(STRING_LENGTH, padding) end |
.encode_bytes(bytes) ⇒ String
Encodes a byte string or byte array into base 62
89 90 91 |
# File 'lib/ksuid/base62.rb', line 89 def self.encode_bytes(bytes) encode(Utils.int_from_bytes(bytes)) end |