Module: ULID::Generator

Included in:
ULID
Defined in:
lib/ulid/generator.rb

Constant Summary collapse

ENCODING =

Crockford’s Base32

'0123456789ABCDEFGHJKMNPQRSTVWXYZ'.bytes.freeze
RANDOM_BITS =
80
ENCODED_LENGTH =
26
BITS_PER_B32_CHAR =
5
ZERO =
'0'.ord
MASK =
0x1f

Instance Method Summary collapse

Instance Method Details

#generate(time = Time.now, suffix: nil) ⇒ Object

Generates a 128-bit ULID string.

Parameters:

  • time (Time) (defaults to: Time.now)

    (Time.now) Timestamp - first 48 bits

  • suffix (String) (defaults to: nil)

    (80 random bits) - the remaining 80 bits as hex encodable string



17
18
19
20
21
22
23
24
25
# File 'lib/ulid/generator.rb', line 17

def generate(time = Time.now, suffix: nil)
  (hi, lo) = generate_bytes(time, suffix: suffix).unpack('Q>Q>')
  if hi.nil? || lo.nil?
    raise ArgumentError, 'suffix string without hex encoding passed to ULID generator'
  end

  integer = (hi << 64) | lo
  encode(integer, ENCODED_LENGTH)
end

#generate_bytes(time = Time.now, suffix: nil) ⇒ Object

Generates a 128-bit ULID.

Parameters:

  • time (Time) (defaults to: Time.now)

    (Time.now) Timestamp - first 48 bits

  • suffix (String) (defaults to: nil)

    (80 random bits) - the remaining 80 bits as hex encodable string



30
31
32
33
34
35
36
37
38
39
# File 'lib/ulid/generator.rb', line 30

def generate_bytes(time = Time.now, suffix: nil)
  suffix_bytes =
    if suffix
      suffix.split('').map { |char| char.to_i(32) }.pack('C*')
    else
      SecureRandom.random_bytes(RANDOM_BITS / 8)
    end

  time_48bit(time) + suffix_bytes
end